Thursday, July 9, 2009

PowerShell: Update Desktop Shortcut Targets


# iterate shortcuts to find matching target paths and
# if found, replace with new target path and save link

$desktop = $home+"\desktop"
$oldPath = "\\server1\sharename1"
$newPath = "\\server2\sharename1"

$shell = New-Object -ComObject WScript.Shell

$Dir = get-childitem $desktop -recurse

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

2 comments:

  1. Your script was very useful. I modified to fit my needs as drive letters will be changed for a portion of our users. That will cause all kinds of shortcuts to break and a large amount of helpdesk calls.

    $oldPath = 's:\*'
    $newPath = 'W:\'


    $desktop = $home+"\desktop"

    $shell = New-Object -ComObject WScript.Shell

    $Dir = get-childitem $desktop -filter "*.LNK" -recurse

    foreach($file in $Dir) {
    $fname = $file.Name
    $lnk = $shell.CreateShortcut($desktop+"\"+$fname)
    $target = $lnk.TargetPath
    if ($target -like $oldPath) {
    $tail = $lnk.TargetPath | split-path -NoQualifier
    $FinalPath = $newPath+$tail
    write-host "Updating shortcut target $fname"
    $lnk.TargetPath = $FinalPath
    $lnk.Save()
    }

    ReplyDelete
  2. Hi Guys this script can help in our environment also. I need to change shortcut target based on logged in user name. I would like to import csv file with username corresponding to shortcut target. Can someone guide me. Thanks

    ReplyDelete