1
0 Comments

I am working on a script that can generate a shortcut for each Powershell script present in a particular directory with administrator privileges. Here is my progress so far:

$scripts = Get-ChildItem -path "C:\Users\djcim\Google Drive\Powershell Scripts\*.ps1" -Recurse
foreach ($script in $scripts) {
    $shortcutFile = [io.path]::ChangeExtension($script.FullName, '.lnk')
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
    $Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    $Shortcut.Save()

    $bytes = [System.IO.File]::ReadAllBytes($ShortcutFile)
    $bytes[0x15] = $bytes[0x15] -bor 0x20
    [System.IO.File]::WriteAllBytes($ShortcutFile, $bytes)

    Move-Item -Path $shortcutFile -Destination "C:\Users\djcim\Google Drive\Powershell Scripts\Admin Shortcuts" -force
}

The above code is able to generate a shortcut with administrative privileges for each script, but the target of the shortcut is only set to Powershell and not to the actual scripts.

It is important for me to set the shortcut target to “Powershell -f [script path]”, as shown in this example:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -f "C:\Users\GJBalaich\Google Drive\Powershell Scripts\FFmpeg\FFclip.ps1"

However, when I attempt to define the target path using Powershell, here are some examples:

$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -f " + "`"" + $script + "`""
$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -f " + $script

It raises an error message “Value does not fall within the expected range” when attempting to set the target path using Powershell. Do you have any suggestions or insights on how to fix this issue?

Askify Moderator Edited question April 27, 2023