I came across a bug (at least I would assume this a bug) in PowerShell while using the Select-Object (alias select) cmdlet in conjunction with a mix of literal and variable arguments for the Property parameter (attempting to use Get-ChangeLog with a multiple column identifier). Select-Object’s Property parameter accepts either an array of objects, or a hashtable of name/expression pairs as arguments. Let’s look at an example: [code language=”powershell”] Get-Help select -Parameter Property #usage with literal argument Get-Process | select Name, ID, Handle, VM, PM #usage with a variable argument $props = “Name”, “ID”, “Handle” Get-Process | select $props #mixed usage of literal and a variable argument Get-Process | select $props, VM, PM [/code]
The last command results into the following error message:
Even if we change the literal values to strings and put the arguments in parentheses Select-Object still refuses to accept it:
[code language=”powershell”]
$props = “Name”, “ID”, “Handle”
#check the type of the parameter value
($props, “VM”, “PM”).GetType().FullName
#should work, but still doesn’t
Get-Process | select ($props, “VM”, “PM”)
[/code]
I found two possible workarounds.
-
Concatenation of the values
-
Using Write-Output (alias echo) to produce an array of strings (I like that one more)
See also PowerShell tricks- Build an array of strings without quotation marks [code language=”powershell”] #concatenate $props = echo Name ID Handle Get-Process | select ($props + “VM” + “PM”) #using echo Get-Process | select (echo $props VM PM) [/code]