首页 > 解决方案 > 文件名到 CSV

问题描述

#get filenames from txtfile
foreach ($file in Get-Content -Path "C:\Filelist.txt") 
{
#Remove : and replace with Underscores
    $name = ( $file) -replace '\\', '_' -replace ':'
#Create new folder at destination location with new filename
    New-Item -Path "\\destinationpc\$name" -ItemType Directory -ErrorAction SilentlyContinue 
    
###Next step How would one create a csv with 2 columns, the original name and new name?
      
}

下一步我遇到了困难,如何创建一个包含 2 列、原始名称和新名称的 csv?

标签: powershellcsv

解决方案


Get-Content C:\Filelist.txt |
  ForEach-Object {
    $name = $_ -replace '\\', '_' -replace ':'
    # Create new folder at destination location with new filename
    New-Item -Path "\\destinationpc\$name" -ItemType Directory -ErrorAction SilentlyContinue 

    # Output an object with properties reflecting the original and the new name
    [pscustomobject] @{
      OriginalName = $_
      NewName = $name
    }

  } |
    Export-Csv out.csv -NoTypeInformation -Encoding utf8

注意:在 PowerShell [Core] v6+中,-NoTypeInformation-Encoding utf8都是隐含的;在Windows PowerShell中,默认字符编码是 ASCII(!),并且utf8总是创建一个带有 BOM的 UTF-8 文件。


推荐阅读