Powershell – Using Invoke-Command to run commandlets that you do not have locally

With Powershell you have the ability to run commands from remote computers, having the remote hosts installed modules at your disposal.

This means that you no longer have to install modules locally and have the freedom to do your work from any machine that has Powershell installed.

In the below example the requirement is to remote to a Domain Controller so that you can make use of its ActiveDirectory module and move a Computer Object to a particular AD Organization Unit(OU).


Code description

  1. Specify the remote computer in $AD_RemoteComputer
  2. Specify the Computer Object to be moved in $ComputerName
  3. Specify the target OU in $TargetOU
  4. A new Powershell Session will be opened up with the remote computer
  5. Within the existing session, Invoke-Command will execute the AD command with the required information passed in as arguments
  6. The session will then be ended


$AD_RemoteComputer = "TestDC"
$ComputerName = "TestComputer"
$TargetOU = "CN=TestOU,DC=testDC,DC=local"

$AD_Session = New-PSSession -ComputerName $AD_RemoteComputer
Invoke-Command -Session $AD_Session -ScriptBlock {Get-ADComputer $Args[0] | Move-ADObject -TargetPath $Args[1]} -Args $ComputerName, $TargetOU
Get-PSSession -computername $AD_RemoteComputer | %{Remove-PSSession $_}



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s