Out-File生成的bat文件前含空白字符导致运行报错问题排查
问题原因及解决办法
这个错误是UTF-8 BOM(字节顺序标记)或Unicode编码导致的:
- PowerShell的
Out-Filecmdlet默认使用Unicode(UTF-16LE)编码生成文件,部分PowerShell版本也可能默认生成带BOM的UTF-8文件。 - Windows的cmd.exe(执行bat文件的程序)无法识别这类编码文件开头的BOM字符,会把它当成脚本的第一个命令的一部分,也就是你看到的
■@,从而触发报错。 - 记事本会自动处理BOM字符,所以你看不到这个隐藏标记。
解决方法
修改生成bat文件的代码,使用cmd能识别的编码(ANSI或无BOM的UTF-8):
方案1:使用Set-Content(推荐)
Set-Content默认使用ANSI编码,完全兼容cmd,替换原代码中的Out-File即可:
if(!(Test-Path $Location)){ $Script | Set-Content -FilePath $Location -Force }
方案2:指定Out-File的编码
如果你坚持用Out-File,可以明确指定编码为ASCII或无BOM的UTF-8:
# PowerShell 5.1及更早版本用ASCII编码 if(!(Test-Path $Location)){ $Script | Out-File -FilePath $Location -Force -Encoding ASCII } # PowerShell 6+版本可直接指定无BOM的UTF-8 if(!(Test-Path $Location)){ $Script | Out-File -FilePath $Location -Force -Encoding UTF8NoBOM }
另外补充:原bat脚本里的goto Continue没有对应的:Continue标签,运行时会报错找不到标签,建议在powershell.exe执行行前加上:Continue标记:
@echo off REM Verifies if the script is running as admin. net session >nul 2>&1 if %errorLevel% == 0 ( goto Continue ) else ( REM Restarts the script as admin. powershell -command "Start-Process %~dpnx0 -Verb runas" ) :Continue powershell.exe -NoLogo -NoExit -NoProfile -ExecutionPolicy Bypass -File %~dp0YourScriptName.ps1
内容的提问来源于stack exchange,提问作者Al D. J.
相关产品推荐
相关产品推荐

