【问题标题】:Overwriting output file?覆盖输出文件?
【发布时间】:2016-11-19 17:40:46
【问题描述】:

我正在将日志文件中的一些错误提取到一个单独的文件中。

我正在搜索的错误在一个小块中定义:

# Define all the error types that we need to search on
$error_6  = "Missing coded entry in table for provider sector category record"
$error_7  = "not a well-formed email address"
$error_8  = "Org Id must not contain invalid characters"
$error_9  = "Missing sub type code for provider type category record"
$error_10 = "Provider sub type"

然后我读入源日志文件并删除匹配的行。

奇怪的是,如果我将它们转储到单独的文件中,我会在每个文件中得到正确的行数,但如果我使用同一个文件,我只会得到一行。我以为它会附加到文件中。

这不起作用(只有一行输出):

(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_6 } |   Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_7 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_8 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_9 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_10 } | Set-Content $path\known_errors.log

作品(共16行输出):

(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_6 } | Set-Content $path\known_errors_6.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_7 } | Set-Content $path\known_errors_7.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_8 } | Set-Content $path\known_errors_8.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_9 } | Set-Content $path\known_errors_9.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_10 } | Set-Content $path\known_errors_10.log

【问题讨论】:

  • 您确实意识到,通过将“不匹配”更改为“匹配”,previous question 的答案也适用于此,不是吗?

标签: file powershell append


【解决方案1】:

Set-Content 总是 创建一个新文件。

https://technet.microsoft.com/en-us/library/hh849828.aspx

设置内容
用新内容写入或替换项目中的内容。

您需要使用Add-Content 向现有文件添加数据。

https://technet.microsoft.com/en-us/library/hh849859.aspx

添加内容
向指定项添加内容,例如添加单词 到一个文件。

【讨论】:

    【解决方案2】:

    或者你可以使用:

    (Get-Content $path\temp_report.log) | Where-Object { $_ -match  $error_6 } |  out-file $path\known_errors.log -Append
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 2016-02-13
      • 2015-03-14
      • 2013-01-25
      • 2017-02-08
      • 2018-08-20
      • 2018-05-31
      相关资源
      最近更新 更多