If you want to call a PowerShell script (Test2.ps1) with named parameters from a PowerShell script (Test1.ps1), you can’t use the & operator, like & “C:\Temp\Test2.ps1” –Computer L001 –User User1, because the & command is an alias for the Get-Command cmdlet. The Get-Command cmdlet executes precisely one command, see : http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-12-command-discovery-and-scriptblocks.aspx#the-call-operator-quotampquot, but you can use script blocks to execute more then one command or the Invoke-Expression cmdlet. I used the Invoke-Expression cmdlet to call a PowerShell script with named parameters from an other PowerShell script.

[Test1.ps1]

$command = “C:\Temp\Test2.ps1” –Computer L014 –User User1

Invoke-Expression $command

 

 

[Test2.ps1]

param
(
    [string]$Computer = "MyDefaultComputer",
    [string]$User = "MyDefaultUser"

)

$Computer

$User

 

 

[Result]

L014

User1

Tags:

4 Comments on How to call a PowerShell script with named parameters from a PowerShell (*.ps1) script

  1. pheiner says:

    Thanks for the example, short and to the point. Just started PS and not sure if a PowerGui bug but:
    $command =“C:\Temp\Test2.ps1” –Computer L014 –User User1

    Had to move the quote to the end to get this to work

    $command =“C:\Temp\Test2.ps1 –Computer L014 –User User1″

  2. Spencer says:

    Thanks! This was just what I was looking for. I did find what pheiner said to be true, though. I also had to quote the entire command.

  3. dragos says:

    Hi,
    What if you have a space char in the folder name? It doesn’t work anymore. I’m not able to find a solution for this.

  4. Marc Derksen says:

    If the path contains spaces, enclose it in single quotes and prefix it with &
    $command =”&’C:\Temp\Test 2.ps1′ –Computer L014 –User ‘User 1′”

Leave a Reply