简体   繁体   中英

Passing parameter to command in powershell

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

I think what you want to do here is

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

which will pass them as an array.

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) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM