【问题标题】:Changing the entries and columns in an exported CSV file in Powershell在 Powershell 中更改导出的 CSV 文件中的条目和列
【发布时间】:2021-04-08 06:17:04
【问题描述】:

在 CSV 文件中导出 MD5 哈希时,它会创建三列:算法、哈希、路径。我想改变它并使它只创建两列:哈希和文件名。其中 Path 显示完整路径(例如 C:\Users\Admin\Desktop\ExampleFiles\SampleFile.txt)。但是,我希望它只显示文件名 (SampleFile.txt)。

如果更多文件夹中有文件,那么我希望它看起来像这样 (TestFolder1\File1.txt) 而不是 (C:\Users\Admin\Desktop\ExampleFiles\TestFolder1\File1.txt)。

我的代码是这样的:

#Getting the MD5 hash of the source and storing it a csv format
$InstallerPath = Get-ChildItem -Path 'C:\source\Folder1' -Recurse
$InstallerHash = foreach ($File in $InstallerPath) 
{
    Get-FileHash $File.FullName -Algorithm MD5 -ErrorAction SilentlyContinue
}
$InstallerHash | Export-Csv -Path C:\Users\Admin\Desktop\Exports\SourceHash.csv

#Getting the MD5 hash of the destination and storing it in a csv format
$DestinationPath = Get-ChildItem -Path "C:\destination\Folder1" -Recurse
$DestinationHash = foreach ($File in $DestinationPath) 
{
    Get-FileHash $File.FullName -Algorithm MD5 -ErrorAction SilentlyContinue 
}
$DestinationHash | Export-Csv -Path C:\Users\Admin\Desktop\Exports\DestinationHash.csv

我希望 CSV 表如下所示:

| Hash | FileName |
| ---- | -------- |
| 12345abcde | SampleFile.txt|
| abcde12345 | TestFolder1\File1.txt |

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试试这个

    #Get All files and group by name
    $AllFilesGrouped=Get-ChildItem "c:\temp" -file -Recurse | group Name
    
    #take all group, get Nb doublons and loop on file
    $AllFilesGrouped |%{
    
    $NbFile=$_.Count
    
    $_.Group | %{
    
                    #If doublon => Filename + Directory
                    if ($NbFile -gt 1)
                    {
                       $FileName="{0}\{1}" -f $_.Directory.Name , $_.Name
                    }
                    else
                    {
                       $FileName=$_.Name 
                    }
    
                    #Build final object
                    [pscustomobject]@{
    
                    Hash=(Get-FileHash $_.FullName -Algorithm MD5 -ErrorAction SilentlyContinue).Hash
                    FileName=$FileName
                    }
    
    
                }
    
    
    } | export-csv "c:\temp\result.csv" -notype
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多