PowerShell Error – “Select-Object : Cannot convert System.Object[] to one of the following types…”

tree

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:

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

The last command results into the following error message:
select_Error
Even if we change the literal values to strings and put the arguments in parentheses Select-Object still refuses to accept it:

$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")

I found two possible workarounds.

  1. Concatenation of the values
  2. 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

#concatenate
$props = echo Name ID Handle
Get-Process | select ($props + "VM" + "PM")
#using echo
Get-Process | select (echo $props VM PM)

shareThoughts


Photo Credit: S.Raj via Compfight cc

Advertisements

I'd love to hear what you think

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s