20

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.

1
  • 1
    While you did find an answer to this specific issue, best practices would suggest functions rather "loose code" in a file, and even better, modules (.psm1 files). And try to avoid Invoke-Expression (see Invoke-Expression Considered Harmful ). Commented Aug 15, 2014 at 15:20

2 Answers 2

25

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"
Sign up to request clarification or add additional context in comments.

6 Comments

You have syntactic error in your answer - on this line $args += ("-b" 2) missing comma between "-b" and 2.
Chosen value 2 for parameter "-b" is not suitable because foo.ps1 contains ValidateSet with values 0,1.
Nice and clean :). Wasted allot of time trying to pass the args :/.
I have argument $dirPath with has spaces in path. Example: "D:\work dir\app". And it throws an error when passing like this: $args += ("-appDir", "$dirPath"). I get error: "The term 'D:\work' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct an d try again." How to pats path with spaces?
I did work around ('Set-Location' ..) suggested in this page stackoverflow.com/questions/18537098/…
|
10

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.