Powershell: Reference a property that contains a space
PowershellCsvPowershell Problem Overview
I am importing a CSV file using powershell.
The problem is, the title of one of the columns is "Remaining Time - Hours". So I'm getting a sequence of objects, and it's actually assigned the property "Remaining Time - Hours".
What is the syntax to refer to this property?
eg
Import-Csv AllOpenCases.csv | % {$case = $_ }
$case | get-member
returns
Category : Inquiry
Starred : No
Remaining Time - Hours : 22.5
but if I type
$case.Remaining Time - Hours
I get "Unexpected token 'Time' in expression or statement"
Powershell Solutions
Solution 1 - Powershell
Properties with embedded spaces have to be quoted when they're referenced:
$case."Remaining Time - Hours"
Solution 2 - Powershell
Just to add, the property name can itself be a variable e.g.:
PS> $o = new-object psobject -prop @{'first name' = 'John'; 'last name' = 'Doe'}
PS> $o
last name first name
--------- ----------
Doe John
PS> $prop = 'first name'
PS> $o.$prop
John
Solution 3 - Powershell
Or you can also wrap that property in { }. Like this:
$case.{Remaining Time - Hours}
Solution 4 - Powershell
FWIW, if it gets to be pain to code with, you can add an alias property:
$caseprops = @"
Category = Inquiry
Starred = No
Remaining Time - Hours = 22.5
"@
$case = new-object psobject -property ($caseprops | convertfrom-stringdata)
$case | add-member aliasproperty "RT" "Remaining Time - Hours"
$case | fl
Remaining Time - Hours : 22.5
Starred : No
Category : Inquiry
RT : 22.5