我正在尝试在PowerShell中运行此脚本。我已将下面的脚本保存为桌面上的ps.ps1
。
$query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"
Register-WMIEvent -Query $query -Action { invoke-item "C:\Program Files\abc.exe"}
我创建了一个批处理脚本来运行此PowerShell脚本
@echo off
Powershell.exe set-executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
pause
但是我得到了这个错误:
9条答案
按热度按时间sr4lhrrt1#
你需要
-ExecutionPolicy
参数:否则,PowerShell会将参数视为要执行的行,而
Set-ExecutionPolicy
* 是 * 一个cmdlet,它没有-File
参数。hsgswve42#
我解释了为什么要从批处理文件调用PowerShell脚本以及如何执行in my blog post here。
这基本上就是你要找的:
如果您需要以管理员身份运行PowerShell脚本,请使用以下命令:
我建议将批处理文件和PowerShell脚本文件放在同一个目录中,而不是硬编码到PowerShell脚本的整个路径,正如我的博客文章所描述的那样。
vxqlmq5t3#
如果要在没有完全限定路径的情况下从当前目录运行,可以用途:
dwthyt8l4#
如果你以管理员身份运行一个调用PowerShell的批处理文件,你最好像这样运行它,这样可以省去所有的麻烦:
最好使用
Bypass
。7lrncoxx5#
这允许批处理文件在其中包含PowerShell代码(保存为
test.cmd
或test.bat
)8iwquhpp6#
也在这里发布:如何在批处理文件中运行powershell命令
跟随这个线程:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch
您可以使用此PowerShell函数轻松地将任何PowerShell脚本转换为批处理文件:
要转换目录中的所有PowerShell脚本,只需运行以下命令:
其中是所需文件夹的路径。例如:
要转换单个PowerShell脚本,只需运行以下命令:
其中是所需文件的路径。
转换后的文件位于源目录中。即 或 。
将所有内容放在一起:
创建一个.ps1文件(PowerShell脚本),其中包含以下代码:
别忘了,如果你只想转换一个文件而不是许多文件,你可以替换以下文件
用这个:
正如我之前解释过的。
8iwquhpp7#
如果你想运行一些脚本,你可以使用
Set-executionpolicy -ExecutionPolicy Unrestricted
,然后用Set-executionpolicy -ExecutionPolicy Default
重置。请注意,执行策略仅在您开始执行时才会被检查(或者看起来是这样),因此您可以在后台运行作业并立即重置执行策略。
g6baxovj8#
另一种从批处理中执行ps脚本的简单方法是将其简单地合并在ECHO和重定向字符(>和>>)之间,例如:
最后一行删除创建的临时文件。
tcomlyy69#
如果您的PowerShell登录脚本在2012服务器上运行5分钟后(如我的),则服务器上有一个GPO设置-“配置登录脚本延迟”默认设置“未配置”,这将在运行登录脚本之前留下5分钟的延迟。