所以我知道如何使用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。
最佳答案
跑
$Path = "C:\Testpath"
gci -Path $Path | Get-Member -MemberType Properties | ft -AutoSize
您会看到有不同的属性集
System.IO.DirectoryInfo
:.Directory
属性:改用.PSParentPath.Remove(0,38)
或.PSParentPath.Replace('Microsoft.PowerShell.Core\FileSystem::', '')
(找不到更聪明的替代方法); .Length
属性:使用"-0"
或其他任何方式; 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
关于powershell - PowerShell:使用Out-File将Dir列表的特定部分写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925112/