Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call PowerShell script with arguments from another powershell script

Tags:

powershell

How do you call a PowerShell script which takes named arguments from within 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

Error:

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 latest attempt - I've tried multiple methods from googling none seem to work.

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

like image 766
Chris L Avatar asked Aug 15 '14 07:08

Chris L


2 Answers

After posting the question I stumbled upon the answer. For completeness here it 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"
like image 100
Chris L Avatar answered Oct 01 '22 13:10

Chris L


Here is something that might help future readers:

foo.ps1:

param ($Arg1, $Arg2)

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

bar.ps1:

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

That's it !

like image 36
phi1.614 Avatar answered Oct 01 '22 13:10

phi1.614