Powershell 如何在读取后清除文件内容

Powershell 如何在读取后清除文件内容,powershell,Powershell,读取数据和随后清理文件的操作必须在一个会话中进行。其他进程不应访问该文件 $FileTwo = [System.io.File]::Open('C:\FiLeTwo.txt', "Open", "Read", "None") $FileTwo2 = New-Object System.IO.StreamReader($FileTwo) $text = $text + $FileTwo2.ReadToEnd() $text = $text -replace '\ ' -replace 'g'

读取数据和随后清理文件的操作必须在一个会话中进行。其他进程不应访问该文件

$FileTwo = [System.io.File]::Open('C:\FiLeTwo.txt', "Open", "Read", "None") 
$FileTwo2 = New-Object System.IO.StreamReader($FileTwo)
$text = $text + $FileTwo2.ReadToEnd()

$text = $text -replace '\ ' -replace 'g' -replace '\(' -replace '\)' -replace $re, "" #-replace '\n'
# Set-Content 'C:\FiLeTwo.txt' "" -Force 
# IN that moment I need to clear the file. 
# But I need cleare the file and,  after, close the File ($FileTwo.Close())

$FileTwo.Close()

您可以使用
清除内容
擦除文件内容,但不能删除它

例如:
清除内容c:\path\to\your\file.txt

您可以在此处阅读更多信息:
您甚至不需要使用这么多流:

$path = 'C:\FiLeTwo.txt'
$text = Get-Content $path -Raw
Clear-Content $path
$text = $text -Replace ...
如果要使用
FileStream
,还可以使用
SetLength
删除内容:

# open with "ReadWrite"
$fileTwo = [System.IO.File]::Open("C:\FiLeTwo.txt", "Open", "ReadWrite", "None") 
try {
    # ... read, replace etc ...
    # clear the contents:
    $fileTwo.SetLength(0);
}
finally {
    # make sure to put this in a finally block!
    $fileTwo.Dispose()
}

(确保在finally块中正确处理所有流!)

这就是我需要的-$fileTwo.SetLength(0);我需要为其他应用程序删除该文件。谢谢你,玛斯!