删除 txt 文件中空白行的命令不适用于文件路径中的变量

删除 txt 文件中空白行的命令不适用于文件路径中的变量

当我使用变量时,删除 List.txt 文件中的空白行的命令不起作用$env:username

有效:在文件路径中使用 CMG 用户名。

$linblk = [System.IO.File]::ReadAllText('C:\Users\CMG\Desktop\List.txt');$linblk = $linblk.Trim();[System.IO.File]::WriteAllText('C:\Users\CMG\Desktop\List.txt', $linblk)

不起作用:$env:username在文件路径中使用变量:

$linblk = [System.IO.File]::ReadAllText('C:\Users\$env:username\Desktop\List.txt');$linblk = $linblk.Trim();[System.IO.File]::WriteAllText('C:\Users\$env:username\Desktop\List.txt', $linblk)
Exception when calling "ReadAllText" with "1" argument(s): "The given path format is not supported."
No line:1 character:1
+ $linblk = [System.IO.File]::ReadAllText('C:\Users\$env:username\Deskt ...


+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

如何让命令接受变量$env:username

已编辑
所以它起作用了:答案中的命令@Vomit IT - Chunky Mess Style

$linblk = [System.IO.File]::ReadAllText("C:\Users\$($env:username)\Desktop\List.txt");
$linblk = $linblk.Trim();
[System.IO.File]::WriteAllText("C:\Users\$($env:username)\Desktop\List.txt", $linblk)

答案1

使用[System.IO.File]::ReadAllText("C:\Users\$env:username\Desktop\List.txt")语法将参数值括在双引号中。

电源外壳

$linblk = [System.IO.File]::ReadAllText("C:\Users\$env:username\Desktop\List.txt");
$linblk = $linblk.Trim();
[System.IO.File]::WriteAllText("C:\Users\$env:username\Desktop\List.txt", $linblk)

PowerShell(另一种变体)

$file = Get-Content "C:\Users\$env:username\Desktop\List.txt"
$file | % {$_.Trim()} | Set-Content "C:\Users\$env:username\Desktop\List.txt"

支持资源

相关内容