Sep 27

Powershell Remote Use of Module Commandlets (Remoting Import-Module)

Practically all of my Powershell scripts use an Active Directory commandlet. Ok, so they use several.  I like to query AD to get environmental information so when I run the script, I know what I am working with from an AD perspective. I can’t help it, I’m an AD Guy.

In order to run the AD commandlets, a Domain Controller in the domain has to be running ADWS (Active Directory Web Services aka Active Directory Management Gateway Service). Windows 2008 (and Windows 2008 R2) Domain Controllers run this by default and it is available for Windows 2003 DCs.

Sometimes, the server I need to run a script on doesn’t have the AD commandlets installed.
The quick solution to this is to run the following:

powershell set-executionpolicy unrestricted
powershell import-module servermanager  ;  add-windowsfeature rsat-ad-powershell

Assuming this isn’t possible, there is a way to import-modules available on another server.  I often use this with Exchange commandlets since I rarely have them installed on servers I use for running scripts.

Here’s how this works…

# Create a Powershell remote session to a server with the #commandlets installed.
$Session = New-PSsession -Computername Server1
# Use the newly created remote Powershell session to send a #command to that session
Invoke-Command -Command {Import-Module ActiveDirectory} -Session $Session
# Use that session with the modules to add the available # commandlets to your existing Powershell command shell with a #new command name prefix.
Import-PSSession -Session $Session -Module ActiveDirectory -Prefix RM

The code above enables the use of Active Directory commandlets on a server that doesn’t have them installed.

Use AD commandlets in the Powershell command shell with modified names based on the -Prefix set above:

Get-RMAdUser  instead of the standard Get-ADUser
Get-RMAdComputer instead of the standard Get-ADComputer

You can also drop the “-Prefix RM” and it will use the native commandlets using their standard names.

Don Jones calls this Powershell implicit remoting and it is very cool.


(Visited 3,561 times, 2 visits today)