PowerShell script for updating DFS paths for all the shortcut files (.lnk)

Here is the final version of a PowerShell script that I have created for updating DFS paths for all the shortcut files (.lnk). The script has been fine tuned to the best of my ability for optimum performance, no where close to how a PowerShell professional would have done it. My special appreciation to Kevin Marquette for all his help in restructuring the code for performance improvements. You may read some of his best blogs that helped me with the below code here and here.

$folders  = @('C:\Temp\lnkTest','C:\Temp\lnkTest1','C:\Temp\lnkTest2')

$filelist = Get-ChildItem -File -Path $folders -Filter "*.lnk" -Recurse -ErrorAction SilentlyContinue

#SECTION - CSV File Path # Modify / Adapt as required

$csvpath = 'C:\Temp\DFS.csv'

#SECTION - Hash Table Mapping

$dfsHash = @{}
$dfsmappings = Import-Csv $csvpath | ForEach-Object {$dfsHash.add( $_.SourceString, $_.TargetString ) }

$wShell = New-Object -ComObject WScript.Shell

# static code

foreach ($file in $filelist) {

foreach($fromSrv in $dfsHash.keys) 
{

#$fromSrv = "$key"
#$toSrv   = $($dfsHash[$key])
$toSrv   = $dfsHash[$fromSrv]

  $link = $wShell.CreateShortcut($file.FullName)
  $log = [PsCustomObject] @{'Location'        = $file.DirectoryName
                            'Old Filename'    = $file.Name
                            'New Filename'    = $null
                            'Old Target Path' = $link.Targetpath
                            'New Target Path' = $null}
# someString -ireplace [regex]::Escape($someString), $replaceString
  $link.TargetPath       = $link.TargetPath -ireplace [regex]::Escape($fromSrv), $toSrv
  $link.WorkingDirectory = $link.WorkingDirectory -ireplace [regex]::Escape($fromSrv), $toSrv
  $link.IconLocation     = $link.IconLocation -ireplace [regex]::Escape($fromSrv), $toSrv
  $log.'New Target Path' = $link.TargetPath
  
  if ($log.'Old Target Path' -ne $log.'New Target Path')
                        {
    $link.Save()
    $log.'New FileName' = $file | Rename-Item -NewName ($file.Name -ireplace [regex]::Escape($fromSrv), $toSrv) -PassThru | Select -Expand Name
    $log    
                        }
  $link = $null
                }
}

Cheers and hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: