简体   繁体   English

powershell 基于 csv 文件创建 txt 文件

[英]powershell create txt files based on csv file

I have csv file with list of filepaths:我有带有文件路径列表的 csv 文件:

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

I would like to loop through that list and to create in the same directory txt file per every file with below information: Today's date Filepath Name of file我想遍历该列表,并在每个文件的同一目录中创建 txt 文件,其中包含以下信息:今天的日期 Filepath 文件名

so in example for 1st file it should be file C:\\Users\\postgres\\1.tmp.txt with data:所以在第一个文件的例子中,它应该是带有数据的文件C:\\Users\\postgres\\1.tmp.txt

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

I tried:我试过:

$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}

Just use Import-Csv on the input file and loop through the data with ForEach-Object .只需在输入文件上使用Import-Csv并使用ForEach-Object循环遍历数据。
Inside the loop, split the fullname into the path and the filename only:在循环内,将全名拆分为路径和文件名:

$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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM