Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Pass Named parameters to ArgumentList

I have a PowerShell script that accepts 3 named parameters. Please let me know how to pass the same from command line. I tried below code but same is not working. It assigns the entire value to P3 only. My requirement is that P1 should contain 1, P2 should 2 and P3 should be assigned 3.

Invoke-Command -ComputerName server -FilePath "D:\test.ps1" -ArgumentList  {-P1 1 -P2 2 -P3 3}

Ihe below is script file code.

Param (
    [string]$P3,
    [string]$P2,
    [string]$P1
)
Write-Output "P1 Value :" $P1
Write-Output "P2 Value:" $P2
Write-Output "P3 Value :" $P3
like image 838
Parveen Kumar Avatar asked Jan 06 '15 08:01

Parveen Kumar


People also ask

How do I pass a named argument to a PowerShell script?

Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.

How do I pass multiple parameters to a PowerShell script?

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.

How do I set parameters in PowerShell?

To create a parameter set, you must specify the ParameterSetName keyword of the Parameter attribute for every parameter in the parameter set. For parameters that belong to multiple parameter sets, add a Parameter attribute for each parameter set.


2 Answers

One option:

$params = @{
P1 = 1
P2 = 2 
P3 = 3
}

$ScriptPath = 'D:\Test.ps1'

$sb = [scriptblock]::create(".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)")

Invoke-Command -ComputerName server -ScriptBlock $sb
like image 153
mjolinor Avatar answered Oct 19 '22 05:10

mjolinor


Here's a simple solution:

[PowerShell]::Create().AddCommand('D:\test.ps1').AddParameters(@{ P1 = 1; P2 = 2; P3 = 3 }).Invoke()

Here's output:

PS C:\Windows\system32> [PowerShell]::Create().AddCommand('D:\test.ps1').AddParameters(@{ P1 = 1; P2 = 2; P3 = 3 }).Invoke()
P1 Value :
1
P2 Value:
2
P3 Value :
3
like image 44
Haoshu Avatar answered Oct 19 '22 03:10

Haoshu