我正在尝试创建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
以这种方式传递工作目录不起作用。
如何制作能够传递正确工作的directroy以及命令行参数的脚本?
答案 0 :(得分:0)
解决方法是让PowerShell脚本使用以下命令将目录更改为自己的源:
Samples of bufferSize = 512 on iOS:
[0.0166742969, 0.0181432627, 0.0184620395, 0.0182254426, 0.0181945376, 0.0185530782, 0.0192517322, 0.0199078992, 0.0204724055, 0.0212812237, 0.022370765, 0.0230008475, 0.0225516111, 0.0213304944, 0.0200473778, 0.019841563, 0.0206818394, 0.0211550407, 0.0207783803, 0.020227218 ....
Samples of bufferSize = 512 on Python:
[ -52. -32. -11. 10. 24. 31. 37. 38. 33. 25. 10. -4.
-18. -26. -29. -39. ....
作为第一个命令。
或使用此目录打开相邻文件。
Set-Location (Split-Path $MyInvocation.MyCommand.Path)
答案 1 :(得分:0)
使用-WorkingDirectory
时-Verb RunAs
参数不起作用。相反,您必须通过在cd
字符串中调用-Command
来设置工作目录。
这就是我使用的:(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
处创建一个新的注册表项,并将其值设置为上述命令-替换{{1 }}和%cd%
,%W
和PathToPS1File
(如果您希望它执行右键单击的文件)。
结果:(Windows资源管理器上下文菜单shell命令)
%1
编辑:还有一种替代方法,可以使用“ runas”子键通过https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files
从资源管理器中以管理员身份运行脚本。如果要从现有Powershell以管理员身份运行脚本,请删除外部Powershell调用,将powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%W'; & '%1';`\""\"" "
替换为%W
,将$pwd
替换为ps1文件路径,然后将每个%1
替换为\""
。
注意:
"
只是转义的引号,用于从Windows Shell /命令行调用时(它的引号处理很糟糕)。在这种特殊情况下,\""
也应该起作用,但是我使用功能更强大的\"
来简化扩展。有关更多信息,请参见此处:https://stackoverflow.com/a/31413730/2441655
结果:(PowerShell命令)
\""
重要说明:上面的命令假定您的计算机已经配置为允许执行脚本。如果不是这种情况,则可能需要在Powershell标志中添加
Start-Process PowerShell -Verb RunAs "-Command `"cd '$pwd'; & 'PathToPS1File';`""
。 (您可能还希望-ExecutionPolicy Bypass
到avoid running profile scripts)