Forum Discussion
Edit Windows Shortcut properties TargetPath and WorkingDirectory with a script?
I've moved data to a new drive, and there are a lot of shortcuts (*.lnk files) to different files in the data set. I'd like to create a script that edits the file paths in the shortcut properties "TargetPath" and WorkingDirectory" so that these paths are accurate based on where the files are now located. Only parts of the file paths must change, and the file names must not be changed.
For example, if the old path and filename are "D:\Dataset\Folder1\Folder2\filenameX.doc" the new path should be "E:\Folder1\Folder2\filenameX.doc" - where the drive letter is changed from D to E and the folder "Dataset" is removed from the path.
The following script was created for me by Google search results, but it doesn't alter the values of these named properties at all. If anyone can provide edits that cause the script to work, I'd appreciate it very much. Thanks!
# Define the paths and folder to search
$searchFolder = "E:\Internet Files\Shortcut Ops temp"
$oldPath = "D:\Dataset\"
$newPath = "E:\"
# Create the COM object for shell operations
$shell = New-Object -ComObject WScript.Shell
# Get all .lnk files in the search folder (including subfolders)
$shortcuts = Get-ChildItem -Path $searchFolder -Filter *.lnk -Recurse
foreach ($file in $shortcuts) {
# Open the existing shortcut
$lnk = $shell.CreateShortcut($file.FullName)
# Check if the TargetPath contains the old path string
if ($lnk.TargetPath -like "*$oldPath*") {
# Update TargetPath and WorkingDirectory by replacing the old string
$lnk.TargetPath = $lnk.TargetPath.Replace($oldPath, $newPath)
$lnk.WorkingDirectory = $lnk.WorkingDirectory.Replace($oldPath, $newPath)
# Save the changes to the existing file
$lnk.Save()
Write-Host "Updated: $($file.Name)" -ForegroundColor Cyan
}
}