【问题标题】:Launch as Admin Powershell via Batch File通过批处理文件作为管理员 Powershell 启动
【发布时间】:2016-08-11 19:41:06
【问题描述】:

所以我正在运行一个基本脚本来将快捷方式复制到公共配置文件桌面,以便任何登录的用户都可以在他们的桌面上拥有该快捷方式。情况是我将不得不绕过执行策略,所以我通过批处理文件执行此操作。这是我尝试过的,但它似乎对我不起作用......

Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList 'ExecutionPolicy Bypass -File DesktopShortcut.ps1' -Verb RunAs}"

PS 文件很简单:

Copy-Item -Path "aiStarter.lnk" -Destination "C:\Users\Public\Desktop\" -PassThru

当我运行它时,窗口只是闪烁然后消失。如果我在没有 RunAs 的情况下运行它,我会被拒绝访问。我不想问这个问题,因为我确定以前有人问过这个问题,但我很确定我正确地执行了这个。想法?

【问题讨论】:

  • 这看起来很奇怪。您基本上是在使用批处理文件来启动 powershell,它再次启动 powershell,最终尝试运行您的 powershell 脚本。
  • 另外,您不需要脚本来分发快捷方式。只需使用组策略。
  • @Squashman 需要复杂的语法来启动具有提升权限的 PowerShell 进程。 powershell.exe 没有“runas”开关,因此您需要利用 Start-Process cmdlet。
  • 不确定这是您的问题还是您的实际代码中的拼写错误,但它应该是参数列表中的-ExecutionPolicy,而不是ExecutionPolicy(没有前导连字符)。但是,我同意 @Bill_Stewart 的观点,即 group policy (preferences) 是做你想做的更好的方式。

标签: powershell batch-file


【解决方案1】:

正如其他一些人所说,这不是提供快捷方式的最佳选择。

话虽如此,有两个问题。一个是在执行策略中需要-。另一个是在创建提升的 powershell 实例之后,工作路径发生了变化。所以你需要添加脚本的完整路径,如果是批处理文件,你可以使用%~dp0

Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-ExecutionPolicy Bypass -File %~dp0DesktopShortcut.ps1' -Verb RunAs}"

之后可能需要对 powershell 脚本执行相同的操作。

Copy-Item -Path "$($MyInvocation.MyCommand.Path)\aiStarter.lnk" -Destination "C:\Users\Public\Desktop\" -PassThru

这假设批处理文件、快捷方式和 powershell 脚本都在同一个文件夹中。

【讨论】:

  • 链接文件是指向DesktopShortcut.ps1的链接吗?为什么?
  • 这个答案对我有用。但是,我有一个很长的 ArgumentList 需要传递,如果跨越多行,我想拆分。使用插入符号 ^ 在这里不起作用。示例:Powershell.exe -Command "& {Start-Process Powershell.exe -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -File %~dp0HelloWorld.ps1 ^ -parameter1 Long ^ -parameter2 list ^ -parameter3 of ^ -parameter4 parameters ^' }"(此注释中不显示每个^后的新换行符)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
相关资源
最近更新 更多