PowerShell从多个文件中提取所有者元数据 - 失败

时间:2017-11-01 17:02:45

标签: powershell loops

在另一个线程上有一些帮助我已经整理了一个脚本来从特定文件夹中提取文件名,并在较大的数据库中搜索原始文件并识别他们的所有者'。目前的脚本是:

$desktopPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
$images = $desktopPath + '\Get_Owner'
Get-ChildItem -Path $images | Select BaseName | Export-Csv $desktopPath`\Filenames.csv -NoTypeInformation
$serverPath = 'C:\Users\tuggleg\Desktop\Archive'
$files = Import-Csv -Path $desktopPath`\Filenames.csv

#import filenames and search server for filename and owner

ForEach ($fileName in $files.BaseName)
{
    Get-ChildItem -Path $serverPath -Filter "*$fileName*" -Recurse -ErrorAction 'SilentlyContinue' | 
           Select-Object -Property @{
            Name='Owner'
            Expression={(Get-Acl -Path $_.FullName).Owner}
          },'*' |
        Export-Csv -Path $desktopPath`\Owners.csv -NoTypeInformation
}

此脚本以用户移动本地文件($ images)的文件夹为目标,并提取文件名。然后,它会在较大的数据库($ serverPath)中搜索原始文件并拉出所有者。此脚本使用一个文件名,但它不会循环播放'当多个文件位于' $ images'中时,继续工作夹。我尝试了以下内容,脚本无限期运行,但不提供输出csv中的数据:

$desktopPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
$images = $desktopPath + '\Get_Owner'
Get-ChildItem -Path $images | Select BaseName | Export-Csv $desktopPath`\Filenames.csv -NoTypeInformation
$serverPath = 'C:\Users\tuggleg\Desktop\Archive'
$files = Import-Csv -Path $desktopPath`\Filenames.csv

#import filenames and search server for filename and owner
#loop script
While($true) {

ForEach ($fileName in $files.BaseName)
{
    Get-ChildItem -Path $serverPath -Filter "*$fileName*" -Recurse -ErrorAction 'SilentlyContinue' | 
           Select-Object -Property @{
            Name='Owner'
            Expression={(Get-Acl -Path $_.FullName).Owner}
          },'*' |
        Export-Csv -Path $desktopPath`\Owners.csv -NoTypeInformation
}
}

任何人都可以确定为什么循环函数会破坏脚本?或者更好的是为什么最初的' foreach'声明最初没有为每个文件提供所有者吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我可以告诉,虽然($ true)正在运行无限循环,但没有-NoClobber开关的Export-Csv会在循环的每次迭代时覆盖文件(==空白文件一旦用完了条目在$文件中)。

尝试添加-NoClobber(和/或-Append)开关&删除While($ true)循环 - 似乎是多余的,因为你已经获得了ForEach。

否则,您可以收集数据&最后将它写入csv,如:

ForEach ($fileName in $files.BaseName)
{
 $data +=  Get-ChildItem -Path $serverPath -Filter "*$fileName*" -Recurse -ErrorAction 'SilentlyContinue' | 
           Select-Object -Property @{
            Name='Owner'
            Expression={(Get-Acl -Path $_.FullName).Owner}
          },'*'
}

$data | Export-Csv -Path $desktopPath`\Owners.csv -NoTypeInformation