r/PowerShell • u/lethal_dosage_13 • May 14 '19
PowerShell commands you can't live without.
Hello everyone, I'm traversing into the PowerShell realm after using Linux and want a little jumpstart. So I ask what commands can't you live without or wished you learned earlier to make your life easier? Thanks all for your help!
2
u/lethal_dosage_13 May 16 '19
Thank you all for the help! I'm woking to try and understand each of these commands and their uses. And, of course, compiling them in my own little cheat sheet! Once again, thank you so much for the help everyone!
94
u/ClayShooter9 May 15 '19
When beginning with PowerShell...can't stress enough how important it is to know and love:
Get-Help
Get-Member
Get-Type()
$Error[0] and $Error[0].Exception
21
4
4
u/PM_ME_UR_CEPHALOPODS May 15 '19
$Error[0] and $Error[0].Exception
I'll add $LastExitCode to this for native application scopes.
4
May 15 '19
Also, if you can't remember the exact commandlet, but you remember a word from it, then you can find it with wildcards:
help get*disk*will return anything that starts with get, and has "disk" in it somewhere
3
u/SemiNormal May 15 '19
Get-Help
I still hate it. It's humiliating.
6
u/Tonedefff May 15 '19
Sounds like you need to Get-Help for that anger problem.
5
2
u/Temptis May 15 '19
he ran
net helpand got redirected here. i can totaly relate with those anger issues.
0
May 15 '19
[deleted]
2
u/GnuInformation May 15 '19
to extend on that, I think other languages have it, but theres all kinds of .stuff() things you can do. but im not a programmer first, so I don't know what to call that exactly. I learned PS from monkeys.
5
May 15 '19
They're called member methods, because they're methods that are a member of an object.
Much like viewing a property of an object, methods within an instance of an object are called using dot notation. In PowerShell, many types (string, bool, etc.) are objects themselves, and come with their own member properties and methods, like string's Replace():
$String1 = "Hello world." $String1 = $String1.Replace(".", "!") Write-Host $String1 >> Hello world!Calling the following POSH will output all members of the $String1 variable:
$String1 | Get-Member1
27
u/Tonedefff May 15 '19
Welcome to the world o' PowerShell! In no particular order:
Exporting/importing objects to/from XML files:
$SomeObject | Export-Clixml ".\someObject.xml"
$SomeObject = Import-Clixml ".\someObject.xml"Exporting/importing to/from CSV files:
$Obj | Export-Csv ".\obj.csv" -NoTypeInformation
$Obj = Import-Csv ".\obj.csv"Foreach loop through objects:
foreach ($Object in $Objects) {
Write-Output "$($object.Name): $($object.Status)"
}(Also that syntax -- $(expression) or $($var.property) inside a string, is useful. If you just want to use a string variable's value inside a quoted string then you can do "My var: $strVar", but you can't do "My property: $var.property").
Dot-sourcing another script (basically plopping the contents of the other script wherever you put this line):
... # do stuff
. ".\Invoke-OtherFunctionality.ps1"
...The using statement (at the top of a script or module):
using namespace System.Collections.GenericSo you can do stuff like this:
$StrList = new [List[String]]::new(100)
$NumList = new [List[Int]]::new(100)...rather than:
$StrList = new [System.Collections.Generic.List[String]]::new(100)
$NumList = new [System.Collections.Generic.List[Int]]::new(100)Also those generic lists are useful and more efficient than arrays or ArrayLists:
$StrList = new [System.Collections.Generic.List[String]]::new(100)
foreach ($Object in $Objects) {
$StrList.Add($Object.Name)
}Creating custom PSObjects:
$MyObj = [PSObject] @{
prop1 = "value1"
prop2 = $SomeVar.property
}And using VS Code with the PowerShell extension is very useful, for debugging, source control, IntelliSense, etc. (PowerShell ISE is also good but MS is not adding features to it anymore, and I like VS Code better).
5
u/spyingwind May 15 '19
PSCustomObjectshould probably be used overPSObject. If I'm not mistaken Custom is faster. https://devops-collective-inc.gitbook.io/the-big-book-of-powershell-gotchas/new-object-psobject-vs.-pscustomobject1
u/Ta11ow May 15 '19
It's not that it's faster, it's that casting to [PSObject] is literally a no-op; that'll stay as a hashtable.
4
u/artemis_from_space May 15 '19
I would also suggest adding -delimiter ';' on export-csv so that if you double click the csv file it will open in Excel and be "properly formatted".
2
May 15 '19
-UseCulture
Mind you, if you want to send it around I'd recommend you open it in Excel and save as xlsx. Apparently my pc's culture uses comma, but my coworkers use semi-colon.
The .NET way to figure it out is
[System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator3
u/artemis_from_space May 15 '19
Unfortunately in PS Core I don't get anything returned. And if I use -UseCulture it looks like this.
$psobject = @([pscustomobject]@{'a'='4';'b'='9'},[pscustomobject]@{'a'='2';'b'='3'}) $psobject|Export-Csv -UseCulture test.csv Get-Content ./test.csv "a" "b" "4" "9" "2" "3"2
u/MonkeyNin May 16 '19
Which locales are you using?
$ get-culture $ get-culture | format-list -Property *2
u/Thirdbeat May 15 '19
Correct me if I'm wrong, but you don't need to select a size when instantiating a new list. With arrays you have to do it tho.
2
u/Tonedefff May 15 '19
You're correct -- you don't need to pass anything to a list when instantiating it. If you do, you're setting its initial capacity, which really only comes into play for performance reasons with really big lists (100,000s of elements). I just usually like to pass a capacity because it gives me / the reader an idea of about how many items I expect in the list.
2
u/PM_ME_UR_CEPHALOPODS May 15 '19
and
Ieveryone likes VS Code betterFTFY. My only gripe is the psreadline bug that truncates the clipboard at 50 characters when enumerating terminal shells in containers. That, uh, really kinda sucks.
9
u/ShaggyTDawg May 15 '19
Get-Content -Path "<path to log file here>" -Tail 50 -Wait
Let's you watch the contents of a log file in real time. Starts off by showing you the 50 most recent lines added, in case it's a very long log file.
It's equivalent to doing this in Linux
tail -n 50 -f <path to log file>
18
u/Lee_Dailey [grin] May 15 '19
howdy lethal_dosage_13,
things to look into ...
Get-Help
especiallyGet-Help *about*Get-Command
it takes wildcards, soGet-Command *csv*works nicely. that is especially helpful when you are seeking a cmdlet that works on a specific thing. Comma Separated Value files, for instance. [grin]Show-Command
that brings up a window that has all the current cmdlets and all their options ready for you to pick from.
it will also take another cmdlet, or advanced function, as a parameter to limit things to showing just that item.auto-completion
try starting a word and tapping the tab key. some nifty stuff shows up. [grin]intellisense
save something to a $Var and then try typing the $Var name plus a period to trigger intellisense. there are some very interesting things that show up as properties or methods.check out the builtin code snippets in the ISE
use <ctrl><j>, or Edit/Start-Snippets from the menu.assign something to a $Var & pipe that to
Get-Member$Test = Get-ChildItem -LiteralPath $env:TEMP$Test | Get-Memberassign something to a $Var and pipe it to Select-Object
$Test = Get-ChildItem -LiteralPath $env:TEMP$Test[0] | Select-Object -Property *
that will give you a smaller, more focused list of properties for the 1st item in the $Test array.assign something to a $Var & use
.GetType()on it$Test = Get-ChildItem -LiteralPath $env:TEMP$Test.GetType()$Test[0].GetType()
the 1st will give you info on the container $Var [an array object].
the 2nd will give you info on the zero-th item in the $Var [a DirectoryInfo object].Get-Verb
as withGet-Command, it will accept wildcards.
that will show you some interesting cmdlets. then use get-command to see what commands use those verbs. then use get-help to see what the cmdlets do.there really otta be a
Get-Noun, but there aint one. [sigh ...]Out-GridView
it's a bit more than you likely want just now, but it can accept a list of items, present them in a window, allow picking one or more of them, and finally send it out to the next cmdlet.
it's right fun to fiddle with ... and actually useful. [grin]
take care,
lee
5
u/gjpeters May 15 '19
PS noob here,
Would Get-Command -Noun <string[]> do what you are looking for in the missing Get-Noun command?
2
u/Lee_Dailey [grin] May 15 '19
howdy gjpeters,
that only gives commands using the indicated word. what i want is the same list of verbs that you get from
Get-Verb. you CAN derive it, but that aint the same as having a builtin cmdlet for it. something like this ...Get-Command -Name * | ForEach-Object { $_.Noun } | Sort-Object -Uniquei understand why they chose not to include it, but somewhat disagree. still, the good old
Get-Command *ThingToLookFor*will get me there ... [grin]take care,
lee2
u/thinkofitnow May 15 '19
Lee, I've been watching your work for a very long time. You're so courteous to newbies, and veterans alike. You're definitely an asset to the world of PS. You have saved my ass on a few occasions through the great ways you explain things. Thank you very much for your time and candor!
1
u/Lee_Dailey [grin] May 15 '19
howdy thinkofitnow,
thank you for the kind words! i appreciate it a quite a bit ... [grin]
take care,
lee
5
u/savehonor May 15 '19
For me, echoing /u/clayshooter9 a bit, i would say:
get-commandget-member$var.GetType()$var.Method.OverloadDefinitions
I also use:$singleitem = $collectionofitems | select -first 1
I can then do my testing/playing on that single item, then construct the loop, etc. later.
5
u/Reverent May 15 '19
you can also treat any collection as an array, IE: $collectionofitems[0] is the same thing.
EDIT: also fun fact, you can select the last (and work your way backwards) by doing $collectionofitems[-1]
2
u/ponytoaster May 17 '19
(and work your way backwards) by doing $collectionofitems[-1]
I am both impressed and disgusted by this...
4
u/Wtf909189 May 15 '19
Start-transcript. Think built in tee.
0
May 15 '19
[deleted]
1
u/Wtf909189 May 16 '19
You redirect a console apps output (usually just stdout) to tee, who in turn sends the output to the regular destination for stdout AND the redirected output (usually a file but it can be a device or some other output), otherwise you get no output when redirecting the stdout. Tee-object does this for one line of code, not your entire script, so in order to do this you would pipe your script, which if you intended on using the output objwct you may not get the intended results. Start-transcript copies what goes to stdout to a file and lets the output go to the original output device. So it is comparable to tee and why I said think tee. I never said it was the equivalent, but behaves enough like it that it is good enough for an explanation.
4
u/Sys_man May 15 '19
I'll add some things that I dont see listed so far:
gci env:To get a list of environment variables. like $env:COMPUTERNAME
The following :
winrm -quickconfigOn all machines that you want to remote in to/send commands to. Following on from that:
invoke-command -computername 'compname' { <your commands> }Using regex is easy:
if($variable -match 'regexp pattern'){
}
(also)
$re = [regex]'pattern'
if($variable -match $re){
}If you're iterating over a number of things and want to ignore errors:
-erroraction silentlycontinue Can be tacked on the end of commands. Also the following if you want to see everything that is going on:
-verbose Also the following if you want to test your command:
-whatifIf you want your output to be silent you can pipe out-null, or as I have started to do, use:
[void]set-command -parameter $thing2
u/bikeknife May 15 '19
$re = [regex]'pattern'
if($variable -match $re){
}
While -match returns Boolean, I'll add that in this operation that the native variable $matches will contain what did match. I use it quite a lot.
2
4
May 15 '19
Hi
Defenitely all these commands from other folks are pretty useful in addition i want you to check this cool one
OUT-GRIDVIEW
You simply pipe any objects to this command it will throw you in a beautiful gui.the other usefull ones are
Measure-Object
Group-object
Take care..
2
4
u/DragonDrew May 15 '19
Creating an array of objects based on other variables. This would have saved me so much time trying to format nice CSVs, tables and such.
$Array = @()
Foreach($Thing in $List) {
$Temp = New-Object -TypeName PSObject
$Temp | Add-Member -MemberType NoteProperty -Name 'Thing1' -Value $Thing
$Temp | Add-Member -MemberType NoteProperty -Name 'TheHashOfStuff' -Value $($Hashtable[$Thing])
$Array += $Temp
}6
u/TheXentar May 15 '19 edited May 16 '19
Just a tip:
[System.Collections.ArrayList]$Array = @() ForEach($thing in $List){ $Array.Add(New-Object -TypeName PSObject -Property @{ 'Thing1' = $thing 'TheHashofStuff' = $Hashtable[$thing] }) # Use .Add(), not += this will convert the ArrayList back to an Array and make things slow again (thanks Lee_Dailey for catching the +=) }An array where you're adding items can be way slower than using an arraylist (depending on how many items), this is because array doesn't have an add function so every time you add something to an array, underwater the array gets rebuild with all the items in the old array + the one extra item you're trying to add. Try:
[System.Array]$Array = @() Write-Host "Adding 20.000 items to an array took:" -ForegroundColor Green (Measure-Command -Expression { 1..20000 | ForEach-Object {$Array += $_} }).TotalSeconds.ToString() + " Seconds" [System.Collections.ArrayList]$ArrayList = @() Write-Host "`nAdding 20.000 items to an arraylist took:" -ForegroundColor Green (Measure-Command -Expression { (1..20000).ForEach({$ArrayList.Add($_) > $null}) }).TotalSeconds.ToString() + " Seconds"Also added a different way to build the psobject, imho it looks cleaner and it's less typing ftw.
5
u/omers May 15 '19
In PowerShell you can also just do this:
$Array = @(foreach ($x in $y) { $x })(Wrapping in
@()makes sure it's an array even if there's 0-1 returns.)It's faster even than using an array list or generic list.
1
u/TheXentar May 15 '19
That's really cool, did not know this. But if that foreach becomes more complex, I think it might be harder from a readability perspective. Still really nice. All them ways to Rome!
1
u/Snak3d0c May 17 '19 edited May 17 '19
Baader–Meinhof effect right here.
I just learned about this on Slack yesterday.I had this problem where i was filling up an array with text coming from a GUI objectSO$array += $textbox.text. For some reason it would concatenate all text into one long string.Then i went
$array += @($textbox.text)and it worked. An other workaround was to explicitly cast the variable as being an array like so :New-Object System.Collections.ArrayListand then using.add().3
u/DragonDrew May 17 '19
Mate, I love you. I always forget about
.Foreach()so I went back and changed one of my problem children. Recursively going through over 40,000 objects.From: 5m 33s
Do{ $FTSearch.NextRow() | Out-Null If([datetime]$($FTSearch.GetPropertyValue("LASTEDITDATE")) -gt $TimeSpan) { $temp = New-Object System.Object $temp | Add-Member # etc etc etc $collectionVariable.Add($temp) | Out-Null } $i++ } While($i -lt $FTSearch.GetRowsFound())To: 0m 49s
(1..$TotalVaulted).ForEach({ $FTSearch.NextRow() | OUT-NULL If([datetime]$($FTSearch.GetPropertyValue("LASTEDITDATE")) -gt $TimeSpan) { $temp = New-Object System.Object $temp | Add-Member # etc etc etc $collectionVariable.Add($temp) | Out-Null } $i++ })2
u/Lee_Dailey [grin] May 16 '19
howdy TheXentar,
on my win7, ps5.1 setup using
+=on an arraylist converts the collection to a standard array.i would go back and convert that
+=to.Add()... [grin]take care,
lee2
u/TheXentar May 16 '19
Hi Lee,
Oh wouw, I did it right in the second example but wrong in the first. Must have been sleeping. Good catch! It's the... "lemme type this up real quick" mess ups, one of the biggest reasons I would make a bad developer xD.
1
u/Lee_Dailey [grin] May 16 '19
howdy TheXentar,
one of the nice things about having others read your code is that they can catch things like that - hopefully before they hit production. [grin]
take care,
lee1
1
u/gpzj94 May 15 '19
Oh yeah, I forgot about Measure-Command. That's a really good one I should use more often to make sure things are running as efficiently as possible!
4
u/jollyfreek May 15 '19
one thing to learn is the difference between foreach and Foreach-Object. This will definitely come in handy in the future.
3
u/Mayki8513 May 17 '19
This is a good point, a lot of people assume that 'foreach' is an alias of 'ForEach-Object' which it is not.
4
u/purplemonkeymad May 15 '19
The thing that helped me most was not so much a command but a concept. Unlike bash (which is WYSIWYG with data,) powershell is a What you see is not always what you get (WYSINAWYG) language. You might see what appears to be a table of text with columns headers at the top, but that might not what is actually returned. The headers might not even be the same as the properties they represent. Or what looks like object display is just an actual text table.
Get-Member (alias gm) is the best tool for this job. Get-Process shows a few properties, but Get-process | gm shows you that there is a lot more you can use, and what type of object you are looking at.
6
u/spyingwind May 15 '19
([System.Net.Dns]::GetHostByName($env:computerName).HostName).Split('.')[1..2] -join '.'Installing software from N-Central is a pain in the ass. Their Powershell "processor" can't do basic things like Start-Process. They don't run powershell script under powershell, but use their own version that doesn't really work.
Any who, the above line of code will return the fqdn of AD. It allows us to know what domain we belong to and can use it to build something like below:
powershell -Command "([System.Net.Dns]::GetHostByName($env:computerName).HostName).Split('.')[1..2] -join '.'" > tmpFile
set /p curdomain= < tmpFile
del tmpFile
set installer=\\%curdomain%\sysvol\%curdomain%\scripts\installers\someinstaller.msiThe reason we can't use %userdnsdomain% is that we run everything under the device's AD account. It lets us not have to show any accidental prompts to a user, but still be able to grab files from AD servers, and it has full rights to the computer it self.
Other things like New-WebServiceProxy are great for talking to SOAP APIs. Export-Clixml and Import-Clixml are really useful when I need to cache some data or save settings to a file for later use.
Since learning Python, I really miss |, Where-Object and Select-Object for list manipulations.
2
u/omers May 15 '19
[System.Net.Dns]::GetHostByName($env:computerName).HostName).Split('.')[1..2] -join '.'Just a heads up,
(Get-WmiObject Win32_ComputerSystem).Domaindoes the same thing and will cover multi part domains like dom.example.com
3
3
u/MysticRyuujin May 15 '19
For performance avoid pipeline.
Use $null = command instead of command | Out-Null
Use $thing.Where({$_.name -eq "thing" }) vs $thing | Where-Object {$_.name -eq "Thing"}
3
u/dverbern May 15 '19
Definitely piping a variable to Get-Member is a winner for me, to discover the nature of the object you're working with.
Also, as others have pointed out, piping displayed results to Out-Gridview can be a way of impressing non-coders with the relative user friendliness of output.
However, some people have used a bunch of aliases in their suggestions on this post - maybe I'm just a weird obsessive non-expert, but I HATE aliases. Sure, I appreciate the crossover appeal when a PowerShell commandlet clearly does what its equivalent does in Linux and so makes sense to have an alias match its Linux equivalent, but for most purposes, I prefer people use the full command, simply because aliases are like acronyms, handy timesavers for some, but obscure hieroglyphics for others. We're all great typists I'd argue, so brevity shouldn't be a justification, especially when we can TAB-complete many of the verbs of commands. Anyway, that's just my personal view. I'm a crap coder anyway.
3
u/NotNotWrongUsually May 15 '19
Not a specific command, others have covered that. I've found that most people coming from a Linux background to Powershell need this message repeated a few times:
Commands emit objects not strings.
It is second nature for most Bash users to consider everything a string to be manipulated - stuff like trying to parse the output of Get-Date with regex. Don't do that. Pipe it to Get-Member instead and see what properties and methods it has, and use those.
Good luck on the journey!
2
2
u/allofthecoffeebeans May 15 '19
All of the above, but also
$list = Import-Csv -path “c:\temp” $results = Foreach ($thing in $list) { Do-stuff | select Parameters } $results | export-csv -path “c:\output” -notypeinformation
Probably my most used kind of loop these days. Gosh, I love powershell.
2
u/false404 May 15 '19
For quick one-liners, the % symbol is a handy shortcut to foreach. When it's used, the $_ variable is used to reference the current item.
Get-ChildItem | %{Get-Acl $_.name}
2
u/sapl84 May 15 '19
Definetly: Out-GridView! You can also combine it with -Passtrough to use the Cmdlet for filtering purposes, e.g.
Get-WindowsOptionalFeature | Out-GridView -PassThru | Enable-WindowsOptionalFeature
to select one or more Features which you want to enable but don't know the exact name of. Unfortunately it can't be used in Remote Sessions.
2
u/gpzj94 May 15 '19
A lot of people have said this already, but wanted to give my own input too!
'Get-Command' and 'Get-Member' and '| Select-Object -First 1' (and I guess I could throw 'Find-Module' in there too)are things that I learned early in the 2 PoSH/PoSH scripting in a month of lunches books. I didn't really use them until much later in my journey, but when it clicked as to why they are so helpful I'm not sure why I glossed past it in the earlier days.
So first off, Get-Command has made it so I have to Google a helluva lot less than before. You can do something like Get-Command -Verb Get -Module Vmware.PowerCLI but it supports the wildcard character so a lot of times I'm doing a search based loosely on what I'm looking for such as Get-Command *Custom*Profile* -Module Vmware.PowerCLI
As for Get-Member, that came as I finally started to understand what 'object oriented' meant. And really, it's not all that important to know but the reason I say that for myself was that I was constantly trying to figure out what property names were available when I'd do something like search for an AD Computer. There are a few ways you can use this, and of course the 'Powershell Way' would be to use the pipe |. So Get-ADUser -Filter * | Get-Member would give you those property names without returning all the data you'd have to sift through that you may not care about *yet*. A lot of times Powershell returns limited output unless you | Select-Object * to get all things, but then you're sifting through all the data to make it a bit harder to read. Plus Get-Member would give you methods you might not have realized were already built in before you make your own thing.
The '| Select-Object -First 1' is something I still use today, but I originally used it in place of 'Get-Method' before I realized what that was really helpful for. It's still so useful today because it helps return just a bit of data to know what to expect on a large dataset that may take some time to wait for all results to be returned. The example I used above could be made faster, and is how I'd normally run this to make it go faster, by doing 'Get-AdUser -filter * | Select-Object -First 1 | Get-Member'. Anyway, AD is my best example of wanting to use | Select-Object -First 1 (or -First 10 or any number there, you can also do -Last 1). So sometimes I want something about a user in AD but I don't remember what name means what. I'm not in there enough to remember all the things off hand, so a lot of times I do this to figure out which property is going to give me the OU. I just need to see the output of 1 object/User to see DistinguishedName gives me the OU in the format I'm looking for.
My honorable mention of 'Find-Module' also helps keep me in the shell and out of a browser by being able to search for modules that might assist in what I'm doing. I can get full details on who made it (because I'm not always trusting if it's a user contributed one, I can sort those out). I can get all the info I could from the Internet on it. Same with Get-Help command -Full, it's the same as the online help (although you may have to run 'Update-Help' to make sure you have the latest and greatest).
$variable.GetType() is also one people have mentioned here that is very useful, that I don't rely on too much but I'm typically only working on my own stuff, I could see that being handy if working on other people's scripts or in an environment I'm not familiar with yet.
2
u/PM_ME_UR_CEPHALOPODS May 15 '19
One that I'd wished I'd found earlier was the [switch] type. This allows simple binary state variables $true or $false for the variable. I use this mostly for switch parameters (like calling MyFunction -force , where $force is the switch) but overall it's very handy for terse flow control.
Great suggestions in this thread. /saved
2
u/noOneCaresOnTheWeb May 15 '19
get-command <command>| select module | Update-HelpSo you don't have to update all of the help.
2
2
2
May 15 '19
I'm traversing into the PowerShell realm after using Linux and want a little jumpstart.
Same here. Presenting:
Mike's Powershell Profile (and how to set up Windows console if you've been using *nix for 20 years)
2
u/tk42967 May 15 '19
Most of them are functions I have written. Find-user + <samaccountname> gets me the CN of a user, variations for computers and groups. This makes life easier when you are looking for an AD object buried in AD. I have another called get-groupmembership + <samaccountname> that generates a CSV of all AD groups that the account is a member of and drops it on my desktop. This is useful when I have to terminate a user. I can attach the CSV to the ticket and when they replace the person, ensure permissions are exactly the same.
I tend to do alot of repetitive stuff and have automated that as much as possible.
2
u/mr_mgs11 May 15 '19
Invoke-Command -computer computername {commands here}. I use this a shit ton on help desk. So much easier to just do stuff to a users computer instead of waiting for their input. Combined with Set-Content/Add-Content can do stuff like edit a exceptions.site file for java configuration.
2
u/ms-ch May 15 '19
Adding VLans to Network Adapters without having explicit Driver support (Needs Hyper-V installed):
Add-VMNetworkAdapter -ManagementOS -Name vlan300 -StaticMacAddress (Get-NetAdapter -Physical | Select -First 1 | %{$_.MacAddress}) -SwitchName "vlans"
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName vlan300 -Access -VlanID 3002
u/shobble May 15 '19
Set-PSReadlineOption -editMode emacs for (some of) the bindings I can't live without, like C-a/e for line motion, C-r for history search, etc.
1
2
u/Michelieus May 15 '19
I couldnt live without Where-Object or its aliases where and "?". Every language should implement something like that. Its really the most useful thing for filtering and such :3
3
u/RL5588 May 15 '19
I'm sure you're aware, but wanted to put this down for others to see as well:
"Filter to the left" is the unspoken rule
So if your command has a -
Filterswitch, use that to it's full extent to limit the processing of the command.EG:
Get-ADUser -Filter "SamAccountName -eq 'Michelieus'"Will be more efficient than
Get-ADUser -Filter "*" | Where-Object { SameAccountName -eq "Michelieus" }because the first command is only getting the user details of what you want; the second command is getting all the users in AD, and then grabbing the 'Michelieus' user out of that returned list.
2
u/infinit_e May 15 '19
I’ve known this for a while, as I use it with AD queries a lot but I’ve never known why it’s more efficient. Does
-Filterinstruct some other processes to do a search first before PowerShell receives any data to process?2
u/TheXentar May 15 '19
Your assumption is correct, in essence it's quite easy -Filter or -LDAPFilter just requests the data that matches the filter, whenever you use a pipeline means ALL objects that are being output by the previous cmdlet will be evaluated. And in some cases you need to use both because if the filter isn't able to give you the subset you're looking for you can then pipe them to a Where-Object to filter them further.
1
u/infinit_e May 15 '19
requests the data that matches the filter
So am I correct that some other system is doing the filtering before it gets to PowerShell? Like the -LDAPFilter instance, Active Directory is doing a internal search and then handing off the data that matches the request?
1
u/TheXentar May 15 '19
In case of AD cmdlets -filter just gets converted to an ldapfilter, so yes. For things like Get-ChildItem it works slightly different because of how Windows is builtup (everything has it's own APIs essentially) means the filter works differently depending on what you're trying to query. Also why you can't use Get-ChildItem -Filter with registry, the registry doesn't support filters/queries.
Hope this clears things up a bit.
1
u/RL5588 May 15 '19
Unfortunately, I don't know the gritty details.
I would love to know why as well to be honest, but I can only attest to my own testing.
So running
Measure-Commandto check filtering vs looping. Sometimes, loops can be faster, but in general filtering is.
1
u/greengrownTree May 15 '19
$PSVersionTable For if you are certain your code is correct yet ps still says it doesn’t know the cmdlet. Happened alot to me on an DC running Windows Server 2008 while testing on an Server 2012 or a Win10 Client.
1
1
1
u/Empath1999 May 15 '19
definitely get-help :/ followed by import-csv and export-csv and set-executionpolicy
1
1
u/Marco_jeez May 15 '19
When comparing files, I'm prone to using Get-Filehash -path XXXXX -Algorithm XXXX
0
May 15 '19
[deleted]
2
u/Mayki8513 May 17 '19
I used to use that, changed it to "| Set-Clipboard" I always get extra lines with "| clip" in powershell
25
May 15 '19
[removed] — view removed comment
10
u/Sharklad93 May 15 '19
Just want to add -- Get-Help does have -ShowWindow. A small text box will pop out loading the full Help document, examples and all, and it keeps your terminal clean. Also you can keep it minimized if you expect to need it again soon
5
1
u/smalls1652 May 15 '19
• Get-ChildItem / gci (like ls)
I use
lsanyway since it’s an alias. I only use it in the console, so I never use it in scripts.
18
u/motsanciens May 15 '19
Seemed popular last time I mentioned it: As you're composing a command, after typing the cmdlet name, type a hyphen and hit ctrl+space, which will show you all the parameters you have available for that cmdlet.