5 Comments

NOTE
In PowerShell 7 you can just call the *.ps1 script with named parameters like you would call a function inside a *.ps1 file.

If you have a C:\Temp\MyScriptWithNamedParameters.ps1 file with the following content:

param (
[String] $buildOutputRootFolder= “C:\BuildOutput”,
[String] $deployFolder = “C:\Deploy”
)

Write-Host “buildOutputRootFolder = [$($buildOutputRootFolder)]”
Write-Host “deployFolder = [$($deployFolder)]”

You can call it on the commandline like:

Set-Location “C:\Temp”
.\MyScriptWithNamedParameters.ps1 -buildOutputRootFolder “C:\BuildOutputFolder” -deployFolder “C:\DeployFolder”

It will output:

buildOutputRootFolder = [C:\BuildOutputFolder]
deployFolder = [C:\DeployFolder]

OLD POST:
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

5 Replies to “How to call a PowerShell script with named parameters from a PowerShell (*.ps1) script”

  1. 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. 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. 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. 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts