Removing Duplicate Values

When you have a list and only want the unique values you should do the following:

$strings="purple", "blue", "white", "black", "green","purple", "red", "yellow", "green"
$strings | Sort-Object | Get-Unique

Let's say you want to read a text and want to know how many unique words are in it:
$filename = "c:\filenametextfile.txt"
$(foreach ($line in Get-Content $filename) {$line.tolower().split(" ")}) | Sort-Object | Get-Unique

Or you want to know how many time the word "the" is in the text:
$(foreach ($line in Get-Content $filename) {$line.tolower().split(" ")}) | Sort-Object | Group-Object

And you can go on with piping the results into another command:
$(foreach ($line in Get-Content $filename) {$line.tolower().split(" ")}) | Sort-Object | Get-Unique | Group-Object|Sort-Object Name -descending

To count how many words , lines, characters are in a file:
Get-Content C:\filename.txt| Measure-Object -character -line -word

Let's change a text file and compare the result in Dir:
PS X:\> $before = Dir
PS X:\> "Hello world" >> test.txt
PS X:\> $after = Dir
PS X:\> Compare-Object $before $after -property Length, Name

                                 Length Name                                    SideIndicator

                                     80 test.txt                                =>
                                     54 test.txt                                <=

When you want is in clear text do as follows (you'll need to focus on the side indicator):
Compare-Object $before $after -property LastWriteTime, Name | Where-Object { $_.SideIndicator -eq "=>" } | ForEach-Object { "The file {0} has last been written at {1}" -f $_.Name, $_.LastWriteTime}

On Me

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License