Passing an array as parameter from CMD to PowerShell give problems

0

I have problems to pass an array to PowerShell script as parameter from CMD. Here an example of the PS code:

[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

How I call script from CMD:

powershell -file .\script.ps1 -serverArray Server1,Server2

I get an error because $serverArray is not passed an array:

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

If I run the same command from a PowerShell window it works because the script accepts $serverArray as an array:

.\script.ps1 -serverArray Server1,Server2
Server1
Server2
powershell
cmd
asked on Stack Overflow Oct 7, 2017 by karnak • edited Oct 8, 2017 by Ansgar Wiechers

2 Answers

1

CMD doesn't know anything about PowerShell arrays. You can pass the server list as individual tokens

powershell -File .\script.ps1 Server1 Server2

and use the automatic variable $args instead of a named parameter in your script:

foreach ($server in $args) {
    ...
}

or you can split the value of the parameter at commas in the body:

[CmdletBinding()]
Param(
    [string]$Servers
)

$serverArray = $Servers -split ','
answered on Stack Overflow Oct 8, 2017 by Ansgar Wiechers
0

You can run this from command prompt: powershell script.ps1 "Server1,Server2"

And if you add more parameters to your script :

powershell script.ps1 "Server1,Server2" "parameter2 argument" "parameter3 argument"

answered on Stack Overflow Oct 7, 2017 by Ravi • edited Oct 7, 2017 by Dmitry

User contributions licensed under CC BY-SA 3.0