windows - 如何使用正确的工作目录从 BAT 文件启动 PowerShell 脚本?

标签 windows powershell batch-file cmd

我正在尝试创建 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

以这种方式传递工作目录是行不通的。

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

最佳答案

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

这是我使用的:(cmd/批处理文件命令)

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% 替换为 %W,并将 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 文件路径,并将每个 \"" 替换为 "

Note: The \""'s are just escaped quotes, for when calling from the Windows shell/command-line (it's quote-handling is terrible). In this particular case, just \" should also work, but I use the more robust \"" for easier extension.

See here for more info: https://stackoverflow.com/a/31413730/2441655

结果:(PowerShell 命令)

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

Important note: The commands above are assuming that your computer has already been configured to allow script execution. If that's not the case, you may need to add -ExecutionPolicy Bypass to your powershell flags. (you may also want -NoProfile to avoid running profile scripts)

关于windows - 如何使用正确的工作目录从 BAT 文件启动 PowerShell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44284964/

相关文章:

image-processing - 批量处理EPS转JPG的工具

java - 从内存棒安装jdk的批处理文件

windows - Windows 上的 pg_upgrade 无法写入日志文件 pg_upgrade_internal.log

windows - ffmpeg 和 ffprobe 嵌套延迟扩展变量

powershell - 使用Powershell创建IIS 6.0应用程序池

powershell - 如何使用 PowerShell 从远程计算机获取所有(IIS)网站状态/状态?

batch-file - 仅当之前已多次启用 RDP 时,通过更改注册表设置来启用 RDP 才有效

c - 添加到 HIMageList 失败,无法找出原因

linux - python3中window和linux的文件路径有什么区别?

Powershell:替换为西里尔字符串