2015-09-14 45 views
0

我有以下代码:如何在名称存储在变量中的计算机上执行命令?

$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在计算机上执行代码的其余部分。有人知道怎么做这个吗?请注意,其余代码可以是十几种不同脚本中的一种,因此我将所选脚本作为变量进行远程执行,并且很好。理想情况下,代码也会自动传递参数,以便现在有机会获得我们迄今为止的代码。

编辑:

调用命令[[-ComputerName] <字符串[] >] [-ScriptBlock] <脚本块> [-ApplicationName <字符串>] [-ArgumentList <对象[] >] [ -AsJob] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <字符串>] [-ConfigurationName <字符串>] [-Credential <PSCredential的0] [-EnableNetworkAccess] [-HideComputerName] [-InDisconnectedSession] [-InputObject <PSObject>] [-JobName <字符串>] [ - 端口<的Int32 >] [-SessionName <字符串[] >] [-SessionOption < PSSessionOption首> ] [-ThrottleLimit <的Int32 >] [-UseSSL] [<CommonParameters>]

看起来相当不错,但我会的第一个参数是Invoke-Command -ComputerName $domain脚本块作为代码的其余部分使用它?这是如何运作的?

Alternively也许Enter-PSSession命令可能会奏效?

+0

为什么接近的选票?谨慎评论? – Thijser

+0

我没有cloes投票,但它是“不清楚你问什么”,而事实上它是有点令人费解。你尝试[调用命令](https://technet.microsoft.com/de-de/library/hh849719.aspx?f=255&MSPPError=-2147217396)? –

+0

调用命令看起来相当不错,现在阅读它的功能,希望我可以理解它的使用。 – Thijser

回答

0

更改您的代码是这样的:

$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 

一个脚本块是大括号的一段代码。 Scriptblocks通常不能使用变量从周围的脚本,不过,所以你需要通过-ArgumentList参数将它们传递到脚本块。

相关问题