Where’s the value

PowerShell is object based – its the one fact that is mentioned in very introduction to PowerShell – and its the use of objects that gives PowerShell its reach and power.

The use of objects has one tiny drawback. When you want the actual value of a property you have to do slightly more work.

This is representative of a typical PowerShell expression

£> Get-Process powershell | select Path

Path
----
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Now if you want the value of path itself to use elsewhere you have to do one of three things:

£> $proc = Get-Process powershell
£> $proc.Path
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

OR

£> $path = Get-Process powershell | select -ExpandProperty Path
£> $path
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

OR

£> $proc = (Get-Process powershell | select Path).path
£> $path
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

The first one gives you an object to work with.  If you want other properties you can access them later.

The other two options give you a variable containing just the information you need – the value of the Path property.

Which one works best  - depends on what you are doing.  I use all three techniques on  a regular basis though tend to prefer using option 2 to option 3 – mainly because I find it easier to read when I come back to the script weeks, months or even years later.

Leave a Reply