Sunday, May 3, 2009

Swapping UNC Shortcuts

So you've got this fantastically clever approach to remapping drives to suit a server name change.  Maybe "Server1" is becoming "Server22" or maybe the share name "Documents" is being changed to "Docs", or maybe it's both.  Easy enough.  There's all sorts of ways to do this, Group Policy Preferences, Scripts, etc.  So their "X:" drive needs to be disconnected and reconnected to the new share.

But what about users that have created UNC shortcuts?

Here's a KiXtart script to walk through all the shortcut .lnk files on the users desktop and check if the existing target path matches the "old" target path. If it does, then we simply update it and save the shortcut object, then continue on to the next one.

Break ON

$oldPath = "\\Server1\Documents"
$newPath = "\\Server2\Docs"

$shell = CreateObject("WScript.Shell")
$DesktopPath = ExpandEnvironmentVars("%userprofile%")+"\Desktop"

$FileName = Dir("$DesktopPath\*.lnk")
While $FileName <> "" and @ERROR = 0
? $FileName
$link = $shell.CreateShortcut("$DesktopPath\$FileName")
If Ucase($link.TargetPath) = Ucase($oldPath)
? "updating shortcut target..."
$link.TargetPath = $newPath
$FileName = Dir() ; retrieve next file

And not to be biased or anything, here's the same chunk of script code done in VBscript.

oldPath = "\\Server1\Documents"
newPath = "\\Server2\Docs"

Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

DesktopPath = shell.ExpandEnvironmentStrings("%userprofile%") & "\Desktop"

Set objFolder = fso.GetFolder(DesktopPath)
For each objFile in objFolder.Files
If Lcase(Right(objFile.Name,4)) = ".lnk" Then
Wscript.Echo "updating shortcut target..."
Set link = shell.CreateShortcut(DesktopPath & "\" & objFile.Name)
link.TargetPath = newPath
End If

EDIT: Ok, as soon as I posted the above mess, I realized that some folks might want this in PowerShell also. So I gave in. Don't even ask about Sanskrit or Swahili, I won't go there.

$desktop = $home+"\desktop"
$oldPath = "\\Server1\Documents"
$newPath = "\\Server2\Docs"

$shell = New-Object -ComObject WScript.Shell
$Dir = get-childitem $desktop -recurse

foreach($file in $Dir) {
$fname = $file.Name
$lnk = $shell.CreateShortcut($desktop+"\"+$fname)
$target = $lnk.TargetPath
if ($target -eq $oldPath) {
write-host "Updating shortcut target..."
$lnk.TargetPath = $newPath
Post a Comment