Linux "uniq -d" command equivalent for PowerShell?
This should do what you need,
$var = Get-ChildItem | Group-Object -Property BaseName | Where-Object { $_.Count -gt 1} | Select-Object -ExpandProperty Name
I tried following command, but doesn't work:
$var = (Write-Host (Get-ChildItem $i).BaseName | Sort-Object -Unique).Count
# I want variable var's value is 1, because only one group that has same file names
The other answer by jfrmilner stores the BaseName
in var
not the count as you have requested in the question.
The following command stores the count (number of distinct sets of files sharing a command BaseName) in var
, which may be a more useful general command:
$var = (Get-ChildItem $i).BaseName | Group-Object | ?{ $_.Count -gt 1 } | Measure-Object | Select-Object -ExpandProperty Count
Example 1 - One set of files sharing a common basename (test)
> Get-ChildItem
Directory: F:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/02/2020 12:18 1272 test.txt
-a---- 16/02/2020 17:51 72 test.cmd
-a---- 19/11/2019 21:50 19 output.txt
-a---- 08/12/2019 18:47 119 GetBits.cmd
-a---- 31/12/2019 14:31 26876158 SystemEvents.xml
-a---- 08/01/2020 21:30 845 notepad++ regexp answer template.txt
-a---- 12/02/2020 11:00 17755 usb.csv
-a---- 01/03/2020 10:05 264 index.jpg
-a---- 01/03/2020 10:09 264 New.txt
> (Get-ChildItem $i).BaseName | Group-Object | ?{ $_.Count -gt 1 } | Measure-Object | Select-Object -ExpandProperty Count
1
>
Example 2 - Two sets of files sharing a common basename (test and New)
> Get-ChildItem
Directory: F:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/02/2020 12:18 1272 test.txt
-a---- 16/02/2020 17:51 72 test.cmd
-a---- 19/11/2019 21:50 19 output.txt
-a---- 08/12/2019 18:47 119 GetBits.cmd
-a---- 31/12/2019 14:31 26876158 SystemEvents.xml
-a---- 08/01/2020 21:30 845 notepad++ regexp answer template.txt
-a---- 12/02/2020 11:00 17755 usb.csv
-a---- 01/03/2020 10:05 264 index.jpg
-a---- 01/03/2020 10:09 264 New.txt
-a---- 08/03/2020 15:35 0 1
-a---- 08/03/2020 15:52 0 New.xxx
> (Get-ChildItem $i).BaseName | Group-Object | ?{ $_.Count -gt 1 } | Measure-Object | Select-Object -ExpandProperty Count
2
>