Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell pass command line arguments

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

like image 859
icn Avatar asked Feb 07 '12 22:02

icn


People also ask

How do you pass a command line argument in PowerShell?

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.

How do I pass multiple command line arguments in PowerShell?

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.

What is param () in PowerShell?

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.

What does $() mean in PowerShell?

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.


2 Answers

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.

like image 179
Andy Arismendi Avatar answered Sep 19 '22 16:09

Andy Arismendi


You need to pass the arguments to the scriptblock:

Invoke-Command  -ScriptBlock $script -ArgumentList $args 
like image 41
xcud Avatar answered Sep 23 '22 16:09

xcud