首页 > 解决方案 > powershell根据csv文件创建txt文件

问题描述

我有带有文件路径列表的 csv 文件:

Filename 
C:\Users\postgres\1.tmp 
C:\Users\postgres222\2.txt
C:\Users\postgres3333\3.jpeg

我想遍历该列表并在同一目录中为每个文件创建包含以下信息的 txt 文件:今天的日期文件路径文件名

所以在第一个文件的例子中,它应该是C:\Users\postgres\1.tmp.txt 带有数据的文件:

03\11\2021
C:\Users\postgres\1.tmp 
1.tmp

我试过了:

$Time=Get-date
$data = "\mydir"
foreach($file in Get-ChildItem $data){New-Item -ItemType file -Path $Get-Item $file.Fullpath + ".txt" -Value $Time Add-Content $Get-Item $file.Fullpath}

标签: powershellloopsforeach

解决方案


只需Import-Csv在输入文件上使用并使用ForEach-Object.
在循环内,将全名拆分为路径和文件名:

$today = '{0:dd\\MM\\yyyy}' -f (Get-Date)
(Import-Csv -Path 'X:\Path\Folder\Input.csv').Filename | ForEach-Object {
    $path = [System.IO.Path]::GetDirectoryName($_)   # or use: Split-Path $_ -Parent
    $file = [System.IO.Path]::GetFileName($_)        # or use: Split-Path $_ -Leaf
    # create the full path and filename for the output
    $out  = Join-Path -Path $path -ChildPath ('{0}.txt' -f $file)
    # construct the three lines and write the file
    "$today`r`n$_`r`n$file" | Set-Content -Path $out
}

推荐阅读