powershelllnk

Changing the target of multiple shortcuts with PowerShell


I am writing a PowerShell script to search the C:\Users directory and change all lnk files that contain \server1 to \server2 but keep the rest of the link.

What I have so far will keep changing the LNK's target path to "Computer" and then disable you from being able to edit the LNK. Can anyone explain why this is doing this?

Code:

#Folder to search
$favourites_path = "C:\Users\" 

#Backup C:\Users DISABLED by Default "
# Copy-Item $favourites_path "$favourites_path`1" -Recurse

$favourites = Get-ChildItem $favourites_path -Recurse -Filter *.lnk
foreach ($favourite in $favourites) {
  $shortcut = (New-Object -ComObject 
  'WScript.Shell').CreateShortCut($favourite.FullName)
  $newpath=switch -Wildcard ($shortcut.TargetPath)
  {
    '"\\server1*"'           { $_ -replace '"\\server1"', '"\\server2"'}
  }
  $shortcut.TargetPath=$newpath
  $shortcut.Save()
}

Solution

  • The following code addresses these issues:

    #Folder to search
    $favourites_path = "C:\Users" 
    
    Get-ChildItem $favourites_path -Recurse -Filter *.lnk | ForEach-Object {
       $shortcut = (New-Object -ComObject 'WScript.Shell').CreateShortCut($favourite.FullName)
       $shortcut.Target = $shortcut.Target -replace '^\\\\server1\\', '\\server2\'
       $shortcut.Save()
    }