简体   繁体   中英

powershell create txt files based on csv file

I have csv file with list of filepaths:

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

so in example for 1st file it should be file C:\\Users\\postgres\\1.tmp.txt with data:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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