繁体   English   中英

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

[英]How to run a PowerShell script from a batch file

我正在尝试在 PowerShell 中运行此脚本。 我已在桌面ps.ps1以下脚本另存为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

但我收到此错误:

在此处输入图片说明

您需要-ExecutionPolicy参数:

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

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

在我的博客文章中解释了为什么要从批处理文件中调用 PowerShell 脚本以及如何执行此操作

这基本上就是你要找的:

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 脚本的整个路径,正如我的博客文章所述。

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

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

如果你以管理员身份运行一个调用 PowerShell 的批处理文件,你最好这样运行它,省去你所有的麻烦:

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

最好使用Bypass ...

小样本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...

如果你想运行几个脚本,你可以使用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

从批处理中执行 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"

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

如果您的 PowerShell 登录脚本在 2012 年服务器上运行 5 分钟(就像我的一样),则服务器上有一个 GPO 设置-“配置登录脚本延迟”默认设置“未配置”这将留下 5 分钟的延迟在运行登录脚本之前。

也在这里发布: 如何在批处理文件中运行 powershell 命令

按照这个线程:
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

所需文件的路径在哪里。

转换后的文件位于源目录中。 即, <FILE-PATH><DIR-PATH>

把它们放在一起:
创建一个 .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

正如我之前解释的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM