Sunday, March 11, 2012

PowerShell: Map Network Drives

Wanted to explore mapping network drives with PowerShell. Quick search online shows that you will still need to use Wscript.network or the old net use command. Since I came into the game with VBScript I went that path. I configured a scheduled task that runs when my domain account logs onto the system. Below are the parameters of the Action tab of the scheduled task.

Action: Start a program

Settings -

Program/Script: C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -noexit -command "C:\Users\userID\Documents\Scripts\Dean_Drive_Mappings.ps1"

----Dean_Drive_Mappings.ps1-----------

#Create Object Instance of Wscript.Network
$net = new-object -ComObject WScript.Network

#Gather Collection of All Network Drive Mappings
$mappedDrives = $net.EnumNetworkDrives()

#Remove All Established Network Drive Mappings
for ($d = 0; $d -lt $mappedDrives.Count(); $d = $d + 2)
{
#Remove Network Drive
$net.RemoveNetworkDrive($mappedDrives.item($d).ToString(),$true,$true)
}

#Pause the Script to Prevent Networking Confusion
Start-Sleep -Milliseconds 800

#Map Required Drives
$net.MapNetworkDrive("i:", "\\server1.mycollege.edu\share1", $true)
$net.MapNetworkDrive("j:", "\\server2.mycollege.edu\share2", $true)
$net.MapNetworkDrive("k:", "\\server3.mycollege.edu\share3", $true)
$net.MapNetworkDrive("l:", "\\server4.mycollege.edu\share4", $true)
$net.MapNetworkDrive("s:", "\\server5.mycollege.edu\share5", $true)

No comments: