在 powershell 中,我想学习调用变量来启动作业的最佳方法,这样我就不必编辑每个服务器的脚本,因为它将根据我放置脚本的客户端而具体化。
$Servername = 'Server1'
$pingblock = {
pathping $servername | Out-File C:\client\PS\ServerPing.TXT
}
start-job $pingblock
当我运行上面的代码时,我只是得到一个带有帮助的文件,就好像我忘记了指定 $servername 一样。
来补充基思·希尔的有用回答 with a PSv3+ 替代方案:
The $using:范围修饰符可用于引用传递给的脚本块内调用者范围内的变量值Start-Job
,作为传递参数的替代方法(默认情况下,作为后台作业执行的脚本块不会not查看调用者的任何变量或其他定义):
$Servername = 'Server1'
Start-Job { "Target: " + $using:ServerName } | Receive-Job -Wait -AutoRemoveJob
上面的结果是:
Target: Server1
Note:
-
相同的技术可用于:
-
Invoke-Command for remote执行-参见这个问题.
-
Start-ThreadJob,默认情况下在 PowerShell (Core) v6+ 中可用,可在 Windows PowerShell 中按需安装。
-
ForEach-Object -Parallel,仅在 PowerShell (Core) v7+ 中可用。
-
Note that, as with -ArgumentList
(-Args
), it is only variable values that are being passed, not the variables themselves; that is, you cannot modify the caller's variables.[1]
[1] However, the thread-based concurrency features - Start-ThreadJob
and ForEach-Object Parallel
- permit indirect modification, namely if the variable value at hand happens to be an instance of a (mutable) .NET reference type, such as a hashtable, in which case the object that that the variable "points to" can be modified (if it is mutable). Note that taking advantage of that requires additional, nontrivial effort to make the concurrent modifications thread-safe, such as by use of concurrent (synchronized) collections - see this answer - and/or explicit locking of individual objects - see this answer.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)