Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Powershell脚本中删除文件的每一行_Powershell - Fatal编程技术网

如何从Powershell脚本中删除文件的每一行

如何从Powershell脚本中删除文件的每一行,powershell,Powershell,我有一个包含以下内容的文件: 123 234 345 我使用foreach循环读取文件的每一行 我有这样一个要求:我想删除foreach循环中文件的每一行 在foreach循环中是否有删除文件行的方法 以下是我尝试过的: $source1 = "Y:\New Documents\test.txt" foreach ($line in Get-Content $source1) { $find = $line (Get-Content $source1).replace($find

我有一个包含以下内容的文件:

123 234 345

我使用foreach循环读取文件的每一行

我有这样一个要求:我想删除foreach循环中文件的每一行

在foreach循环中是否有删除文件行的方法

以下是我尝试过的:

$source1 = "Y:\New Documents\test.txt"
foreach ($line in Get-Content $source1) {
    $find = $line
    (Get-Content $source1).replace($find,"") |
        Set-Content $source1
}

我可以清除文件的内容,但我不知道如何使文件大小为零。

您要做的就是截断文件。PowerShell有一个cmdlet用于:

Clear-Content $source1
如果要先执行某些处理:先执行该操作,然后清除文件:

Get-Content $source1 | ForEach-Object {
    # do stuff with content of $source1
}

Clear-Content $source1
$remains = Get-Content $source1 | ForEach-Object {
    if (<# some condition or other #>) {
        # do stuff with matching lines
    } else {
        # output back to pipeline
        $_
    }
}

# write $remains back to file if it's not empty, otherwise clear file
if ($remains) {
    $remains | Set-Content $source1
} else {
    Clear-Content $source1
}
如果在一种或另一种情况下需要处理内容并保留行,则可以收集应保留在变量中的行并将其写回文件:

Get-Content $source1 | ForEach-Object {
    # do stuff with content of $source1
}

Clear-Content $source1
$remains = Get-Content $source1 | ForEach-Object {
    if (<# some condition or other #>) {
        # do stuff with matching lines
    } else {
        # output back to pipeline
        $_
    }
}

# write $remains back to file if it's not empty, otherwise clear file
if ($remains) {
    $remains | Set-Content $source1
} else {
    Clear-Content $source1
}

删除每一行会将一个空文件作为输出。你到底在找什么。请详细说明。假设我想从文件中读取123,然后我会做其他事情,然后想从文件中删除123,我想这样做,最后我想将空文件作为outputClear Content$文件?为什么要删除每一行?只要读取文件,处理它,然后清除它。@Rab业务是错误的。没有合乎逻辑的理由这么做。