Reputation: 23
I'm actually writing a plugin with powershell for a monitoring solution.
This monitoring solution runs the powershell skript from the command line cmd.
One of the input parameters is a string array but it looks like cmd can't hand over the array to the powershell.
Here a example script that I've wrote to explain you the problem:
param (
[array]$myarray
)
Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray
When I run this script from a powershell console my output is right:
.\Test-Script.ps1 -myarray bla1, bla2
My array is a System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2
now I run the same from the cmd and the array is not interpreted as it should:
powershell.exe -file Test-Script.ps1 -myarray bla1, bla2
My array is a System.Object[]
How much value do I have in my array? 1
My content is bla1,
My question is now how to commit the array to the powershell script? I have tried quite every thing.... Escaping with ^ , brackets, sing quotes , double quotes and so on. but nothing helped...
I am thankful for every hint :)
Upvotes: 2
Views: 2348
Reputation: 21
When calling the script from CMD, do:
powershell.exe -command ".\Test-Script.ps1 -myarray bla1, bla2"
Results in:
My array is a System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2
From my experience, using the command argument rather than the file argument, then wrapping the entire command in quotes causes things to behave more like you'd expect them to as if you were running from the PoSh console.
Also, if you want to make your param statement specific to a string, or array of strings, you can write the statement like:
param (
[string[]]$myarray
)
Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray
The result is:
My array is a System.String[]
How much value do I have in my array? 2
My content is bla1 bla2
As you have it now, it will accept an array with elements of any type, depending on your application, you may want it to only accept arrays with elements of a specific type. Defining an array like [typename[]]
specifies that it's an array with elements of typename
.
Upvotes: 2