更新时间:2023-01-08 19:06:54
您无需Start-Process
即可从另一个PowerShell脚本运行一个PowerShell脚本.只需使用所需的任何参数调用第二个脚本即可:
You don't need Start-Process
to run one PowerShell script from another PowerShell script. Simply call the second script with whatever parameters you want:
# script1.ps1
$loc = Read-Host 'Enter location'
C:\path\to\script2.ps1 $loc 'other parameter'
在第二个脚本中,例如可以通过$args
数组访问参数列表:
In the second script the argument list can be accessed for instance via the $args
array:
# script2.ps1
Write-Host $args[0]
Write-Host $args[1]
您还可以这样定义命名参数:
You could also define named parameters like this:
# script2.ps1
Param($Location, $Foo)
Write-Host $Location
Write-Host $Foo
或更像这样(更完整):
or (more complete) like this:
# script2.ps1
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Location,
[Parameter(Mandatory=$false)]
[string]$Foo
)
Write-Host $Location
Write-Host $Foo
定义命名参数使您可以传递参数而不必担心它们的顺序:
Defining named parameters allows you to pass arguments without having to worry about their order:
C:\path\to\script2.ps1 -Foo 'other parameter' -Location $loc
or to have parameters automatically validated without having to implement the checks in the function body:
# script2.ps1
Param(
[ValidateSet('a', 'b', 'c')]
[string]$Location,
[ValidatePattern('^[a-z]+$')]
[string]$Foo
)
Write-Host $Location
Write-Host $Foo
如果传递的参数比定义的命名参数多,则这些附加参数将存储在$args
数组中:
If more arguments are passed than named parameters were defined those additional arguments are stored in the $args
array:
PS C:\> cat test.ps1
Param($Foo)
Write-Host $Foo
Write-Host $args[0]
PS C:\> .\test.ps1 'foo' 'bar'
foo
bar
有关更多信息,请参见 Get-Help about_Functions_Advanced_Parameters
.
For more information see Get-Help about_Functions_Advanced_Parameters
.