Inspired by Harry's post, I made an expanded version of find-to-set-alias suitable to putting into a script (.ps1) file, which includes warnings and diagnostic information, with an optional -quiet switch (more useful for your profile to automatically find and alias things, when you expect that they might not be there).
Source: find-to-set-alias.ps1
param( $foldersearch = $(throw "foldersearch required"), $filename = $(throw "filename required"), $alias = $(throw "alias required"), [switch]$quiet ) if ((test-path $foldersearch) -eq $false) { if ($quiet -eq $false) { write-warning ("Could not find any paths to match " + $foldersearch) } exit } # If the user specified a wildcard, turn the foldersearch into an array of matching items # We don't always want to do this, because specifying a non-wildcard directory gives false positives if ($foldersearch.contains('*') -or $foldersearch.contains('?')) { $foldersearch = Get-ChildItem $foldersearch -ErrorAction SilentlyContinue } $files = @($foldersearch | %{ Get-ChildItem $_ -Recurse -Filter $filename -ErrorAction SilentlyContinue }) if ($files -eq $null) { if ($quiet -eq $false) { write-warning ("Could not find " + $filename + " in searched paths:") $foldersearch | %{ write-warning (" " + $_) } } exit } set-alias $alias $files[0].FullName -scope Global if ($quiet -eq $false) { write-host ("Added alias " + $alias + " for " + $files[0].FullName) if ($files.count -gt 1) { write-warning ("There were " + $files.count + " matches:") $files | %{ write-warning (" " + $_.FullName) } } }
Brad, call me late to the party but I just discovered your post (not sure why technorati didn't point it out to me). Anyway, I tried running this on my machine and it failed. I had to change the line
$files = $foldersearch | %{ Get-ChildItem $_ -Recurse -Filter $filename -ErrorAction SilentlyContinue }
to
$files = @($foldersearch | %{ Get-ChildItem $_ -Recurse -Filter $filename -ErrorAction SilentlyContinue })
i.e. adding the @(...) syntax. That forces the output to always be a collection, even if it's a single item. Before that, I was getting a failure in the line with $files[0].
Posted by: DevHawk | April 28, 2009 at 16:34
Good catch! I've updated the post.
Posted by: Brad Wilson | April 30, 2009 at 00:02