简体   繁体   English

如何在csv文件中获取文件名,但在Powershell中截断部分名称?

[英]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. 我从Powershell脚本开始,该脚本在特定日期从文件夹中提取文件名,然后将其提取到新的csv文件中。 All I want is to trim the characters after the 5th character in each line. 我想要的是在每行第5个字符之后修剪字符。 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 MMPM_SuperUser_24042017
  • MERHS_SuperUser_24042017 MERHS_SuperUser_24042017
  • BRUSD_SuperUser_24042017 BRUSD_SuperUser_24042017
  • HDUJD_SuperUser_24042017 HDUJD_SuperUser_24042017
  • BDFOR_SuperUser_24042017 BDFOR_SuperUser_24042017

I want to trim the characters from _ and after for each line. 我想从_和每行之后修剪字符。 I want the result to be: 我希望结果是:

  • MMPM MMPM
  • MERHS MERHS
  • BRUSD BRUSD
  • HDUJD HDUJD
  • BDFOR BDFOR

Assign that in a variable and use split method to split with underscore. 将其分配给变量,然后使用split方法使用下划线进行拆分。 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

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

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