PowerShell for Non-N00bs: Symlinks
Here's how to create a shortcut in PowerShell. Actually, it's how to create a shortcut with COM in PowerShell
function New-ShortCut
{
param (
[string]$target = $null,
[string]$name = $target,
[string]$parent = (Get-Location).ToString(),
[string]$iconLocation,
[switch]$help
);
if ($help -or !$target)
{
@"
New-Shortcut -target <string> -name <string> -parent <string
target: what this is a shortcut to. Required.
name: what is the name of this shortcut. Default to -target's value.
parent: where to create this shortcut. Default to current working
directory.
"@;
if
($help) {
return;
} else
{
Throw "New-Shortcut
-target not specified, required. Exiting.";
}
}
$shell = New-Object -com WScript.Shell;
$name = $name -replace '[\\\/\:\*\?\"\<\>\|]', "-";
if (!($name -match "\.lnk$"))
{ $name += ".lnk"; }
$shortcut = $shell.CreateShortcut($(Join-Path $parent $name));
$shortcut.TargetPath
= $target;
if ($iconLocation) {
if (Test-Path $iconLocation) {
$shortcut.IconLocation = $iconLocation;
}
else {
Write-Warning "-iconLocation
$iconLocation specified, not found.";
}
}
$shortcut.Save();;
}
Not much of a walkthrough - we create a WScript.Shell object, then use it to create a shortcut object. We populate the object and save it. End of story.
Oh, this is actually a function in my $profile, so it doesn't use the script outline before.
To review, we learned a few things:
- PowerShell interacts with COM pretty cleanly.
- WScript.Shell creates shortcuts.
- My $profile has stuff I don't ever use.