【问题标题】:Write output of PS2 script to textfile将 PS2 脚本的输出写入文本文件
【发布时间】:2015-07-17 23:52:16
【问题描述】:

我有以下脚本:

Get-ChildItem $rootPath -Recurse | 
    Where-Object {$_.PSIsContainer} | 
    Where-Object {(Get-ChildItem $_.FullName | Where-Object {!$_.PSIsContainer}|  Measure-Object | Select-Object -ExpandProperty Count) -gt 0} |
    ForEach-Object{

        $files = Get-ChildItem $_.FullName

        $props = @{
            Path = $_.FullName
            Size = "{0:N0}" -f (($files | Where-Object {!$_.PSIsContainer} |  Measure-Object -Sum Length | Select-Object -ExpandProperty Sum))
            Count = $files | Measure-Object | Select-Object -ExpandProperty Count
        }

        If ($files.Extension -match "L\d\d"){
            # These are special files and we are assuming they are alone in the directory
            # Change the path
            $props.Path = $files | Select-Object -First 1 | Select-Object -ExpandProperty FullName
        }

        New-Object -TypeName PSCustomObject -Property $props

} | Select Path,Size,Count

如何将输出写入文本文件而不是控制台?

【问题讨论】:

标签: powershell powershell-2.0


【解决方案1】:

转发给Out-File。例如:

Get-ChildItem ...
<skipped>
} | Select Path,Size,Count | Out-File "files.txt"

【讨论】:

    【解决方案2】:

    有几件事。您还有其他值得一提的选择。

    } | Select Path,Size,Count | Set-Content "files.txt"
    

    Set-Content 也可以工作,并且具有默认为 ACSII 编码的优点。如果性能发挥作用,那么使用 .Net StreamWriter 无论如何都会击败 Set-ContentOut-File

    更重要的是,此代码旨在输出对象。使用它,您应该使用Export-CSV 以获得格式良好的输出。

    } | Select Path,Size,Count | Export-Csv -NoTypeInformation "files.csv"
    

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2017-01-09
      • 2016-07-13
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多