Windows shortcut to a PowerShell script with relative path

試著忘記壹切 提交于 2019-12-23 19:51:04

问题


When creating a Windows shortcut to launch a PowerShell script the following works fine when double clicked as a regular user and with right click Run as administrator:

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy "Bypass" -Command "&{& 'C:\Script.ps1'}"

However, when the path is relative and not known upfront the following works fine when double clicked as a regular user but not with right click Run as administrator:

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy "Bypass" -Command "&{& '.\Script.ps1'}"

My question, how can I have it work in both case when the path is relative? I tried using PSScriptRoot but that didn't work either.

Thank you for your help.


回答1:


When launching as admin from Explorer, you must provide an absolute path to the script.

Explorer.exe ignores the starting directory from the shortcut when launching a process as admin. Instead, Admin-level processes always launch with the current directory in [Environment]::GetFolderPath('System') (usually C:\Windows\System32)

The easy way to run in a different directory is to change directory at the beginning of your script. The following line will cd to the directory the script is in.

Set-Location $PsScriptRoot

If the script needs to start in a different path, then you may have to write a function to discover where that path is on the local machine (such as enumerating USB drives)




回答2:


You can use your current solution for non-admin promoted shortcuts then auto promote the script internally:

# ========================================= Admin Rights =======================================================
# Usage: asAdmin $PSCommandPath
function asAdmin
{
    [string]$cmdPath = $args[0]
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$cmdPath`"" -Verb RunAs; exit }
}


来源:https://stackoverflow.com/questions/38658420/windows-shortcut-to-a-powershell-script-with-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!