首页 文章

PowerShell:使用相对路径从快捷方式运行脚本

提问于
浏览
6

EDIT :对于未来的读者来说,简而言之,PowerShell脚本并不打算以这种方式使用,这就是没有优雅解决方案的原因 .

我有以下行从快捷方式以管理员身份运行脚本:

C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe -noprofile -noexit Start-Process Powershell -verb RunAs -ArgumentList“C:\ Documents \ WindowsPowerShell \ Scripts \ test.ps1”

我想改变:

“C:\ Documents \ WindowsPowerShell \ Scripts \ test.ps1”

到相对路径,如:

“ . \ test.ps1”

但我还没弄明白我该怎么做 . 如何相对于快捷方式的位置运行脚本? (快捷方式和脚本在同一个文件夹中)

5 回答

  • 3

    这是一个丑陋的解决方法 .

    具有目标的 Shortcut.lnk 文件: %COMSPEC% /C .\launcher.cmdsource)和开始于: %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 参数?或storing credentials使用Convert * -SecureString cmdlet?算我好奇 .

    Why你想要一条捷径吗?

  • 1

    经过多次试验和错误,我想出了一个解决方案:

    使用此(为.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从第一个启动的第二个管理实例的原因是直接以管理员身份启动(通过勾选快捷方式的"Run as administrator"框),因为some reason忽略"Start in"并始终在System32中启动 .

    CMD用于启动第一个实例,因为PowerShell当前无法解析包含方括号的路径,将它们解释为正则表达式字符 . 这通常可以使用LiteralPath参数(也就是PSPath)来避免,但是在这里,路径在启动时在幕后传递,并且由开发人员来修复(我刚刚提交了错误报告here) .

  • 0

    当我从快捷方式运行脚本时,它使用实际脚本的路径 . 您可以使用 pwd (当前工作目录)检查当前目录 . 您可以使用 split-path -parent $MyInvocation.MyCommand.Definition 检查(然后使用)脚本的路径,如What's the best way to determine the location of the current PowerShell script?中的答案所示 .

    所以要回答你的问题,你应该已经能够使用相对路径了 . 你试过吗?如果是这样,你的经历是什么?

  • 0

    对于您的脚本,默认情况下将其设置为使用Powershell打开 . 为脚本创建快捷方式,并通过右键单击快捷方式,选择属性,单击快捷方式选项卡为其分配热键 . 将光标移动到选择快捷键并定义快捷键 . 每次按快捷键,脚本都会运行

  • -1

    这绝对是比现在更困难 .

    此问题更有可能在Windows Server上影响您 . 在常规Windows上,您可以运行 Set-ExecutionPolicy unrestricted 并且它将在Windows Server(至少在AWS上)上保持对机器的影响,从powershell脚本设置执行策略仅持续脚本的会话并立即关闭以便您立即关闭看不出错误 .

    我刚刚在AWS实例bypassing group policy上成功修改了注册表,只需右键单击任何目录中的powershell脚本,并向可运行的桌面发送快捷方式 .

相关问题