Passing parameter to command in powershell

0

Could you tell my why this works:

Get-WmiObject Win32_LogicalDisk -ComputerName xxx, yyy, zzz -Filter "DeviceID='C:'" | Select-Object pscomputername, @{Name="Size GB";Expression={ "{0:N2}" -f ($_.Size / 1GB)}}, @{Name="Free GB";Expression={ "{0:N2}" -f ($_.FreeSpace / 1GB) }}

And this is not:

$Machines = "xxx, yyyy, zzz"
Get-WmiObject Win32_LogicalDisk -ComputerName $Machines -Filter "DeviceID='C:'" | Select-Object pscomputername, @{Name="Size GB";Expression={ "{0:N2}" -f ($_.Size / 1GB)}}, @{Name="Free GB";Expression={ "{0:N2}" -f ($_.FreeSpace / 1GB) }}

?

I'm really confused. I tried to change $Machines to:

xxx, yyy, zzz
@(xxx, yyy, zzz)

The error I'm getting is:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At C:\AppSupport\ps\freespace\freespace.ps1:10 char:1 + Get-WmiObject Win32_LogicalDisk -ComputerName $Machines -Filter "DeviceID='C:'" ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException

powershell
parameter-passing
asked on Stack Overflow Mar 16, 2016 by Michal • edited Mar 16, 2016 by Frode F.

2 Answers

2

I think what you want to do here is

$Machines = @("xxx", "yyy", "zzz")

which will pass them as an array.

answered on Stack Overflow Mar 16, 2016 by pholtz
1

Because you defined all three names as a single string.

$Machines = "xxx, yyyy, zzz"

This is the same as calling Get-WmiObject for the computer "xxx, yyyy, zzz"

xxx, yyy, zzz and @(xxx, yyy, zzz) doesn't work because you didn't quote them, so PowerShell tries to use them as an expression and save the results (calling the function/cmdlet/application with name xxx etc.). That's why it returns ex.

$machines = xxx, yyy, zzz
At line:1 char:16
+ $machines = xxx, yyy, zzz
+                ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument

You need to split them into an array of three strings. This should work

$Machines = "xxx", "yyyy", "zzz"
Get-WmiObject Win32_LogicalDisk -ComputerName $Machines -Filter "DeviceID='C:'" |
Select-Object pscomputername, @{Name="Size GB";Expression={ "{0:N2}" -f ($_.Size / 1GB)}}, @{Name="Free GB";Expression={ "{0:N2}" -f ($_.FreeSpace / 1GB) }}
answered on Stack Overflow Mar 16, 2016 by Frode F.

User contributions licensed under CC BY-SA 3.0