Invoke-Command 命令使用技巧
2020-12-30上海崔阳
■ 上海 崔阳
编者按:在PowerShell 中,Invoke-Command 命令用于在本地或远程计算机上运行命令,并从命令返回所有输出,包括错误信息。本文笔者通过实践总结出使用技巧,分享给读者。
首先,当我们要在本地或远程计算机上运行一条命令时,我们可以用以下命令行去实现:
In voke-Comm and-Computer Name < MACHINENAME > -Scriptblock {
其 中,MACHINENAME 是本地或远程计算机的名字,COMMAND 是 你 要 运 行的 命 令,例 如:Invoke-Command -ComputerName bjbffo 3 0 ads 001 -Script Block {g e tchilditem d:}
通常情况下,你可能需要去执行一系列(多条)的命令才能达到你的操作目标,这时候如果你仍然使用上面的命令形式,每次Invoke 一条命令,你就需要进行一次建立连接和释放连接的过程。为了提高命令执行速度,降低系统开销,我们可以引入-Session 参数,如下所示:
In voke-Comm and-Session
这样你先定义了一个Session 变 量,Session 变量可以重复使 用, 每 次Invoke 一条命令时把Session变量直接加进去就可以使用了,不用重复定义。 例 如:$s = New-PSSession -ComputerName BJBFFO30ADS001
In voke-Comm and-Session $s -ScriptBlock {get-childitem c:}
In voke-Comm and-Session $s -ScriptBlock {get-childitem d:}
在执行Invoke-Command命令时,我们也可以传入外部参数,通常情况下,我们可以传入以下类型的参数:
传入字符串:
Invoke-Command -Scrip tBlock { param([string]$tem) $item } -ArgumentLi st “Hello”
传入变量:
$somestring = “Hello again!”
Invoke-Command -Scrip tBlock { param([string]$item) $item } -ArgumentL ist $somestring
传入数组:
In voke-Comm and-ScriptBlock { param([arr ay]$item) $item } -Argume ntList @("Hello", "World")
当传入数组时,你会发现结果只会返回当前的第一个元素,为了解决这个问题,我们需要在数组前加入一个逗号,引入空数组元素,如下所示:
$array = @("hello","w orld")
In voke-Comm and-ScriptBlock { param([ar ray]$item) $item } -Argu mentList @(,$array)
我们还可以用Invoke-Command 来远程地执行本 地 的function,这 时候我们要把原来命令行中 的“Scriptblock {}”更 改 为“scriptblock ${function:
function Get-ItemsCr eatedLastweek
{
$date = (get-date).AddDays(-7)
$items = Get-ChildIte m D: |?{$_.lastwritetime -gt $date}
return $items
}
Invoke-Command -Compu terName shaffo30lg001 -ScriptBlock ${function:Get-ItemsCreatedLastwee k}
当需要远程执行的本地function 有参数时,可以有以下几种执行方式。
当参数为单参数字符串类型时:
function Get-ItemsCre atedByDate
{
param($date)
$items = Get-ChildIt em D: |?{$_.lastwriteti me -gt $date}
return $items
}
Invoke-Command -ComputerName shaffo30lg001 -ScriptBlock ${function:G et-ItemsCreatedByDate} ` -ArgumentList '2019-10-13'
当参数为单参数数组类型时:
function Get-ItemsCr eatedByDate
{
param($locations)$items = @()
foreach($lct in $loca tions)
{
$items += Get-ChildIt em $lct
}
return $items
}
$locations = @("c:","D:")
Invoke-Command -Compu terName shaffo30lg001 -Sc riptBlock ${function:Get-I tems Created By Date} `-ArgumentList @(,$locat ions)
当参数为
多参数类型时:
function Get-exItem
{param($location,$date)
$items = Get-ChildIte m $location |?{$_.lastwri tetime -gt $date}
return $items
}
Invoke-Command -Compu terName shaffo30lg001 -ScriptBlock ${function:G et-exItem} -ArgumentList ` @('D:21V-GalOpsDigicerts','2018-05-23')
当参数类型为数组时:
function Get-ItemsCre atedByDate
{param($date,$locations)
$items = @()
foreach($lct in $loca tions)
{
$items += Get-ChildItem $ lct | ? { $ _ .lastwritetim e -gt $date}
return $items
}
}
$locations = @("c:","d:")
Invoke-Command -Compu terName shaffo30lg001 -ScriptBlock ${function:Get-ItemsCreatedByDate} ` -ArgumentList @('2019-10-10',@(,$locations))
以上是命令的使用技巧,大家可以作为参考,并加以体会和运用。