简体   繁体   中英

How to get file names in a csv file but truncate part of the name in powershell?

I started with a powershell script that extracts filenames from a folder on a specific date and extract them to a new csv file. All I want is to trim the characters after the 5th character in each line. I started with this:

Get-ChildItem U:\data\*.* |Where{$_.LastWriteTime -gt (Get-
Date).AddDays(-1)} | Foreach-Object {$_.BaseName} > U:\result.csv 

My result was:

  • MMPM_SuperUser_24042017
  • MERHS_SuperUser_24042017
  • BRUSD_SuperUser_24042017
  • HDUJD_SuperUser_24042017
  • BDFOR_SuperUser_24042017

I want to trim the characters from _ and after for each line. I want the result to be:

  • MMPM
  • MERHS
  • BRUSD
  • HDUJD
  • BDFOR

Assign that in a variable and use split method to split with underscore. Once split is done, you will have the values stored in array. So, index of zero will give your result.

This should do your work:

$values= Get-ChildItem U:\data\*.* |Where{$_.LastWriteTime -gt (Get-date).AddDays(-1)} 
Foreach ($value in $values)
 {
 $value.BaseName.Split('_')[0] >> U:\result.csv
 }

just do it

Get-ChildItem "U:\data\" -file |Where {$_.LastWriteTime -gt (Get-Date).AddDays(-1) -and $_.BaseName -like '*_*' } | 
Foreach-Object {$_.BaseName.Split('_')[0]} > U:\result.csv 

#short version
gci "U:\data\" -file |? {$_.LastWriteTime -gt (Get-Date).AddDays(-1) -and $_.BaseName -like '*_*' } | 
% {$_.BaseName.Split('_')[0]} > U:\result.csv

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