powershell 修剪 - 删除字符串后的所有字符

sam*_*sux 7 powershell trim

在字符串 (\test.something) 之后删除所有内容的命令是什么。我在文本文件中有信息,但是在字符串之后有 1000 行我不想要的文本。如何删除包括字符串在内的所有内容。

这就是我所拥有的 - 不工作。非常感谢。

$file = get-item "C:\Temp\test.txt"

(Get-Content $file) | ForEach {$_.TrimEnd("\test.something\")} | Set-Content $file
Run Code Online (Sandbox Code Playgroud)

Lin*_*est 6

为什么之后删除所有内容?只需保持一切正常(我将使用两行以提高可读性,但您可以轻松组合成单个命令):

$text = ( Get-Content test.txt | Out-String ).Trim() 
#Note V3 can just use Get-Content test.txt -raw
$text.Substring(0,$text.IndexOf('\test.something\')) | Set-Content file2.txt
Run Code Online (Sandbox Code Playgroud)

此外,您可能不需要 Trim,但您使用的是 TrimEnd,因此添加以备以后添加。)


mjo*_*nor 5

使用 -replace

(Get-Content $file -Raw) -replace '(?s)\\test\.something\\.+' | Set-Content $file
Run Code Online (Sandbox Code Playgroud)