IvoDijkgraaf
7/6/2016 - 1:55 PM

Create a Shortcut

Create a Shortcut

function New-Shortcut
{
	param (
		$Path = $(throw "path not specified"),
		$Arguments,
		$Description,
		$IconLocation,
		$TargetPath = $(throw "target not specified"),
		$WindowStyle,
		$WorkingDirectory
	)
	
	if (-not ($path.ToUpper().EndsWith(".LNK"))) {
		throw "Please specify shortcut type in the `$path parameter"
	}
	
	# Create the shortcut path if needed
	$RootPath = Split-Path -Path $path
	if (-not (Test-Path -Path $RootPath)) { New-Item -Path $RootPath -ItemType directory -Force | Out-Null }

	$wsh = New-Object -ComObject WScript.Shell
	$lnk = $wsh.Createshortcut($path)
	
	if (Test-Path -Path $targetpath -IsValid) {
		$lnk.targetpath = $targetpath
	} else {
		Write-Host "Invalid targetpath"
	}

	#optional parameters
	if ($Arguments -ne $null -and $Arguments -ne "") { $lnk.Arguments = $Arguments }
	if (-not([string]::IsNullOrEmpty($Description))) { $lnk.Description = $Description.Trim() }
	if ($IconLocation -ne $null -and $IconLocation -ne "") { $lnk.IconLocation = $Iconlocation }
	if ($WindowStyle -ne $null -and $WindowStyle -ne "") { $lnk.WindowStyle = $WindowStyle }
	if ($WorkingDirectory -ne $null -and $WorkingDirectory -ne "") { $lnk.WorkingDirectory = $WorkingDirectory }
		
	$lnk.Save()
}