【问题标题】:Outputting to log file fails, but PS6 script runs with no errors输出到日志文件失败,但 PS6 脚本运行没有错误
【发布时间】:2018-03-16 23:53:47
【问题描述】:

我有其他导出 csv 文件的软件,当一切正常运行时,我在 csv 中有 1291 行。我正在尝试轻松识别哪些文件不完整。

这是我第一次尝试 PowerShell。我修改了在 stackoverflow 上找到的这段代码:

$files = Get-ChildItem 'd:\*.txt'

ForEach ($file in $files) {
    $lineCount = Get-Content -LiteralPath $file | Measure-Object | Select-Object -ExpandProperty Count
    Write-Output "File $($file.Name) has $lineCount lines"
    if ($lineCount -gt 50) {
        Write-Warning "Warning $($file.Name) is too big"
    }
}

并设法做到这一点而没有出错:

$files = Get-ChildItem 'D:\!__DATA for searches\__CSVs\*.csv'

$logfile = 'D:\!__DATA for searches\__CSVs\CompletedFiles.txt'

ForEach ($file in $files) {
    $lineCount = Get-Content -LiteralPath $file | Measure-Object | Select-Object -ExpandProperty Count
    Write-Output "File $($file.Name) has $lineCount lines"
    if ($lineCount -gt 1290) {
        Write-Warning "Warning $($file.Name) is completed"   | Out-File $logfile -Append
    } 
}

还有这个变化

$files = Get-ChildItem 'D:\!__DATA for searches\__CSVs\*.csv'

ForEach ($file in $files) {
    $lineCount = Get-Content -LiteralPath $file | Measure-Object | Select-Object -ExpandProperty Count
    Write-Output "File $($file.Name) has $lineCount lines"
    if ($lineCount -gt 1290) {
        Write-Warning "Warning $($file.Name) is completed"  | Out-File 'D:\!__DATA for searches\__CSVs\CompletedFiles.txt' -append
   } 
}

但都不写入日志文件。该脚本在 PS6 控制台中运行良好,识别出 1291 行的文件。

所以我需要日志文件,另外我还想将完成的文件移动到同一脚本中的另一个目录,因此非常感谢您输入什么/在哪里实现这一点。

感谢答案和其他研究,我完成了脚本

$files = Get-ChildItem 'D:\!__DATA for searches\__CSVs\*.csv'
$logfile = 'D:\!__DATA for searches\__CSVs\CompletedFiles.txt'

ForEach ($file in $files) {
    $lineCount = Get-Content -LiteralPath $file | Measure-Object | Select-Object -ExpandProperty Count
#    Write-Output "File $($file.Name) has $lineCount lines"
    if ($lineCount -gt 1290) {
#        Write-Warning "Warning $($file.Name) is completed" 3>&1 |Out-File $logfile -Append
    Write-Output  "File $($file.Name) has $lineCount lines, and moving to D:\Completed\" 3>&1 | Out-File $logfile -Append
     Move-Item "D:\!__DATA for searches\__CSVs\$($file.Name)" "D:\!__DATA for searches\Completed\" -Force
   } 
}

【问题讨论】:

    标签: powershell export-to-csv


    【解决方案1】:

    Write-Warning 不会向stdout 发送任何内容。

    您可以使用类似于cmd 的语法重定向警告流:

    Write-Warning "Warning $($file.Name) is completed" 3>> $logfile
    

    Write-Warning "Warning $($file.Name) is completed" 3>&1 |Out-File $logfile -Append
    

    【讨论】:

    • @user3345612 提到的它在 pwsh 中的行为如何
    • @Mathias R. Jessen 我使用了您的第二个选项,感谢您提供我需要的答案
    • @PRASOON KARUNAN V 不确定您的评论,但使用当前代码,脚本会打开一个控制台窗口,但会静默运行,并且窗口会在没有写入任何内容的情况下关闭
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2019-10-18
    • 1970-01-01
    • 2022-01-01
    • 2015-06-01
    • 2012-07-24
    • 1970-01-01
    • 2023-02-21
    相关资源
    最近更新 更多