将文件路径追加到包含文件名的csv文件

时间:2019-03-11 10:22:56

标签: powershell csv append filepath

我想将文件的完整路径添加到包含文件名的CSV中。

因此在CSV中,我目前拥有:

file1.txt file2.txt

导出csv应该如下:

file1.txt; c:/temp/file1.txt file1.txt; c:/temp/file1.txt

我尝试了以下操作:

$csv = Import-Csv <location csv>


    $allItems = Get-ChildItem -Recurse <location folders/files>
    $fullname = @()

    foreach ($item in $csv)
    {
      $fullname += $a | Where-Object {$_.Name -eq $file} | Select-Object -ExpandProperty Fullname
    }

1 个答案:

答案 0 :(得分:0)

如果您的CSV输入文件如下所示:

"FileName"
"file1.txt"
"file2 with spaces.txt"
"some other file.blah"

然后,您可以使用$files = (Import-Csv <location csv>).FileName来获取您要查找的文件名的字符串数组。

如果(根据您的评论判断)输入文件是单个字符串,且文件名用分号;分隔,则可以这样做:

$files = (Get-Content <location csv> -Raw) -split ';'

使用该文件名数组,您可以执行以下操作:

$result = @{}
Get-ChildItem -Path $searchPath -Recurse -File | ForEach-Object {
    if ($files -contains $_.Name) {
        if ($result.ContainsKey($_.Name)) {
            $result[$_.Name] += (';{0}' -f $_.FullName)
        }
        else {
            $result.Add($_.Name, $_.FullName)
        }
    }
}
# convert the hashtable to an array of PSCustomObjects and export to csv
$result.Keys | 
    ForEach-Object { [PSCustomObject]@{ FileName = $_ ; FullName = $result.$_ }} | 
    Export-Csv -Path $output -NoTypeInformation -Force

假设您的搜索路径包括以下内容:

D:\TEST
|   file1.txt
|   file2 with spaces.txt
|   some other file you are not interested in.txt
|
\---subfolder
        file2 with spaces.txt

然后从上面的代码输出的CSV文件将是:

"FileName","FullName"
"file2 with spaces.txt","D:\Test\file2 with spaces.txt;D:\Test\subfolder\file2 with spaces.txt"
"file1.txt","D:\Test\file1.txt"

希望有帮助