Skip to content

Instantly share code, notes, and snippets.

@prasannavl
Last active December 21, 2017 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasannavl/ce81599fb39cc50dbdb2 to your computer and use it in GitHub Desktop.
Save prasannavl/ce81599fb39cc50dbdb2 to your computer and use it in GitHub Desktop.
Create windows shortcuts from Powershell
function New-FileShortcut
{
<#
.SYNOPSIS
Create Windows shortcuts
.DESCRIPTION
Creates shortcuts of the Target in the given location.
Given locations can either be the full path, or just the name in which
case its created on the current path.
If just the target path is given, it creates a shortcut with the same
name as the target in the current path.
All parameters other than the Target is optional.
.EXAMPLE
New-FileShortcut "C:\Windows\notepad.exe"
Creates notepad.lnk in the current folder
.EXAMPLE
New-FileShortcut -Target "C:\Windows\notepad.exe" -Name "Notepad Shortcut"
Creates "Notepad Shortcut.lnk" in the current folder
.EXAMPLE
New-FileShortcut -Target "C:\Windows\notepad.exe" -FullPath "D:\Notepad Shortcut.lnk"
Creates shortcut: "D:\Notepad Shortcut.lnk"
#>
[CmdletBinding()]
param(
[Parameter(Position=1)]
[string] $Name,
[Parameter(Position=2)]
[string] $FullPath,
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[ValidateScript({ Test-Path -IsValid -PathType Leaf -LiteralPath $_ })]
[string] $Target,
[Parameter()]
[ValidateNotNull()]
[string] $IconLocation,
[Parameter()]
[ValidateNotNull()]
[string] $Arguments,
[Parameter()]
[ValidateScript({Test-Path -IsValid -PathType Container -LiteralPath $_})]
[string] $WorkingDirectory,
[Parameter()]
[string] $Description
)
process {
$shell = New-Object -ComObject WScript.Shell
$path = ''
if ($Name -and -not $FullPath)
{
$path = "$($pwd.Path)\$($Name)"
if (-not $path.EndsWith('.lnk')) {
$path += '.lnk'
}
}
elseif ($FullPath)
{
$path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($FullPath)
$parent = Split-Path $path -Parent
if (-not (Test-Path -LiteralPath $parent -PathType Container))
{
mkdir $parent
}
}
else
{
$path = "$($pwd.Path)\$([System.IO.Path]::GetFileNameWithoutExtension($Target)).lnk"
}
$shortcut = $shell.CreateShortcut($path)
$shortcut.TargetPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Target)
if ($IconLocation)
{
$shortcut.IconLocation = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($IconLocation)
}
if ($Arguments)
{
$shortcut.Arguments = $Arguments
}
if ($Description)
{
$shortcut.Description = $Description
}
if ($WorkingDirectory)
{
$shortcut.WorkingDirectory = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($WorkingDirectory)
}
$shortcut.Save()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment