powershell - 重定向到 null 是在 PowerShell 脚本中丢弃行的正确方法吗?

标签 powershell csv if-statement

我正在集成两个通过 CSV 文件相互通信的软件,但应用程序 A 的输出文件需要进行一些后处理,然后应用程序 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

最佳答案

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

您有四个选项来抑制 stdout 流(也称为 &1successoutput >).

  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

有关Switch的额外信息:

The Default keyword specifies a condition that is evaluated
only when no other conditions match the value.

The action for each condition is independent of the actions in
other conditions. The closing brace ( } ) in the action is an
explicit break.

关于powershell - 重定向到 null 是在 PowerShell 脚本中丢弃行的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48447917/

相关文章:

Powershell New-ScheduledTaskSettingsSet

azure - 如何使用 PowerShell 为已停止的 Azure Web App 禁用 Kudu (SCM)?

c# - 为什么 File.WriteAllBytes 不适用于 .db 文件但适用于 .csv 文件?

php - 将新条件添加到 header if 语句中 - 如果 URI 是某个页面,则不显示在网站上其他任何地方显示的代码

java - 如果这个变量可以是三个不同类之一,我该如何声明它?

powershell - 获取当前目录下子文件夹中文件的相对路径

c++ - 文本文件的C++ getline

php - 在 PHP 或 Javascript 上将大型 Excel/Csv 文件拆分为多个文件

MYSQL Event IF 然后运行查询

windows - 用于获取运行 Windows Server 2012 的服务器上安装的所有语言包的 Powershell 命令