What are the hidden features of PowerShell?
feedback
|
locked by voretaq7♦ Feb 27 at 22:37
This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: FAQ.
|
Force Powershell functions to really return an array, even an empty array. Due to the way the @() syntax is implemented, functions may not always return an array as expected, e.g. the following code will return a $null and NOT an empty array. If you are testing code with
Simply prepending a
| ||||
feedback
|
|
Make your own custom functions and save them in your profile. You can build tons of useful functions without having to re-think it all every time a similar problem pops up. Edit your profile:
| ||||
feedback
|
|
Access any .net classes by using | ||||
|
feedback
|
|
Save files using different encoding than UTF-16 in ISE. The Powershell ISE defaults to saving all files as "Unicode Big Endian" (UTF-16) encoding. The following code will create a menu item in the ISE and assign a hotkey (default, Ctrl-Shift+E) to save the file in the current PowerShellISE tab using a specified encoding other than UTF-16. I set it to UTF-8, but you could use ASCII or something else if desired.
This trick is useful for avoiding certain issues with PowerShell scripts such as:
| |||||
feedback
|
|
Splatting. You can define a bunch of arguments in a Hashtable, and then use it as the parameters of a function.
| ||||
|
feedback
|
|
Moving mine to an answer so I don't feel bad making this a commwiki. Foreach loops:
Changedir to a UNC path:
Get running services: PS C:> get-service | where {$_.status -eq "running"}
| |||||||||||
feedback
|
|
This is more of a non-obvious hassle, but I once wrote a script to produce a CSV file as input for an older executable, ofiller.exe, which is used with Checkpoint firewalls. I was using output redirection: My powershell-created CSV file didn't work, where my hand-written test CSV file worked fine, even though the two files diff'ed identically. Only when I looked at the size of the files did I realize it was a Unicode Vs ASCII problem; the powershell CSV was twice as large. Piping my output to | ||||
feedback
|