powershell list of unique parts of filename

偶尔善良 提交于 2019-12-13 16:49:45

问题


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!


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/15360525/powershell-list-of-unique-parts-of-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!