PowerShell:使用Out-File将Dir列表的特定部分写入文本文件

时间:2016-04-28 20:44:06

标签: powershell

所以我知道如何使用Out-File将完整的目录列表写入文本文件,但我的问题是我只想将目录的某些部分写入文件,即我只想写目录名,文件名,文件长度和上次写入时间。

以下是我的尝试:

我使用"〜"作为一个分隔符。

cls

$Path = "C:\Testpath"
$OutFile = "C:\Testpath\Output.txt"

gci -Path $Path -Recurse | % { $_.Directory + "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") } | Out-File $Outfile

它似乎创建了文件并写了几行,然后我多次得到此错误,直到脚本完成。只写了几行似乎是父文件夹中的子文件夹。

错误:

+ : Method invocation failed because [System.IO.DirectoryInfo] doesn't contain a method named 'op_Addition'.

At C:\SomeDirectory.ps1:4 char:46
+ gci -Path $Path -Recurse | % { $_.Directory + <<<<  "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") } | Out-File $Outfile
+ CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

注意:由于显而易见的原因,我在错误中用C:\ SomeDirectory替换了我的实际位置。

2 个答案:

答案 0 :(得分:2)

尝试将目录转换为字符串:

~/.bash_profile

答案 1 :(得分:1)

运行

$Path = "C:\Testpath"
gci -Path $Path | Get-Member -MemberType Properties | ft -AutoSize

您可以看到

有不同的属性集
  • TypeName:System.IO.DirectoryInfo
    • 没有.Directory属性:改为使用.PSParentPath.Remove(0,38).PSParentPath.Replace('Microsoft.PowerShell.Core\FileSystem::', '')(未找到更明智的替代);
    • 没有.Length属性:使用"-0"或其他任何内容;
  • TypeName:System.IO.FileInfo
    • 使用.DirectoryName属性(类型string)而不是.Directory一个(类型System.IO.DirectoryInfo)。

这是我的虚拟解决方案:

$Path = "C:\Testpath"
$OutFile = "C:\Testpath\Output.txt"

gci -Path $Path -Recurse | % { 
    if ($_.Attributes -match "Directory") {
        $_.PSParentPath.Remove(0,38) + "~" + $_.Name + "~" + "-0" + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") 
    } else {
        $_.DirectoryName + "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") 
    }
} | Out-File $Outfile