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

时间:2013-10-12 13:57:43

标签: windows shell powershell batch-file

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

9 个答案:

答案 0 :(得分:214)

您需要-ExecutionPolicy参数:

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

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

答案 1 :(得分:95)

我解释了为什么要从批处理文件调用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脚本文件放在同一目录中,正如我的博客文章所描述的那样。

答案 2 :(得分:13)

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

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

最好使用Bypass ...

答案 3 :(得分:13)

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

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

答案 4 :(得分:2)

如果您想运行一些脚本,可以使用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

答案 5 :(得分:1)

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

答案 6 :(得分:1)

从批处理中执行ps脚本的另一种简便方法是将其简单地合并到ECHO和重定向字符(>和>>)之间, 示例:

@echo off
set WD=%~dp0
ECHO New-Item -Path . -Name "Test.txt" -ItemType "file" -Value "This is a text string." -Force > "%WD%PSHELLFILE.ps1"
ECHO add-content -path "./Test.txt" -value "`r`nThe End" >> "%WD%PSHELLFILE.ps1"
powershell.exe -ExecutionPolicy Bypass -File "%WD%PSHELLFILE.ps1"
del "%WD%PSHELLFILE.ps1"

最后一行删除创建的临时文件。

答案 7 :(得分:1)

也在这里发布: How to run powershell command in batch file

关注此线程:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch


您可以使用此 PowerShell 功能轻松地将任何 PowerShell 脚本转换为批处理文件:

function Convert-PowerShellToBatch
{
    param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]
        [Alias("FullName")]
        $Path
    )
 
    process
    {
        $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
        $newPath = [Io.Path]::ChangeExtension($Path, ".bat")
        "@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
    }
}


要转换目录中的所有 PowerShell 脚本,只需运行以下命令:

Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
  Convert-PowerShellToBatch

所需文件夹的路径在哪里。例如:

Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
  Convert-PowerShellToBatch


要转换单个 PowerShell 脚本,只需运行以下命令:

Get-ChildItem -Path <FILE-PATH> |
  Convert-PowerShellToBatch

所需文件的路径在哪里。

转换后的文件位于源目录中。即,

综合起来:
创建一个 .ps1 文件(PowerShell 脚本),其中包含以下代码:

function Convert-PowerShellToBatch
{
    param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]
        [Alias("FullName")]
        $Path
    )
 
    process
    {
        $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
        $newPath = [Io.Path]::ChangeExtension($Path, ".bat")
        "@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
    }
}

# change <DIR> to the path of the folder in which the desired powershell scripts are.
# the converted files will be created in the destination path location (in <DIR>).
Get-ChildItem -Path <DIR> -Filter *.ps1 |
  Convert-PowerShellToBatch


并且不要忘记,如果您只想转换一个文件而不是多个文件,您可以替换以下内容

Get-ChildItem -Path <DIR> -Filter *.ps1 |
  Convert-PowerShellToBatch

这样:

Get-ChildItem -Path <FILE-PATH> |
  Convert-PowerShellToBatch

正如我之前解释过的。

答案 8 :(得分:0)

小样本test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...
相关问题