Powershell 如何将参数传递给通过启动作业调用的PS脚本?
我想使用start job运行需要参数的.ps1脚本。以下是脚本文件:Powershell 如何将参数传递给通过启动作业调用的PS脚本?,powershell,parameter-passing,automatic-variable,Powershell,Parameter Passing,Automatic Variable,我想使用start job运行需要参数的.ps1脚本。以下是脚本文件: #Test-Job.ps1 Param ( [Parameter(Mandatory=$True)][String]$input ) $output = "$input to output" return $output 下面是我运行它的方式: $input = "input" Start-Job -FilePath 'C:\PowerShell\test_job.ps1' -
#Test-Job.ps1
Param (
[Parameter(Mandatory=$True)][String]$input
)
$output = "$input to output"
return $output
下面是我运行它的方式:
$input = "input"
Start-Job -FilePath 'C:\PowerShell\test_job.ps1' -ArgumentList $input -Name "TestJob"
Get-Job -name "TestJob" | Wait-Job | Receive-Job
Get-Job -name "TestJob" | Remove-Job
这样运行,它将返回“to output”,因此在作业运行的脚本中$input为null
我见过其他类似的问题,但它们大多使用-Scriptblock代替-FilePath。通过启动作业向文件传递参数是否有不同的方法?tl;dr
是一个自动变量(由PowerShell提供的值),不应用作自定义变量$input
- 只需将
重命名为$input
即可解决问题$InputObject
请注意,是一个,不应分配给(它由PowerShell自动管理,以在非高级脚本和函数中提供管道输入的枚举器) 遗憾的是,出乎意料地,一些自动变量(包括
$input
)可以分配给:请参阅
$input
是一个特别隐蔽的例子,因为如果将其用作参数变量,传递给它的任何值都会被悄悄地丢弃,因为在函数或脚本的上下文中,$input
始终是任何管道输入的枚举器
下面是一个简单的例子来说明问题:
PS> & { param($input) "[$input]" } 'hi'
# !! No output - the argument was quietly discarded.
$input
的内置定义优先于以下内容:
PS> 'ho' | & { param($input) "[$input]" } 'hi'
ho # !! pipeline input took precedence
$Input
是一个保留的自动变量。请勿将其用作只读项以外的任何内容。[咧嘴笑]