Avatar of Julio Arizaga
Julio Arizaga
 asked on

Change shortcut links to new location

Hello All,

I'm currently trying to get the following script to work, but need to adjust it to match anything with  "\\server1\IT". Using -eq works perfectly for folders, however when using -match I get the following error.

parsing "\\server1\IT" - Unrecognized escape sequence \I

Script should change files and folders location. Ex  "\\server1\IT\Document.docx" to "\\newserver\IT\Document.docx"



# Call wscript com object
$shell = new-object -com wscript.shell
$oldsharepath = "\\server1\IT"

# Recurse through directories for .lnk files
dir 'D:\Test Server1' -filter *.lnk -recurse | foreach {
$lnk = $shell.createShortcut($_.fullname)
$oldPath= $lnk.targetPath
# If match text, perform operation
if($oldpath -match $oldsharepath)
{
write-host "Match: " + $_.fullname
remove-item $_.fullname
$lnknew = $shell.createShortcut($_.fullname)
$lnknew.targetPath = "`"\\newserver\share1`""
$lnknew.IconLocation = "%SystemRoot%\system32\SHELL32.dll,4"
$lnknew.Save()
}
}
Write-Host "End..."
Code from: http://www.squiggle.org/2010/02/powershell-script-to-mass-change-shortcut-path/
Powershell

Avatar of undefined
Last Comment
Julio Arizaga

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
jmcg

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Brian Scholer

-match is the regular expression matching operator, so you must use regular expression syntax. In a regular expression, the backslash is the escape character.

You want to do a partial match here. The easiest way is to the -like operator instead, which uses a much more simple syntax:

if($oldpath -like "$oldsharepath*")
{
    # do stuff
}

Open in new window


To do this in a regular expression, a partial match at the beginning of the string would be written as:

^StringToMatch

Open in new window


The caret matches the start of the string, then you put the literal string. Problem in your case is that it's a variable, so you can't tell in advance what kinds of special regex characters might exist.

Luckily there's a programmatic way to escape any special characters so you know you match the literals:

[RegEx]::Escape($string)

Open in new window


So your match would then look like this:

if($oldpath -match "^$([RegEx]::Escape($oldsharepath))")
{ }

Open in new window


Or, broken out more:

$reg = "^" + [RegEx]::Escape($oldsharepath)
if($oldpath -match $reg)
{ }

Open in new window

Julio Arizaga

ASKER
GREAT!! That worked. Thanks
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy