为何Get-ChildItem返回的目录对象Directory属性为null,文件对象却正常?
为什么PowerShell中目录对象的Directory属性返回$null?
这是PowerShell对文件和目录对象的属性设计差异导致的:
属性定位不同
文件对象(FileInfo类型)的Directory属性用于指向它所在的父目录,因为文件本身依赖目录存在;而目录对象(DirectoryInfo类型)本身就是容器,PowerShell没有为它设计Directory属性,取而代之的是Parent属性来指向其父目录。你看到文件的Directory返回相对路径,本质是它指向的DirectoryInfo对象的路径表现形式。验证属性差异
你可以通过以下命令对比两者的属性列表:# 查看单个文件对象的属性 Get-ChildItem -Path $Path -File | Select-Object -First 1 | Get-Member -MemberType Property # 查看单个目录对象的属性 Get-ChildItem -Path $Path -Directory | Select-Object -First 1 | Get-Member -MemberType Property执行后会发现,文件属性里包含
Directory,而目录属性里只有Parent,没有Directory字段,所以直接访问时返回$null。获取目录父路径的正确方法
如果要获取目录的父目录路径,直接使用Parent属性即可:Get-ChildItem -Path $Path -Recurse -Directory | Select-Object FullName, Parent要是需要和文件
Directory属性返回的相对路径格式一致,可以做简单的字符串处理:Get-ChildItem -Path $Path -Recurse | ForEach-Object { $basePath = (Resolve-Path $Path).Path $parentPath = if ($_.PSIsContainer) { $_.Parent.FullName.Replace($basePath, '').TrimStart('\') } else { $_.Directory.FullName.Replace($basePath, '').TrimStart('\') } [PSCustomObject]@{ ItemName = $_.Name ItemType = if ($_.PSIsContainer) { 'Directory' } else { 'File' } ParentRelativePath = $parentPath } }
内容的提问来源于stack exchange,提问作者Silloky
相关产品推荐
相关产品推荐

