Thursday, December 3, 2009

Mapping a network drive on a remote computer

As many blogs have stated there is a a quick way to map network drives within PowerShell; create a Wscript.Network object and use the MapNetworkDrive method.  Example:
(New-Object -Com WScript.Network).MapNetworkDrive("u:",\\computer\share)

Now, that is great to run localy, but New-Object does not connect to a remote computer.  So, with PoSh 2.0 and Remoting, we now can create remote sessions and run the command as though it was local to the remote computer.

CODE

$session = new-pssession -ComputerName computer1
invoke-command -session $session -scriptblock {(New-Object -Com WScript.Network).MapNetworkDrive("u:",\\computer\share)}

 code: copy : expand : collapse

EXPLANATION
When this is run a new session will open on the remote computer and keep it open as a local object to be called later.  invoke-command will use this session and run the scriptblock necessary to map the network drive

0 comments: