gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:23:29 38 4
gpt4 key购买 nike

我正在集成两个通过 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/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com