Change shortcut links to new location

Julio Arizaga
Julio Arizaga used Ask the Experts™
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
$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"
Write-Host "End..."
Code from:
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Probably the simplest solution is to double the backslashes when they appear in patterns.

But for you, you're not really using a regular expression, you're just checking to see whether two strings are equal for the length of the shorter string, so you could do better with:

if($oldpath.substring(0,$oldsharepath.length) -eq $oldsharepath)

Open in new window

-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:


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:


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


GREAT!! That worked. Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial