将PS2脚本的输出写入文本文件

时间:2015-07-17 12:51:36

标签: powershell powershell-v2.0

我有以下脚本:

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

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

2 个答案:

答案 0 :(得分:4)

将其转发至`[[<-` = function (x, i, value) { if (exists(x, mode = 'environment', inherits = TRUE)) assign(i, value, pos = x, inherits = FALSE) else if (exists(x, inherits = FALSE) internal_assign(x, i, value) else assign(x, list(i = value), pos = parent.frame(), inherits = FALSE) } 。例如:

Out-File

答案 1 :(得分: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"