【问题标题】:How to start PowerShell script from BAT file with proper Working Directory?如何使用正确的工作目录从 BAT 文件启动 PowerShell 脚本?
【发布时间】:2017-11-01 06:28:44
【问题描述】:

我正在尝试创建 bat 脚本,该脚本可以在正确的工作目录中启动与 bat 文件命名相同的 PowerShell 脚本。

这是我得到的:

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE

以这种方式传递工作目录不起作用。

如何制作能够传递正确工作目录和命令行参数的脚本?

【问题讨论】:

  • 它对我有用,但如果'%~dp0' 评估为其中包含空格的目录,则不会。对于这种情况,您需要对工作目录进行三重双引号:"""%~dp0"""
  • 你不能在提升时为进程设置一个初始工作目录——它将默认为System32(或SysWOW64对于32位进程)。这是设计使然。
  • %~dpn0.ps1 中使用Set-Location (Split-Path $MyInvocation.MyCommand.Path) 作为第一个命令怎么样?
  • 正确 - 这将是解决方法。在启动提升的进程时设置工作目录无效。
  • @LotPings - 如果你能回答你们的问题,我会接受。

标签: windows powershell batch-file cmd


【解决方案1】:

-WorkingDirectory 参数在使用-Verb RunAs 时不起作用。相反,您必须通过在 -Command 字符串中调用 cd 来设置工作目录。

这是我使用的:(cmd/batch-file 命令)

powershell -command "   Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%cd%'; & 'PathToPS1File';`\""\""   "

如果您想在 Windows 资源管理器中创建“以管理员身份运行脚本”右键单击命令,请在 HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command 处创建一个新注册表项,并将其值设置为上述命令 - 除了将 %cd% 替换为 @ 987654331@,以及PathToPS1File%1(如果您希望它执行右键单击的文件)。

结果:(Windows 资源管理器上下文菜单 shell 命令)

powershell -command "   Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%W'; & '%1';`\""\""   "

编辑:还有另一种方法可以让脚本从资源管理器以管理员身份运行,方法是使用“runas”子键:https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files


如果您想从现有的 powershell 以管理员身份运行脚本,请删除外部 powershell 调用,将 %W 替换为 $pwd,将 %1 替换为 ps1 文件路径,并将每个 \"" 替换为只是"

注意:\"" 只是转义引号,用于从 Windows shell/命令行调用时(它的引号处理很糟糕)。在这种特殊情况下,只需 \" 也应该可以工作,但我使用更强大的 \"" 以便于扩展。

查看这里了解更多信息:https://stackoverflow.com/a/31413730/2441655

结果:(PowerShell 命令)

Start-Process PowerShell -Verb RunAs "-Command `"cd '$pwd'; & 'PathToPS1File';`""

重要提示:以上命令假设您的计算机已配置为允许执行脚本。如果不是这种情况,您可能需要将 -ExecutionPolicy Bypass 添加到您的 powershell 标志中。 (您可能还想要-NoProfileavoid running profile scripts

【讨论】:

  • 不错;然而,使用' 来引用文件系统路径是有问题的,因为' 是一个合法的文件名字符——最好使用"。对于您的最后一条命令,这意味着:Start-Process PowerShell -Verb RunAs "-Command cd \`"$pwd\`"; & \`"PathToPS1File\`""
  • 是否可以将参数传递给 .ps1 文件以使用 PathToPS1File 执行?
  • 也在试图解决这个问题。我需要将参数传递给脚本。
【解决方案2】:

一种解决方法是让 PowerShell 脚本将目录更改为它自己的来源:

Set-Location (Split-Path $MyInvocation.MyCommand.Path) 

作为第一个命令。

根据mklement0s 提示:在 PSv3+ 中使用更简单的:

Set-Location -LiteralPath $PSScriptRoot

或者使用这个目录打开相邻的文件。

$MyDir = Split-Path $MyInvocation.MyCommand.Path
$Content = Get-Content (Join-Path $MyDir OtherFile.txt)

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 2022-12-10
    • 2010-11-03
    • 2017-11-17
    • 2022-01-08
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多