Powershell 脚本未从批处理文件触发
我一直在尝试从批处理文件启动一个简单的 powershell 脚本。网上查了一下,建议是使用 Set-ExecutionPolicy 设置策略。
我已经完成了此操作并使用 Get-ExecutionPolicy 策略已更改。
但是,运行此批处理文件会导致出现“打开方式”对话框,而不是执行脚本。
Batch:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe ^&'./script.psl'
Powershell:
Write-Host "This is a message"
我在 Windows 7 和 Server 2008 R2 上进行了采样。两者都有相同的结果。我缺少什么?
I've been trying to launch a simple powershell script from a batch file. After looking online the advice is to set the policy using Set-ExecutionPolicy.
I've done this and using Get-ExecutionPolicy the policy has been changed.
However running this batch file results in an 'Open With' dialog rather than the execution of the script.
Batch:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe ^&'./script.psl'
Powershell:
Write-Host "This is a message"
I have sampled on both Windows 7 and Server 2008 R2. Both have same result. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要从命令行运行脚本文件,请使用 powershell.exe 的 -file 参数。
To run a script file from the command line, use the -file parameter of powershell.exe.
要从 *.cmd 文件运行脚本文件,请使用 powershell.exe 的 -file 参数和双引号:
当您在批处理文件中仅使用一个引号时,您可能会遇到如下 powershell 错误:
To run a script file from the *.cmd file , use the -file parameter of powershell.exe and double quotes:
When you will use only one quote in batch file you can expect powershell error like:
还有另一种方法可以得到此错误,该错误与文件路径中的空格相关,即使到今天,这种情况在 Windows 中仍然很常见。
假设您已经了解了在 powershell 中的常识,您需要使用反引号 `(也称为坟墓运算符)转义文件名中的空格。
然后,您可以在批处理脚本中像这样使用它来运行 powershell 脚本,这两个脚本都位于其中包含空格的目录路径的同一子目录中:
Get-ChildItem 将起作用,但 powershell 将找不到该脚本作为 -File 的参数。
事实上,事实证明,-File 参数不需要转义空格,即使 Get-ChildItem 需要转义空格。所以这会起作用:
是的,我发现了这一点,因为我正在批处理脚本中运行 powershell 脚本,原因与OP相同。 13年后。
There is another way you can get this error, associated with spaces in file paths which is still common in windows even to this very day.
Let's say you had access to the common knowledge that in powershell, you need to escape spaces in filenames with a backtick, `, also known as a grave operator.
You could then use it like this in a batch script to run a powershell script, both of which are in the same sub-directory of a directory path that has spaces in it:
Get-ChildItem will work, but powershell will not find the script as an argument of -File.
In fact, as it turns out, escaping the spaces is NOT needed for the -File argument, even as it is needed for Get-ChildItem. So this will work:
And yes I found this out because I'm running powershell script in batch script for same reason as OP. 13 years later.