PowerShell - 搜索现有文件会生成空输出

时间:2016-06-08 23:22:41

标签: powershell

我希望搜索searchFiles中列出的特定文件,并将其位置传递给TestFileLocation.CSV。但是,我当前的脚本只生成一个空CSV。我错过了什么?

My TestFindFile.csv的格式为:

Name
123.pdf
321.pdf
aaa.pdf

$searchFiles = Import-CSV 'C:\Data\SCRIPTS\PS1\TestFindFile.csv' -Header ("Name")
$source = 'C:\Data'

ForEach($File in $searchFiles) 
{
    Get-ChildItem $source -Filter $File -rec | where {!$_.PSIsContainer} | select-object FullName | export-csv -notypeinformation -delimiter '|' -path c:\data\scripts\ps1\TestFileLocation.csv
}

2 个答案:

答案 0 :(得分:1)

您在循环的每次迭代中都覆盖了CSV。

$searchFiles = Import-CSV 'C:\Data\SCRIPTS\PS1\TestFindFile.csv' -Header ("Name")
$source = 'C:\Data'
$outputPath = 'c:\data\scripts\ps1\TestFileLocation.csv'

$searchFiles |  ForEach-Object {
    # Silently continue to try to ignore error like
    # not being able to read path's which are too long
    Get-ChildItem $source -Filter $_ -rec -ErrorAction SilentlyContinue | where {!$_.PSIsContainer} | select-object FullName 
} | export-csv -notypeinformation -delimiter '|' -path $outputPath

使用AlphaFS的示例

评论要求使用AlphaFS的一个例子,因为它声称克服了长路径问题。我没有详细介绍所有细节,但这就是我如何使用它。

# download and unzip to c:\alpahfs
# dir C:\AlphaFS\* -Recurse -File | Unblock-File 
[System.Reflection.Assembly]::LoadFrom('C:\AlphaFS\lib\net451\AlphaFS.dll')
$searchFiles = Import-CSV 'C:\Data\SCRIPTS\PS1\TestFindFile.csv' -Header ("Name")
$source = 'C:\Data'
$outputPath = 'c:\data\scripts\ps1\TestFileLocation.csv'

    $searchFiles |  ForEach-Object {
        $files = [Alphaleonis.Win32.Filesystem.Directory]::EnumerateFiles($source,'*',[System.IO.SearchOption]::AllDirectories) 
        $files | ForEach-Object { [PSCustomObject] @{FileName = $_} }
    } | export-csv -notypeinformation -delimiter '|' -path $outputPath
# type $outputPath

答案 1 :(得分:1)

如果您的.csv文件包含标题"名称",则在运行 Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : namespace ‘htmltools’ 0.2.6 is being loaded, but >= 0.3 is required In addition: Warning messages: 1: replacing previous import by ‘grid::arrow’ when loading ‘ggthemes’ 2: replacing previous import by ‘grid::unit’ when loading ‘ggthemes’ 3: replacing previous import by ‘scales::alpha’ when loading ‘ggthemes’ Error: package or namespace load failed for ‘CosmoPhotoz’ 时无需再次声明它。

输出为空的原因是您正在搜索包含属性Name的对象(从TestFindFile.csv导入)。搜索Import-Csv。同时在循环之外拉出不需要的命令:

$File.Name