powershellbatch-filecmdcharacter-encodingpowershell-5.1

Blank character in front of "Out-File"-created file


I am trying to configure a PowerShell script that will restart itself after reboot.

In order to do so, I have the PowerShell script check and write a bat-script in the Windows Startup folder "C:\Users<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" with the following code:

# Creates a startup script to restart the process after a reboot.
$Location = "$Env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\Restart.bat"
$Script = "
@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`"
)
powershell.exe -NoLogo -NoExit -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath
"
if(!(Test-Path $Location)){
    $Script | Out-File -FilePath $Location -Force

Everything seems to be working fine, but when attempting to run it I get the following error: '■@' is not recognized as an internal or external command, operable program or batch file.

Opening the bat-file in Notepad doesn't show the character in question.

Would anyone know what might be causing this?


Solution

  • tl;dr


    SomethingDark has provided the crucial pointer:

    Your problem is one of character encoding:

    See the bottom section of this answer for how to make cmd.exe sessions as well as PowerShell sessions use (BOM-less) UTF-8 as the OEM code page via autorun commands / profile files, as a less drastic alternative to the aforementioned system-wide change.


    As for the specific symptom, '■@' is not recognized ...: