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
Here's a simple solution:
Here's output:
If you're willing to skip Invoke-Command altogether...
Your script could look like this:
And you would call it like this:
D:\test.ps1 -P1 1 -P2 2 -P3 3
If you are trying to use the -FilePath with named parameters (-P1 1 -P2 2), then I found this will work. Use a script block to run the file, instead of the using -FilePath.
Use a hashtable :
One option:
The code by mjolinor works great, but it took me several minutes to understand it.
The code makes a simple thing - generates a content of script block with built-in parameters:
Then this script block is passed to Invoke-Command.
To simplify the code:
Let's make a basic C# implementation:
The code generates a temporary script and executes it.
Example script: