Powershell如何在Start-Job的Scriptblock里传参?

发布时间:2020-07-04 21:30:10 作者:UltraSQL
来源:网络 阅读:4271

如何在Start-Job的Scriptblock里传参?

方法1:

利用本地变量,从一个可扩展的字符串,使用[scriptblock]::create方法创建脚本块:

$v1 = "123"
$v2 = "asdf"
$sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")
$job = Start-Job -ScriptBlock $sb

# 另一种写法
[scriptblock]$sb =
{
Write-Host "Values are: $v1, $v2"
}



方法2:

在InitializationScript中设置变量

$Init_Script = {
$v1 = "123"
$v2 = "asdf"
}
$sb = {
    Write-Host "Values are: $v1, $v2"
}
$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb



方法3:

使用-Argumentlist参数

$v1 = "123"
$v2 = "asdf"
$sb = {
    Write-Host "Values are: $($args[0]), $($args[1])"
}
$job = Start-Job  -ScriptBlock $sb -ArgumentList $v1,$v2


深入阅读


Using scope


PowerShell v3 introduced another level of scope called using. It doesn’t fit into the
hierarchical model described in figure 22.1, and the rules laid down in this chapter
don’t apply, because it’s designed to be used in situations where you want to access
a local variable in a remote session. The definition from the help file about_scopes is:
Using is a special scope modifier that identifies a local variable in a remote
command. By default, variables in remote commands are assumed to be defined
in the remote session.

More on using can be found in about_Remote_Variables. It’s used like this:
PS C:\> $s = New-PSSession -ComputerName W12Standard
PS C:\> $dt = 3
PS C:\> Invoke-Command -Session $s -ScriptBlock {Get-WmiObject -Class
➥ Win32_LogicalDisk -Filter "DriveType=$dt"}

Invalid query "select * from Win32_LogicalDisk where DriveType="
+ CategoryInfo : InvalidArgument: (:)
[Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,
Microsoft.PowerShell.Commands.GetWmiObjectCommand
+ PSComputerName : W12Standard

PS C:\> Invoke-Command -Session $s -ScriptBlock {Get-WmiObject -Class
➥ Win32_LogicalDisk -Filter "DriveType=$Using:dt"}
DeviceID : C:
DriveType : 3
ProviderName :
FreeSpace : 126600425472
Size : 135994011648
VolumeName :
PSComputerName : W12Standard

Create a remoting session to another machine and define a local variable. If you try
to use that variable (which is local) in the remote session, you’ll get the error shown
in the first command, but if you employ the using scope, it works.
In PowerShell v2, you could do this:
PS C:\> Invoke-Command -Session $s -ScriptBlock {param($d) Get-
➥ WmiObject -Class Win32_LogicalDisk -Filter "DriveType=$d" }
➥ -ArgumentList $dt

Using is a valuable addition to your toolbox when you’re working with remote machines.

推荐阅读:
  1. msyql 问号 传参
  2. jquery如何传参及获取

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

powershell start job

上一篇:垂直行业大数据分层架构图

下一篇:关于Sublime Text 3的常见问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》