Call a PowerShell script with arguments from another powershell script

What do you call a PowerShell script that takes named arguments from a PowerShell script?

foo.ps1:

param( [Parameter(Mandatory=$true)][String]$a='', [Parameter(Mandatory=$true)][ValidateSet(0,1)][int]$b, [Parameter(Mandatory=$false)][String]$c='' ) #stuff done with params here 

bar.ps1

 #some processing $ScriptPath = Split-Path $MyInvocation.InvocationName $args = "-a 'arg1' -b 2" $cmd = "$ScriptPath\foo.ps1" Invoke-Expression $cmd $args 

Mistake:

 Invoke-Expression : A positional parameter cannot be found that accepts argument '-a MSFT_VirtualDisk (ObjectId = "{1}\\YELLOWSERVER8\root/Microsoft/Windo...).FriendlyName -b 2' 

This is my last attempt - I tried several methods from googling that don't seem to work.

If I run foo.ps1 from the shell terminal as ./foo.ps1 -a 'arg1' -b 2 , it works as expected.

+10
powershell
source share
2 answers

After posting the question, I came across an answer. For completeness, here is:

bar.ps1:

 #some processing $ScriptPath = Split-Path $MyInvocation.InvocationName $args = @() $args += ("-a", "arg1") $args += ("-b", 2) $cmd = "$ScriptPath\foo.ps1" Invoke-Expression "$cmd $args" 
+19
source share

Here are some things that will help future readers:

foo.ps1:

 param ($Arg1, $Arg2) 

Be sure to place the "param" code at the top before any executable code.

bar.ps1:

 & "path to foo\foo.ps1" -Arg1 "ValueA" -Arg2 "ValueB" 

Here it is!

0
source share

All Articles