Here is my code :
$script={
Write-Host "Num Args:" $args.Length;
Write-Host $args[0]
}
Invoke-Command -ScriptBlock $script
When I run
powershell.exe .\test.ps1 one two three
I got
Num Args: 0
I thought I would get
Num Args: 3
One
Something am I missing?
Thanks
Execution the PowerShell Script from Command Line Parameters If you are using the command line then to execute the PowerShell script you could use the below format. powershell.exe -File "C:\example. ps1" arg1 arg2 arg3 # OR powershell.exe -File "C:\example.
To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.
Parameters can be created for scripts and functions and are always enclosed in a param block defined with the param keyword, followed by opening and closing parentheses. param() Inside of that param block contains one or more parameters defined by -- at their most basic -- a single variable as shown below.
Subexpression operator $( ) For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.
You actually have two scopes there. The script level and the script block level. $args.Length
and $args[0]
will have what you are expecting at the Invoke-Command
level. Inside the script block there is another scope for $args
. To get the args from the command line all the way into the script block you'll need to re-pass them from Invoke-Command -ArgumentList $args
.
You need to pass the arguments to the scriptblock:
Invoke-Command -ScriptBlock $script -ArgumentList $args
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With