【问题标题】:How to execute command on computer whose name is stored in variable?如何在名称存储在变量中的计算机上执行命令?
【发布时间】:2015-09-14 08:56:27
【问题描述】:

我有以下代码:

$ADForest = Get-ADForest
$ADForestGlobalCatalogs = $ADForest.GlobalCatalogs
$domain= $ADForestGlobalCatalogs | Select-Object -first 1
//connect with $domain the rest of the code has to be executed on $domain
//rest of code goes here (one out of several different scripts). 
Remove-Mailbox "$A" -confirm:$false
Get-Addresslist | where {$_.Name -like "$k*"} | Update-Addresslist
Get-GlobalAddresslist | where {$_.Name -like "$k*"} | Update-GlobalAddresslist

现在我想在计算机上执行存储在变量$domain 中的其余代码。有人知道怎么做这个吗?请注意,其余代码可以是十几个不同脚本之一,因此我可以将所选脚本作为变量提供,然后远程执行它们。理想情况下,代码也会自动传递参数,因此现在不得不碰碰我们目前拥有的代码。

编辑:

Invoke-Command [[-ComputerName] ] [-ScriptBlock] [-ApplicationName ] [-ArgumentList ] [-AsJob] [-Authentication ] [-CertificateThumbprint ] [-ConfigurationName ] [-Credential ] [-EnableNetworkAccess] [-HideComputerName] [-InDisconnectedSession] [-InputObject ] [-JobName ] [-端口 ] [-SessionName ] [-SessionOption ] [-ThrottleLimit ] [-UseSSL] []

看起来相当不错,但我必须使用它,第一个参数是 Invoke-Command -ComputerName $domain ScriptBlock 是其余的代码?它是如何工作的?

或者Enter-PSSession 命令可能会起作用?

【问题讨论】:

  • 为什么是近距离投票?想发表评论吗?
  • 我没有cloes投票,但它是“不清楚你在问什么”,实际上有点难以理解。你试过Invoke-Command 吗?
  • Invoke 命令看起来很不错,现在阅读它的作用,希望我能很好地理解它以使用它。
  • 我希望这更清楚,现在看看是否有办法不必更改脚本的参数以及如何将我已经拥有的代码实际存储在 Invoke-command 中
  • 你看过Invoke-Command的例子吗?我相信您会在远程机器上找到大量正在运行的命令。您是否尝试过某些特定的事情需要帮助?现在,您似乎希望我们发布一些示例。

标签: windows powershell


【解决方案1】:

把你的代码改成这样:

$ADForest = Get-ADForest
$ADForestGlobalCatalogs = $ADForest.GlobalCatalogs
$domain = $ADForestGlobalCatalogs | Select-Object -first 1

Invoke-Command -Computer $domain -ScriptBlock {
  Param(
    [string]$Mailbox,
    [string]$Name
  )

  Remove-Mailbox $Mailbox -confirm:$false
  Get-Addresslist | where {$_.Name -like "$Name*"} | Update-Addresslist
  Get-GlobalAddresslist | where {$_.Name -like "$Name*"} | Update-GlobalAddresslist
} -ArgumentList $A, $k

脚本块是大括号中的一段代码。但是,脚本块通常不能使用周围脚本中的变量,因此您需要通过 -ArgumentList 参数将它们传递到脚本块中。

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2011-11-23
    • 2017-11-28
    相关资源
    最近更新 更多