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!
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
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.
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