繁体   English   中英

将bat文件转换为powershell脚本

[英]Convert bat file to powershell script

我有一个执行 exe 文件并在 txt 文件中传递一些参数的 simple.bat 文件。 我如何在 powershell 脚本(.ps1 文件)中实现相同的功能?

.bat 文件内容:

@echo on
C:\Windows\System32\cmd.exe /C "C:\Program Files\BMC Software\AtriumCore\cmdb\server64\bin\cmdbdiag.exe" -u test -p test -s remedyar -t 41900 < "C:\Program Files\BMC Software\ARSystem\diserver\data-integration\batch\CleanupInputs.txt" > "C:\Program Files\BMC Software\ARSystem\diserver\data-integration\batch\Snow_Output\DailyOutput.log"
Exit 0

从根本上说,在 PowerShell 中调用控制台应用程序的方式与在cmd.exe中的方式相同,但存在重要区别:

# If you really want to emulate `@echo ON` - see comments below.
Set-PSDebug -Trace 1 

# * PowerShell doesn't support `<` for *input* redirection, so you must
#   use Get-Content to *pipe* a file's content to another command.
# * `>` for *output* redirection *is* supported, but beware encoding problems:
#     * Windows PowerShell creates a "Unicode" (UTF-16LE) file,
#     * PowerShell (Core, v6+) a BOM-less UTF-8 file.
#     * To control the encoding, pipe to Out-File / Set-Content with -Encoding
# * For syntactic reasons, because your executable path is *quoted*, you must
#   invoke it via `&`, the call operator.
Get-Content "C:\..\CleanupInputs.txt" | 
  & "C:\...\cmdbdiag.exe" -u test -p test -s remedyar -t 41900 > "C:\...\DailyOutput.log"

# Turn tracing back off.
Set-PSDebug -Trace 0

exit 0

笔记:

  • 为简洁起见,我已将命令中的长目录路径替换为...

  • 字符编码注意事项

    • 当 PowerShell 与外部程序通信时,它只“说文本”(它通常从不通过其管道传递原始字节(从 v7.2 开始)),因此可能涉及编码和解码字符串的多次传递; 具体来说:

    • Get-Content不只是路径文本文件的原始字节,它会将内容解码.NET 字符串,然后通过管道逐行发送内容。 如果输入文件缺少 BOM,则 Windows PowerShell 假定活动 ANSI 编码,而 PowerShell (Core) 7+ 假定 ZAE957B3DF9087BBC49 您可以使用-Encoding参数显式指定编码。

    • 由于接收命令是外部程序(可执行文件),PowerShell(重新)- 根据$OutputEncoding首选项变量(默认为 Windows Z3D265B4E1EEB118DDFZ178 中的 ASCII(,)),在将它们发送到程序之前对其进行编码 和 PowerShell(核心)7+ 中的 UTF-8。

    • 由于> - 实际上是Out-File的别名 - 用于将外部程序重定向到文件,因此会发生另一轮解码和编码:

      • PowerShell 首先将外部程序的 output解码为 .NET 字符串,基于存储在[Console]::OutputEncoding中的字符编码,默认为活动OEM代码页系统
      • Then Out-File encodes the decoded strings based on its default encoding, which is UTF-16LE ("Unicode") in Windows PowerShell, and BOM-less UTF-8 in PowerShell (Core); 要控制编码,您需要显式使用Out-File (或Set-Content )并使用其-Encoding参数。

也可以看看:

  • about_Redirection

  • & , 呼叫运算符

  • 这个答案讨论了 PowerShell 版本中的默认编码; 简而言之:它们在 Windows PowerShell 中差异很大,但 PowerShell(核心)7+ 现在始终使用无 BOM 的 ZAE37D3DF5970B4966。


重新执行跟踪:在批处理文件中使用@echo ON以及它与 PowerShell 的比较
Set-PSDebug -Trace 1

  • 批处理文件通常使用@echo OFF运行,以免在打印 output 之前回显每个命令本身。
    • 但是, @echo ON (或完全省略@echo ON/OFF语句)有助于诊断执行期间的问题
    • Set-PSDebug -Trace 1类似于@echo ON ,但它有一个缺点:命令的原始源代码被回显,这意味着您不会看到嵌入式变量引用和表达式的- 请参阅此答案了解更多信息信息。

暂无
暂无

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

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