Skip to content

Instantly share code, notes, and snippets.

@vexx32
Last active April 19, 2020 22:57
Show Gist options
  • Save vexx32/64e3c91641d9ba418fd719191d6e26dc to your computer and use it in GitHub Desktop.
Save vexx32/64e3c91641d9ba418fd719191d6e26dc to your computer and use it in GitHub Desktop.
function New-Shortcut {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -IsValid $_ })]
[string]$Path,
[Parameter(Mandatory, ValueFromPipeline)]
[ValidateScript({ Test-Path $_ })]
[string]$Target,
[ValidateScript({ Test-Path $_ })]
[string]$Icon = "",
[string]$Arguments,
[ValidateScript({ Test-Path $_ })]
[string]$WorkingDirectory
)
try {
$Shell = New-Object -ComObject ("WScript.Shell")
$Shortcut = $Shell.CreateShortcut($Path)
$Shortcut.TargetPath = $Target
$Shortcut.WorkingDirectory = $Target | Split-Path -Parent
$Shortcut.IconLocation = "$Target, 0"
$Shortcut.Arguments = $Arguments
switch ($PSBoundParameters.Keys) {
'Icon' {
$Shortcut.IconLocation = "$Icon"
}
'WorkingDirectory' {
$Shortcut.WorkingDirectory = $WorkingDirectory
}
}
if ($PSCmdlet.ShouldProcess($Path, "Create shortcut to $Target")) {
$Shortcut.Save()
}
if (Test-Path $Path) {
Write-Verbose "The shortcut was created at '$Path'"
}
else {
Write-Verbose "The shortcut has not been created."
Write-Verbose "No exceptions have been thrown. Parameters used:"
$PSBoundParameters |
Format-Table -Property Key, Value |
Write-Verbose
}
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment