简体   繁体   中英

CSV file generates new name - call powershell

I want to call a CSV file from a Powershell script, which I know how to do. However the problem is, I need to do this with a new CSV file name everyday ( a new CSV is generated everyday). Is there anyway to do this without having to change the name of the file on the PS script everyday?

$csv = Import-Csv '$D\path to csv'

$headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name

  foreach ($header in $headers) {
  foreach ($data in $csv.$header) {

   }

 }

Thanks,

You can use Get-Childitem to get files/directories in a directory. You can combine it with -Filter to get only CSVs, Sort-Object to sort by LastWriteTime (most recent CSV at the top) and Select-Object so you only get the most recent file.

$myCsv = Get-ChildItem '$D\path to csv' -Filter *.csv |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1

$csv = Import-Csv $myCsv

$headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name

  foreach ($header in $headers) {
  foreach ($data in $csv.$header) {

   }

 }

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