“Out-File”创建的文件前面有空白字符

问题描述 投票:0回答:1

我正在尝试配置一个 PowerShell 脚本,该脚本将在重新启动后自行重新启动。

为此,我使用 PowerShell 脚本检查并在 Windows 启动文件夹“C:\Users\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup”中使用以下代码编写一个bat脚本:

# 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

一切似乎都工作正常,但是当尝试运行它时,我收到以下错误: “■@”不被识别为内部或外部命令、可运行程序或批处理文件。

在记事本中打开 bat 文件不会显示有问题的字符。

有人知道这可能是什么原因造成的吗?

powershell batch-file cmd powershell-5.1
1个回答
0
投票

使用

here string
作为
$Script
变量。

$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
"@
© www.soinside.com 2019 - 2024. All rights reserved.