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

标签 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。

最佳答案


$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/

    相关文章:

    powershell - 有没有办法在 PowerShell 中使文本居中

    arrays - Powershell - LIKE 针对数组

    powershell - 大括号、逗号、参数方法调用

    string - 比较一个 if 语句 Powershell 中的对象

    powershell - 如何从 Get-ADUser 获取所有字段?

    Powershell:如何安装 cmdlet?

    powershell - 从 powershell 中可执行文件的输出中删除颜色代码

    powershell - 从 PowerShell 脚本将工作流事件添加到工具箱时遇到问题

    Powershell Web请求无法正确下载文件

    arrays - 将 JSON 数组索引列值转置为行并导出为 CSV