Misc/New-DesktopShortcut.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function New-DesktopShortcut {
    Param(
        [Parameter(Mandatory=$true)]
        [string] $Name, 
        [Parameter(Mandatory=$true)]
        [string] $TargetPath, 
        [string] $WorkingDirectory = "", 
        [string] $IconLocation = "", 
        [string] $Arguments = "",
        [ValidateSet('None','Desktop','StartMenu','Startup','CommonDesktop','CommonStartMenu','CommonStartup')]
        [string] $shortcuts = "Desktop",
        [switch] $RunAsAdministrator = $isAdministrator
    )
    if ($shortcuts -ne "None") {
        
        if ($shortcuts -eq "Desktop" -or 
            $shortcuts -eq "CommonDesktop" -or 
            $shortcuts -eq "Startup" -or 
            $shortcuts -eq "CommonStartup") {
            $folder = [Environment]::GetFolderPath($shortcuts)
        } else {
            $folder = Join-Path ([Environment]::GetFolderPath($shortcuts)) "NavContainerHelper"
            if (!(Test-Path $folder -PathType Container)) {
                New-Item $folder -ItemType Directory | Out-Null
            }
        }

        if ($folder) {
            $filename = Join-Path $folder "$Name.lnk"
            if (Test-Path -Path $filename) {
                Remove-Item $filename -force
            }
        
            $Shell =  New-object -comobject WScript.Shell
            $Shortcut = $Shell.CreateShortcut($filename)
            $Shortcut.TargetPath = $TargetPath
            if (!$WorkingDirectory) {
                $WorkingDirectory = Split-Path $TargetPath
            }
            $Shortcut.WorkingDirectory = $WorkingDirectory
            if ($Arguments) {
                $Shortcut.Arguments = $Arguments
            }
            if ($IconLocation) {
                $Shortcut.IconLocation = $IconLocation
            }
            $Shortcut.save()
            if ($RunAsAdministrator) {
                $bytes = [System.IO.File]::ReadAllBytes($filename)
                $bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
                [System.IO.File]::WriteAllBytes($filename, $bytes)
            }
        }
    }
}
Export-ModuleMember -Function New-DesktopShortcut