Created
September 12, 2014 15:53
-
-
Save mkropat/fa0bc9179c0610b84543 to your computer and use it in GitHub Desktop.
Automatically maintain shortcuts to files in subdirectories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[parameter(Mandatory=$true, Position=0)] | |
[String[]] $Path, | |
[Switch] $Watch | |
) | |
function main | |
{ | |
Remove-InvalidShortcuts | |
Create-Shortcuts $Path | |
if ($Watch.IsPresent) { | |
Register-FileWatcher | |
} | |
} | |
function Create-Shortcuts($path) | |
{ | |
$slnFiles = Get-Item $path | |
foreach ($link in $slnFiles | Select-LinkToTargetMapping) { | |
Create-Shortcut $link.LinkFile $link.TargetFile | |
} | |
} | |
function Remove-InvalidShortcuts | |
{ | |
param( [string]$Path = '.' ) | |
$shortcuts = Get-ChildItem (Join-Path $Path *) -Include *.lnk | | |
foreach { Get-Shortcut $_ } | |
$nonexistent = $shortcuts | where { -not (Test-Path $_.TargetPath) } | |
foreach ($shortcut in $nonexistent) | |
{ | |
Remove-Item $shortcut.FullName | |
} | |
} | |
function Register-FileWatcher | |
{ | |
$scriptPath = $script:MyInvocation.MyCommand.Path | |
# http://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b | |
$watcher = New-Object IO.FileSystemWatcher '.' | |
$changed = Register-ObjectEvent $watcher Changed -MessageData @{ ScriptPath = $scriptPath; Args = @( $Path ) } -Action { | |
try { | |
& $event.MessageData.ScriptPath $event.MessageData.Args | |
} catch [Exception] { | |
Write-Host $_.Exception.Message | |
} | |
} | |
$watcher.EnableRaisingEvents = $true | |
} | |
filter Select-LinkToTargetMapping | |
{ | |
$path = $_.Directory | Resolve-Path -Relative | |
$name = $path -replace '^.\\','' -replace '\\','-' | |
$lnkFile = Join-Path $Pwd ($name + '.lnk') | |
return @{ LinkFile = $lnkFile; TargetFile = $_ } | |
} | |
function Get-Shortcut | |
{ | |
param ( [string]$Path ) | |
$file = Get-Item $Path | |
$wsh = New-Object -ComObject WScript.Shell | |
$shortcut = $wsh.CreateShortcut($Path) | |
return @{ | |
FullName = $file.FullName; | |
TargetPath = $shortcut.TargetPath; | |
Description = $shortcut.Description; | |
WorkingDirectory = $shortcut.WorkingDirectory; | |
} | |
} | |
function Create-Shortcut | |
{ | |
# Adapted from a post by CB (http://stackoverflow.com/a/9701907/27581) | |
param ( [string]$Path, [string]$Target ) | |
$wsh = New-Object -ComObject WScript.Shell | |
$shortcut = $wsh.CreateShortcut($Path) | |
$targetItem = Get-Item $Target | |
$shortcut.TargetPath = $targetItem.FullName | |
if ($targetItem.Directory) | |
{ | |
$shortcut.WorkingDirectory = $targetItem.Directory.FullName | |
} | |
$shortcut.Save() | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment