Friday, February 25, 2011

Batch edit shortcut targets with a VB Script

On some file servers, users create multiple shotcuts pointing to different locations on the same server.
When migrating data from this server to another, these shorcuts are deprecated, so you need to update them and you can have thousands...
Here is a VB script that let you batch edit these shortcuts so that you can keep all of them updated.

Dim objFSO

Const srcServer = "\\formerServer\"
Const dstServer = "\\newServer\"

args = WScript.Arguments.Count

If args < 1 then
WScript.Echo "usage: cscript replaceLinkTarget.vbs [folder]"
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")

Call FindEditShortcut(WScript.Arguments.Item(0))

Sub FindEditShortcut(currentDrive)
Dim objFile
Dim objFolder

For Each objFolder In objFSO.GetFolder(currentDrive).SubFolders
For Each objFile In objFolder.Files
'Check extension
If LCase(objFSO.GetExtensionName(objFile)) = "lnk" Then
Set objShell = CreateObject("WScript.Shell")
Set shortcut = objShell.CreateShortcut(objFile.path)
target = LCase(shortcut.TargetPath)

If (InStr(target, srcServer) > 0) Then
target = replace(target,srcServer,dstServer)
Wscript.Echo "New target : " & target
shortcut.TargetPath = target
End If
End If

Call FindEditShortcut(objFolder)
End Sub