powershell list of unique parts of filename

2019-07-18 02:00发布

I have multiple machines uploading files to one FTP directory. The first part of the filename is the machine, the rest is a timestamp, e.g. AAAAA_20130312_125113.

Now I want to get a sorted list of all Unique machines that have uploaded to this directory. I managed to write the lost of all filenames.substring(0,5) to the host but I still don't have the unique machine names.

$files=Get-ChildItem $strMOVETO -Name -Include TAS*.csv -Recurse
ForEach ($i in $files) { Write-Host $i.Substring(0,5) }

Any hints on how to do this? Does not necessary have to be a one liner, although that would be a nice challenge ;-).

Thanks!

3条回答
男人必须洒脱
2楼-- · 2019-07-18 02:50

pipe the results of your command into a | sort -unique

$files=Get-ChildItem $strMOVETO -Name -Include TAS*.csv -Recurse
ForEach ($i in $files) { Write-Host $i.Substring(0,5) } | sort -unique

...but better still would be to simplify the script...

$filter = "TAS*.csv"
Get-ChildItem -Path $strMOVETO -Filter $filter -Recurse | % {$_.BaseName.Substring(0,5) } | sort -unique
查看更多
何必那么认真
3楼-- · 2019-07-18 02:58

What happens when you have an 8-character machine name? Your substring will break. Since the machine name, date & time are delimited by an _, split on that & get the first item.

Get-ChildItem $strMOVETO -recurse -name -include TAS*.csv|%{$_.split("_")[0]}|sort-object -unique

To filter on date as well:

Get-ChildItem $strMOVETO -recurse -include TAS*.csv|where-object{$_.lastwritetime -ge (get-date).adddays(-1)}|%{$_.basename.split("_")[1]}|sort-object -unique
查看更多
倾城 Initia
4楼-- · 2019-07-18 02:58

Not tested but something like this:

Get-ChildItem $strMOVETO -Name -Include TAS*.csv -Recurse | % { $_.Name.Substring(0,5) } | Sort -Unique

You don't need to do the Write-Host inside the loop and it's easier to use % instead of a foreach loop.

查看更多
登录 后发表回答