Arkanaught
Arkanaught

Reputation: 21

How to replace part of a mapped network drive path using PowerShell?

At the company I work for we have recently changed file servers the old is called "EXAMPLE-FS-001" and a typical drive map would be \example-fs-001\staff_directory\staffname

The new server is called companyname.local and a typical drive map would be \companyname.local\shares\staff_directory\staffname.

We are using Server 2012 R2.

To help the IT Helpdesk from being bombarded with tickets about "My network drive doesn't work", I want to create a script that will run on the users computer and change the network drives path but just replacing \example-fs-001\ to \companyname.local\shares\ part.

The home drive has already changed, this will replace the manually set up mapped network drives.

I've been attempting to follow examples, but not many exist out there.

Example 1.

Set objNetwork = CreateObject("Wscript.Network")

Set colDrives = objNetwork.EnumNetworkDrives

For (i = 0 to colDrives.Count-1 Step 2){}
If  (colDrives.Item(i + 1) = "\\EXAMPLE-FS-001")
    {strDriveLetter = colDrives.Item(i)
     objNetwork.RemoveNetworkDrive strDriveLetter
     objNetwork.MapNetworkDrive strDriveLetter, "\\companyname.local\shares"}
End If
Next

Example 2.

On Error Resume Next
strOldServer = "EXAMPLE-FS-001"
strNewServer = "companyname.local\shares"
Set objNetwork = CreateObject("Wscript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 to colDrives.Count-1 Step 2
strThisServer = Left(Mid(colDrives.Item(i + 1), 3), InStr(Mid(colDrives.Item(i + 1), 3), "\") - 1)
If LCase(strThisServer) = LCase(strOldServer) Then
strDriveLetter = colDrives.Item(i)
strNewPath = "\\" $strNewServer "\" $Mid(colDrives.Item(i + 1), $Len("\\" & strOldServer       & "\") + 1)
If objFSO.FolderExists(strNewPath) = True Then
objNetwork.RemoveNetworkDrive strDriveLetter
objNetwork.MapNetworkDrive strDriveLetter, strNewPath
End If
End If
Next

I am new to PowerShell but see its fantastic use, I'd love to know if I'm on track with either of these codes.

Thanks,

Arkan

Upvotes: 1

Views: 3716

Answers (1)

websch01ar
websch01ar

Reputation: 2123

I believe this will get you on track. Keep the -whatif in there until you are sure the script will work for you.

 $OldServer = "\\EXAMPLE-FS-001\"
 $NewServer = "\\companyname.local\shares\"

 $drives = Get-WmiObject win32_logicaldisk | 
    ? {$_.ProviderName -like "$($OldServer)*" } | 
        % { 
            $Name = (($_.DeviceID) -replace ":", "")
            $NewRoot = (($_.ProviderName) -replace $OldServer, $NewServer)
            Get-PSDrive $Name | Remove-PSDrive -Force -whatif
            New-PSDrive $Name -PSProvider FileSystem -Root $NewRoot -WhatIf
        }

Upvotes: 2

Related Questions