Link to home
Get AccessLog in
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/
ASKER CERTIFIED SOLUTION
Avatar of jmcg
jmcg
Flag of United States of America image

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Avatar of Brian Scholer
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

Avatar of Julio Arizaga

ASKER

GREAT!! That worked. Thanks