我也在这里发布了:如何在批处理文件中运行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
其中“path”是所需文件夹的路径。例如:
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
}
}
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
不要忘记,如果你只想转换一个文件而不是多个文件,可以替换以下内容。
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
用这个:
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
就像我之前解释的那样。
pwsh.exe
而不是powershell.exe
。 简单解释:powershell.exe
是v5.1-,而pwsh.exe
是6.0+。更多信息。 - ruffin