是否重定向为null以在PowerShell脚本中丢弃行的正确方法?

Dav*_*vid 2 csv powershell if-statement

我正在整合两个通过CSV文件相互通信的软件,但是App A的输出文件需要进行一些后期处理才能让App B拿起它.

下面的代码将数据附加到以"C"开头的行,同时丢弃现在的其他三种可能性,因为这些部分将在以后添加.

$ _> null是我提出的,因为我找不到会删除IF语句中的行的代码片段.它似乎有效,但我想确定它是否正确.TIA

$original = "input.txt"
$destination = "output.txt"
$tempfile = [IO.Path]::GetTempFileName()
get-content $original | foreach-object {
  if ($_ -match "^C,") {
    $_ + ",append this" >> $tempfile
  }
  elseif ($_ -match "^J,") {
    $_ > null
  }
  elseif ($_ -match "^B,") {
    $_ > null
  }
  elseif ($_ -match "^O,") {
    $_ > null
  }
  else {
    $_ >> $tempfile
  }
}
copy-item $tempfile $destination
remove-item $tempfile
Run Code Online (Sandbox Code Playgroud)

The*_*le1 5

这不适用于您正在做的事情,但它回答了您的初始问题:

您有四个选项,以抑制stdout流(也被称为&1,successoutput).

  1. [Void]() 类型转换
  2. $Null = () 分配
  3. () > $Null 重定向
  4. () | Out-Null cmdlet(注意这是选项中最慢的一个数量级)

此代码块应解决您的问题:

$original = 'input.txt'
$destination = 'output.txt'
$tempfile = [IO.Path]::GetTempFileName()

Switch -Regex -File $original
{
    '^C,' { "$_,append this" | Out-File -FilePath $tempfile -Append }
    '^[JBO],' { }
    'Default' { $_ | Out-File -FilePath $tempfile -Append }
}
Copy-Item -Path $tempfile -Destination $destination
Remove-Item -Path $tempfile
Run Code Online (Sandbox Code Playgroud)

有关Switch以下内容的更

所述Default关键字指定被评估的条件
时,没有其他条件相匹配的值只.

每个条件的操作与
其他条件中的操作无关.动作中的右括号(})是
显式的break.