我有一个PowerShell脚本来扫描整个共享驱动器以创建记录保留清单。然而,当我运行代码时,我得到了几行有文件名但没有目录名的地方。
起初我以为这些文件在我正在扫描的主根驱动器上,但它们不是。PowerShell返回文件名、文件大小和相关日期,但不返回目录名,有什么原因吗?
我已经尝试根据文件名手动搜索,但无法找到它们。
我使用变量将源和目标信息路径到脚本中,但这应该是有意义的。
$properties = @(
@{ Name = 'File Size (MB)'
Expression = {[math]::Round(($_.Length / 1MB),2)}
}
'DirectoryName'
'Name'
'CreationTime'
'LastWriteTime'
@{ Name = 'Age'
Expression = {[math]::Round(([datetime]::Now - $_.LastWriteTime).TotalDays /365,2)}
}
)
$target_files = Get-ChildItem $sourcepath* -recurse -include "*" | Select-Object $properties |
Export-Csv $destinationpath${destinationfilename}.csv -NoTypeInformation
提前谢谢你,
女士继续我的评论
FileInfo
对象与DirectoryInfo
对象具有不同的属性。最值得注意的是您的问题是DirectoryName
属性,它存在于FileInfo上,但不存在于DirectoryInfo对象上。
例如,DirectoryInfo返回这些属性对象:
PSPath : Microsoft.PowerShell.CoreFileSystem::D:Test
PSParentPath : Microsoft.PowerShell.CoreFileSystem::D:
PSChildName : Test
PSDrive : D
PSProvider : Microsoft.PowerShell.CoreFileSystem
PSIsContainer : True
Mode : d-----
BaseName : Test
Target : {}
LinkType :
Name : Test
FullName : D:Test
Parent :
Exists : True
Root : D:
Extension :
CreationTime : 4-5-2020 15:33:48
CreationTimeUtc : 4-5-2020 13:33:48
LastAccessTime : 21-9-2021 15:59:43
LastAccessTimeUtc : 21-9-2021 13:59:43
LastWriteTime : 19-9-2021 21:41:48
LastWriteTimeUtc : 19-9-2021 19:41:48
Attributes : Directory
这里是FileInfo的属性对象:
PSPath : Microsoft.PowerShell.CoreFileSystem::D:TestBlah.txt
PSParentPath : Microsoft.PowerShell.CoreFileSystem::D:Test
PSChildName : Blah.txt
PSDrive : D
PSProvider : Microsoft.PowerShell.CoreFileSystem
PSIsContainer : False
Mode : -a----
VersionInfo : File: D:TestBlah.txt
InternalName:
OriginalFilename:
FileVersion:
FileDescription:
Product:
ProductVersion:
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language:
BaseName : Blah
Target : {}
LinkType :
Name : Blah.txt
Length : 0
DirectoryName : D:Test
Directory : D:Test
IsReadOnly : False
Exists : True
FullName : D:TestBlah.txt
Extension : .txt
CreationTime : 21-9-2021 16:04:49
CreationTimeUtc : 21-9-2021 14:04:49
LastAccessTime : 21-9-2021 16:04:49
LastAccessTimeUtc : 21-9-2021 14:04:49
LastWriteTime : 21-9-2021 16:04:49
LastWriteTimeUtc : 21-9-2021 14:04:49
Attributes : Archive
您的代码的主要问题是您不使用Get-ChildItem
上的-File
开关,因此,cmdlet返回两个文件和的对象目录。
在您的$properties
数组中,将'DirectoryName'替换为'FullName',从$sourcepath*
中删除星号,并留下-include "*"
:
$properties = @{Name = 'File Size (MB)'; Expression = {[math]::Round(($_.Length / 1MB),2)}},
'FullName','Name','CreationTime','LastWriteTime',
@{Name = 'Age'; Expression = {[math]::Round(([datetime]::Now - $_.LastWriteTime).TotalDays / 365,2)}}
# use Join-Path to safely construct the path and filename for the output
$outputPath = Join-Path -Path $destinationpath -ChildPath ('{0}.csv' -f $destinationfilename)
Get-ChildItem $sourcepath -File -Recurse | Select-Object $properties |
Export-Csv -Path $outputPath -NoTypeInformation