Reputation: 2633
I have the following code:
$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
Now I would like to execute a the rest of the code on the computer stored in the variable $domain
. Does anybody know how to do this? Note that the rest of the code can be one of over a dozen different script so I'm fine with giving the chosen script as a variable and then executing them remotely. Ideally the code would also pass on the arguments automatically so as to now to have to chance the code we have so far.
Edit:
Invoke-Command [[-ComputerName] <String[]>] [-ScriptBlock] <ScriptBlock> [-ApplicationName <String>] [-ArgumentList <Object[]>] [-AsJob] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-ConfigurationName <String>] [-Credential <PSCredential>] [-EnableNetworkAccess] [-HideComputerName] [-InDisconnectedSession] [-InputObject <PSObject>] [-JobName <String>] [-Port <Int32>] [-SessionName <String[]>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <Int32>] [-UseSSL] [ <CommonParameters>]
looks quite good, but I would have to use it with the first argument being Invoke-Command -ComputerName $domain
ScriptBlock being the rest of the code? How does that work?
Alternively maybe the Enter-PSSession
command might work?
Upvotes: 0
Views: 143
Reputation: 200573
Change your code to something like this:
$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
A scriptblock is a piece of code in curly brackets. Scriptblocks normally can't use variables from the surrounding script, though, so you need to pass them into the scriptblock via the -ArgumentList
parameter.
Upvotes: 0