有一个用户登录脚本,它会根据条件依次调用其他脚本。为了单独调用脚本,添加了 [switch]$Silent 参数。问题 - 如何在 Start-Job 中传递此参数?我尝试以不同的方式添加到参数列表中 - 无论顺序如何,该值始终落入相邻参数中。主脚本示例
Param(
[string]$location = 'C:\Users',
[switch]$Silent
)
Start-Job -FilePath ".\Fonts_Install.ps1" -ArgumentList ($Silent,$location) | Wait-Job
被调用脚本的摘录
Param(
[switch]$Silent = $false,
[string]$location = '.'
)
switch ($Silent) {
$false {
if ($Error.Count -gt 0) {
for ($i = 0; $i -le ($Error.Items.Count + 1); $i++) {
$errMSG = "$Error"
}
[System.Windows.Forms.MessageBox]::Show("$errMSG", "Error", "OK", "Error")
}
else {
[System.Windows.Forms.MessageBox]::Show("ок", "Fonts", "OK", "Asterisk") | out-null
}
}
}
不幸的是,通过( ) 传递参数仅限于位置参数
Start-Job
-ArgumentList
-Args
,这会阻止绑定[switch]
根据定义必须命名的参数的参数。作为一种解决方法,不要使用它,而是
-FilePath
通过-ScriptBlock
. 在脚本块内({ ... }
命名参数可以像往常一样在脚本调用中使用:注意使用作用域
$using:
将变量值从调用程序的作用域嵌入到将在后台运行的脚本块中。仍然需要通过参数
-Silent
名称来引用参数,开关是否启用可以通过添加:$true
或表示:$false
,表示:$using:Silent
。PS 答案在这里收到 - https://stackoverflow.com/questions/72963472/pass-switch-inside-start-job/72967196#72967196