Powershell pass variable to start-job

南楼画角 提交于 2019-11-26 09:11:36

问题


within powershell I\'d like to learn the best way to call a variable to a start job so I don\'t have to edit the script for each server as it will be specific based on the client I\'ve placed my script on.

$Servername = \'Server1\'
    $pingblock = {
      pathping $servername | Out-File C:\\client\\PS\\ServerPing.TXT
    }
    start-job $pingblock

when I run my code above I just get a file with the help as if I forgot the specify the $servername.


回答1:


Use the -ArgumentList parameter on Start-Job e.g.:

Start-Job -Scriptblock {param($p) "`$p is $p"} -Arg 'Server1'

In your case:

$pingblock = {param($servername) pathping $servername | Out-File C:\...\ServerPing.txt}
Start-Job $pingblock -Arg Server1



回答2:


To complement Keith Hill's helpful answer with a PSv3+ alternative:

The $using: scope modifier can be used to reference variables in the caller's scope inside the script block passed to Start-Job, as an alternative to passing arguments (by default, a script block executed as a background job does not see any of the caller's variables or other definitions):

$Servername = 'Server1'
Start-Job { "Target: " + $using:ServerName } | Receive-Job -Wait -AutoRemoveJob

The above yields:

Target: Server1

Note that the same technique can be used when passing a script block for execution on a remote computer to Invoke-Command - see this question.



来源:https://stackoverflow.com/questions/10075943/powershell-pass-variable-to-start-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!