编辑:简而言之,对于未来的读者来说,PowerShell脚本不是以这种方式使用的,这就是为什么没有优雅的解决方案。
我有以下行,从快捷方式以管理员身份运行脚本:
C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe -noprofile -noexit Start-Process Powershell -verb RunAs -ArgumentList“C:\ Documents \ WindowsPowerShell \ Scripts \ test.ps1”
我想改变:
“C:\文档\ WindowsPowerShell \脚本\ test.ps1”
到相对路径,如:
”。\ test.ps1"
但我还没弄明白我该怎么做。如何相对于快捷方式的位置运行脚本? (快捷方式和脚本位于同一文件夹中)
答案 0 :(得分:3)
这是一个丑陋的解决方法。
带有目标的 Shortcut.lnk
个文件:%COMSPEC% /C .\launcher.cmd
(source)和开始时间:%CD%
(或blank)。
Launcher.cmd
文件:
Powershell -noprofile -noexit -File %CD%\PSlauncher.ps1
带有内容的 PSlauncher.ps1
文件:
Start-Process Powershell -verb RunAs -ArgumentList ($pwd.path + "\test.ps1")
当然有一个更好的解决方案。也许使用Start-Process的-WorkingDirectory
参数?或者使用Convert * -SecureString cmdlet storing credentials?让我很好奇。
Why你想要一条捷径吗?
答案 1 :(得分:2)
经过多次反复试验,我想出了一个解决方案:
使用此方法创建一个快捷方式(针对您的.ps1编辑),让scrips以管理员身份运行,相对于任何目录:
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \""SL -PSPath '"$Path"'; & '".\YourScriptHere.ps1"'"\""
您必须清空快捷方式的“开始”字段才能将其相对路径设置为工作目录。
或者,这是一个脚本,它将为目录中的每个.ps1生成这些快捷方式之一(“已开始”已清除):
(GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object {
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk")
$Shortcut.TargetPath = 'CMD'
$Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`""
$Shortcut.IconLocation = 'PowerShell.exe'
$Shortcut.Save()
}
如果需要,请在第一个-NoExit
之后添加-ExecutionPolicy Unrestricted
,\"
等。
注意:
从第一个启动PowerShell的第二个管理实例的原因是直接以管理员身份启动(通过勾选快捷方式的“以管理员身份运行”框),some reason忽略“开始”并始终在System32中启动。
CMD用于启动第一个实例,因为PowerShell当前无法解析包含方括号的路径,将它们解释为正则表达式字符。这通常可以使用LiteralPath参数(也就是PSPath)来避免,但是在这里,路径在启动时在幕后传递,并且由开发人员来修复(我刚刚提交了错误报告here)。
答案 2 :(得分:0)
当我从快捷方式运行脚本时,它使用实际脚本的路径。您可以使用pwd
(当前工作目录)检查当前目录。您可以使用split-path -parent $MyInvocation.MyCommand.Definition
检查(然后使用)脚本的路径,例如What's the best way to determine the location of the current PowerShell script?中的答案。
所以要回答你的问题,你应该已经能够使用相对路径了。你试过吗?如果是这样,你的经历是什么?
答案 3 :(得分:0)
对于您的脚本,默认情况下将其设置为使用Powershell打开。为脚本创建快捷方式,并通过右键单击快捷方式,选择属性,单击快捷方式选项卡为其分配热键。将光标移动到选择快捷键并定义快捷键。每次按快捷键,脚本都会运行
答案 4 :(得分:-1)
这绝对是比现在更困难。
此问题更有可能在Windows Server上影响您。在常规Windows上,您可以运行Set-ExecutionPolicy unrestricted
并且它将在Windows Server(至少在AWS上)上保持对计算机的影响,从powershell脚本设置执行策略仅持续脚本的会话及其立即关闭,以便您看不到错误。
我刚刚在AWS实例bypassing group policy上成功修改了注册表,只需右键单击任何目录中的powershell脚本,然后向可运行的桌面发送快捷方式。