首页 文章

如何从批处理文件运行PowerShell脚本

提问于
浏览
135

我试图在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

但是我收到了这个错误:

Enter image description here

6 回答

  • 1

    我解释了为什么要从批处理文件调用PowerShell脚本以及如何执行它in my blog post here .

    这基本上就是你要找的东西:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
    

    如果您需要以管理员身份运行PowerShell脚本,请使用以下命令:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Users\SE\Desktop\ps.ps1""' -Verb RunAs}"
    

    虽然不是硬编码PowerShell脚本的整个路径,但我建议将批处理文件和PowerShell脚本文件放在同一目录中,正如我的博客文章所描述的那样 .

  • 11

    如果要运行几个脚本,可以使用 Set-executionpolicy -ExecutionPolicy Unrestricted 然后使用 Set-executionpolicy -ExecutionPolicy Default 重置 .

    请注意,只有在您开始执行时(或看起来如此)才会检查执行策略,因此您可以在后台运行作业并立即重置执行策略 .

    # Check current setting
    Get-ExecutionPolicy
    
    # Disable policy
    Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    # Choose [Y]es
    
    Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
    Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com  | tee ping__google.com.txt  }
    
    # Can be run immediately
    Set-ExecutionPolicy -ExecutionPolicy Default
    # [Y]es
    
  • 85

    您需要 -ExecutionPolicy 参数:

    Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1
    

    否则,PowerShell会将参数视为要执行的行,而 Set-ExecutionPolicy 是cmdlet,它没有 -File 参数 .

  • 12

    如果您的PowerShell登录脚本在2012服务器上运行5分钟后(如我的那样),则服务器上存在GPO设置 - “配置登录脚本延迟”默认设置“未配置”这将导致5分钟延迟在运行登录脚本之前 .

  • 2

    如果要从没有完全限定路径的当前目录运行,可以使用:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"
    
  • 182

    如果您运行以管理员身份调用PowerShell的批处理文件,最好像这样运行它,为您节省所有麻烦:

    powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
    

    最好使用 Bypass ...

相关问题