我有問題將數組作爲參數從CMD傳遞給PowerShell腳本。 這裏的PS碼的例子:將數組作爲參數從CMD傳遞給PowerShell給出問題
[CmdletBinding()]
Param(
[string[]]$serverArray,
)
$serviceName = 'service1'
function getState {
Process {
$serverArray
foreach ($server in $serverArray) {
$servState = (Get-WmiObject Win32_Service -ComputerName $server -Filter "name='$serviceName'").State
}
}
getState
我如何調用腳本CMD:
powershell -file .\script.ps1 -serverArray Server1,Server2
我得到一個錯誤,因爲$serverArray
沒有傳遞一個數組:
Server1,Server2 Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At C:\script.ps1:58 char:29 + $servState = (Get-WmiObject <<<< Win32_Service -ComputerName $server -Filter "name='$serviceName'").State + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
如果我從它運行的PowerShell窗口運行相同的命令,因爲腳本接受$serverArray
作爲數組:
powershell script.ps1 "Server1,Server2"
而且:
.\script.ps1 -serverArray Server1,Server2
Server1 Server2
'-file' - >'-command' – PetSerAl
請務必試運行[MCVE]代碼,以確保它母鹿不會引入額外的錯誤,如參數定義中的虛假尾隨逗號和函數缺失的右括號。 –