Tag Archives: CaseSensitive

Sort-Object

NAME
    Sort-Object

SYNOPSIS
    Sorts objects by property values.

SYNTAX
    Sort-Object [[-Property] <Object[]>] [-CaseSensitive] [-Culture <string>] [-Descending] [-InputObject <psobject>] [-Unique] [<CommonParameters>]

DESCRIPTION
    The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object.

    You can specify a single property or multiple properties (for a multi-key sort), and you can select a case-sensitive or case-insensitive sort. You can also direct Sort-Object to display only the objects with a unique value for a particular property.

PARAMETERS
    -CaseSensitive [<SwitchParameter>]
        Indicates that the sort should be case sensitive. By default, sorting is not case sensitive.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Culture <string>
        Specifies the cultural configuration to use when sorting.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Descending [<SwitchParameter>]
        Sorts the objects in descending order. The default is ascending order.

        The Descending parameter applies to all properties. To sort by some properties in
        ascending order and others in descending order, you must specify their property values by using a hash table. For details, see the examples.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies the objects to be sorted.

        When you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection. Because one object cannot be sorted, Sort-Object returns the entire collection unchanged.

        To sort objects, pipe them to Sort-Object.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -Property <Object[]>
        Specifies the properties to use when sorting. Objects are sorted based on the values of these properties. Enter the names of the properties. Wildcards are permitted.

        If you specify multiple properties, the objects are first sorted by the first property. If more than one object has the same value for the first property, those objects are sorted by the second property. This process continues until there are no more specified properties or no groups of objects.

        If you do not specify properties, the cmdlet sorts based on default properties for the object type.

        The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Expression <string> or <script block>
        — Ascending <Boolean>
        — Descending <Boolean>

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Unique [<SwitchParameter>]
        Eliminates duplicates and returns only the unique members of the collection. You can use this parameter instead of using the Get-Unique cmdlet.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.PSObject
        You can pipe the objects to be sorted to Sort-Object.

OUTPUTS
    System.Management.Automation.PSObject
        Sort-Object returns the sorted objects.

NOTES

        Sort-Object sorts objects based on the properties that you specify or the default sort properties for objects of that type.

        If an object does not have one of the specified properties, the property value for that object is interpreted by the cmdlet as NULL and is placed at the end of the sort order.

        When sorting objects, Sort-Object uses the Compare method for each property. If a property does not implement IComparable, the cmdlet converts the property value to a string and uses the Compare method for System.String.

        The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object.

        If you sort on a property whose value is an enumeration, Sort-Object sorts the enumeration values in numeric order; it does not sort the enumeration member names. For example, if you sort services by status, services with a status of “Stopped” appear before services with a status of “Running”, because the value of Status is a ServiceControllerStatus enumeration, in which “Stopped” has a value of 1 and “Running” has a value of 4.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Get-ChildItem | Sort-Object

    Mode                LastWriteTime     Length Name
    —-                ————-     —— —-
    -a—         9/13/2005 4:24 PM         0 0
    -a—         9/6/2005 4:19 PM         12 a.csv
    -a—         9/21/2005 3:49 PM        529 a.Ps
    -a—         8/22/2005 4:14 PM         22 a.pl
    -a—         9/27/2005 10:33 AM         24 a.txt
    -a—         9/15/2005 10:31 AM        398 a.vbs
    -a—         7/21/2005 12:39 PM     37066 a.xml
    -a—         8/28/2005 11:30 PM     5412 a.xslt
    -a—        10/25/2005 1:59 PM        125 AdamTravel.txt
    -a—         7/21/2005 9:49 AM         59 add2Num.Ps
    -a—         8/29/2005 5:42 PM     7111 Add-Content.xml
    -a—         9/21/2005 12:46 PM     8771 aliens.Ps
    -a—         8/10/2005 2:10 PM        798 array.xml
    -a—         8/4/2004 5:00 AM        110 AUTORUN.INF
    -a—         9/6/2005 4:20 PM        245 b.csv
    …

    Description
    ———–
    This command sorts the subdirectories and files in the current directory. Because no properties are specified, the files and directories are sorted in ascending alphabetical order by their default sort property, Name.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Get-ChildItem | Sort-Object -Property length

    Mode                LastWriteTime     Length Name
    —-                ————-     —— —-
    -a—         12/3/2006 5:35 PM         2 pref.txt
    -a—         9/6/2006 3:33 PM         15 count.txt
    -a—         7/26/2006 10:01 AM         30 filenoext
    -a—         8/18/2006 9:02 AM         52 temp.ps1
    -a—         8/18/2006 9:02 AM         52 temp.msh
    -a—         9/6/2006 3:33 PM         56 fivewords.txt
    -a—         7/26/2006 9:28 AM         80 date.csv
    -a—         7/29/2006 7:15 PM         84 test2.txt
    -a—         7/29/2006 7:15 PM         84 test.ps1

    Description
    ———–
    This command displays the files in the current directory in ascending order by file length.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Get-Process | Sort-Object -Property WS | Select-Object -last 5

    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ——- ——    —–     —– —– ——     — ———–
     1105     25    44236     18932 197    93.81 2032 iexplore
     2526     66    37668     36836 221 393.27    868 svchost
        974     19    22844     45928 371    88.39 3952 WINWORD
     1371     22    42192     61872 323    75.75 1584 INFOPATH
     2145     58    93088     70680 619 396.69 3908 OUTLOOK

    Description
    ———–
    This command displays the five processes on the computer with the greatest memory use based on the size of their working sets.

    The command uses the Get-Process cmdlet to get a list of processes. It uses a pipeline operator (|) to send the results to the Sort-Object cmdlet, which sorts the objects in working-set order.

    Another pipeline operator sends the results to the Select-Object, which displays only the last five items in the list.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Get-History | Sort-Object -Descending

    Id CommandLine
    — ———–
    51 Get-History | sort -Descending
    50 Get-History | sort -Descending
    49 Get-History | sort -Descending
    48 Get-History | sort -Descending
    47 Get-History | sort -Descending
    46 Get-History | sort -Descending
    45 Get-History | sort -Descending
    44 cd $pshome
    43 Get-ChildItem | Sort-Object
    42 gci *.txt

    Description
    ———–
    This command sorts HistoryInfo objects using the Id property as the default key.

    ————————– EXAMPLE 5 ————————–

    C:\PS>C:\PS> Get-Service | Sort-Object -Property `
    @{Expression=”Status”;Descending=$true}, `
    @{Expression=”DisplayName”;Descending=$false}

    Status Name             DisplayName
    —— —-             ———–
    Running ALG                Application Layer Gateway Service
    Running Ati HotKey Poller Ati HotKey Poller
    Running wuauserv         Automatic Updates
    Running BITS             Background Intelligent Transfer Ser…
    Running Client for NFS     Client for NFS
    …
    Stopped clr_optimizatio… .NET Runtime Optimization Service v…
    Stopped Alerter            Alerter
    Stopped AppMgmt            Application Management
    Stopped aspnet_state     ASP.NET State Service
    Stopped ATI Smart         ATI Smart
    Stopped ClipSrv            ClipBook

    Description
    ———–
    This command displays the services on the computer in descending Status order and ascending DisplayName order.

    The command uses the Get-Service cmdlet to get the services on the computer. It uses a pipeline operator (|) to send services to the Sort-Object cmdlet.

    To sort one property in ascending order and another property in descending order, the command uses a hash table for the value of the Property parameter. The hash table uses an Expression key to specify the property name and an Ascending or Descending key to specify the sort order.

    The resulting display, which sorts the Status values in descending order, lists properties with a Status value of “Running” before those with a Status value of “Stopped”. When sorted in ascending order, “Stopped” appears before “Running”, because Status is an enumerated property in which the value of “Stopped” (1) is less than the value of “Running” (4).

    ————————– EXAMPLE 6 ————————–

    C:\PS>Get-ChildItem *.txt | Sort-Object -Property @{Expression={$_.LastWriteTime – $_.CreationTime}; Ascending=$false} | Format-Table LastWriteTime, CreationTime

    LastWriteTime                         CreationTime
    ————-                         ————
    2/21/2006 10:22:20 AM                 10/3/2005 4:19:40 PM
    2/27/2006 8:14:24 AM                    2/23/2006 10:41:08 PM
    2/24/2006 1:26:19 PM                    2/23/2006 11:23:36 PM
    1/5/2006 12:01:35 PM                    1/5/2006 11:35:30 AM
    2/24/2006 9:25:40 AM                    2/24/2006 9:22:24 AM
    2/24/2006 9:40:01 AM                    2/24/2006 9:39:41 AM
    2/21/2006 10:21:30 AM                 2/21/2006 10:21:30 AM

    Description
    ———–
    This command sorts text files in descending order by the time span between CreationTime and LastWriteTime.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Get-Content servers.txt

    localhost
    test01
    server01
    server02
    localhost
    server01

    C:\PS> Get-Content servers.txt | Sort-Object -Unique
    localhost
    server01
    server02
    test01

    Description
    ———–
    These commands sort the names of servers in a text file. The second command uses the Sort-Object cmdlet with the Unique parameter to return a sorted list without duplicates.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113403
    Group-Object

Select-String

NAME
    Select-String

SYNOPSIS
    Finds text in strings and files.

SYNTAX
    Select-String [-Path] <string[]> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]

    Select-String -InputObject <psobject> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]

DESCRIPTION
    The Select-String cmdlet searches for text and text patterns in input strings and files. You can use it like Grep in UNIX and Findstr in Windows.

    Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

    However, you can direct it to detect multiple matches per line, display text before and after the match, or display only a Boolean value (true or false) that indicates whether a match is found.

    Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify.

    Select-String can display all of the text matches or stop after the first match in each input file. It can also display all text that does not match the specified pattern.

    You can also specify that Select-String should expect a particular character encoding, such as when you are searching files of Unicode text.

PARAMETERS
    -AllMatches [<SwitchParameter>]
        Searches for more than one match in each line of text. Without this parameter, Select-String finds only the first match in each line of text.

        When Select-String finds more than one match in a line of text, it still emits only one MatchInfo object for the line, but the Matches property of the object contains all of the matches.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CaseSensitive [<SwitchParameter>]
        Makes matches case-sensitive. By default, matches are not case-sensitive.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Context <Int32[]>
        Captures the specified number of lines before and after the line with the match. This allows you to view the match in context.

        If you enter one number as the value of this parameter, that number determines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match.

        In the default display, lines with a match are indicated by a right angle bracket (ASCII 62) in the first column of the display. Unmarked lines are the context.

        This parameter does not change the number of objects generated by Select-String. Select-String generates one MatchInfo (Microsoft.PowerShell.Commands.MatchInfo) object for each match. The context is stored as an array of strings in the Context property of the object.

        When you pipe the output of a Select-String command to another Select-String command, the receiving command searches only the text in the matched line (the value of the Line property of the MatchInfo object), not the text in the context lines. As a result, the Context parameter is not valid on the receiving Select-String command.

        When the context includes a match, the MatchInfo object for each match includes all of the context lines, but the overlapping lines appear only once in the display.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Encoding <string>
        Specifies the character encoding that Select-String should assume when searching the file. The default is UTF8.

        Valid values are “UTF7”, “UTF8”, “UTF32”, “ASCII”, “Unicode”, “BigEndianUnicode”, “Default”, and “OEM”. “Default” is the encoding of the system’s current ANSI code page. “OEM” is the current original equipment manufacturer code page identifier for the operating system.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Exclude <string[]>
        Exclude the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as “*.txt”. Wildcards are permitted.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Include <string[]>
        Include only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as “*.txt”. Wildcards are permitted.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies the text to be searched. Enter a Variable that contains the text, or type a command or expression that gets the text.

        Required?                    true
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -List [<SwitchParameter>]
        Returns only the first match in each input file. By default, Select-String returns a MatchInfo object for each match it finds.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -NotMatch [<SwitchParameter>]
        Finds text that does not match the specified pattern.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Path <string[]>
        Specifies the path to the files to be searched. Wildcards are permitted. The default location is the local directory.

        Specify files in the directory, such as “log1.txt”, “*.doc”, or “*.*”. If you specify only a directory, the command fails.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Pattern <string[]>
        Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

        To learn about regular expressions, see about_regular_expressions.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Quiet [<SwitchParameter>]
        Returns a Boolean value (true or false), instead of a MatchInfo object. The value is “true” if the pattern is found; otherwise, the value is “false”.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -SimpleMatch [<SwitchParameter>]
        Uses a simple match rather than a regular expression match. In a simple match, Select-String searches the input for the text in the Pattern parameter. It does not interpret the value of the Pattern parameter as a regular expression statement.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.PSObject
        You can pipe any object that has a ToString method to Select-String.

OUTPUTS
    Microsoft.PowerShell.Commands.MatchInfo or System.Boolean
        By default, the output is a set of MatchInfo objects, one for each match found. If you use the Quiet parameter, the output is a Boolean value indicating whether the pattern was found.

NOTES

        Select-String is like the Grep command in UNIX and the FindStr command in Windows.

        To use Select-String, type the text that you want to find as the value of the Pattern parameter.

        To specify the text to be searched, do the following:

        — Type the text in a quoted string, and then pipe it to Select-String.
        — Store a text string in a Variable, and then specify the Variable as the value of the InputObject parameter.
        — If the text is stored in files, use the Path parameter to specify the path to the files.

        By default, Select-String interprets the value of the Pattern parameter as a regular expression. (For more information, see about_regular_expressions.) However, you can use the SimpleMatch parameter to override the regular expression matching. The SimpleMatch parameter finds instances of the value of the Pattern parameter in the input.

        The default output of Select-String is a MatchInfo object, which includes detailed information about the matches. The information in the object is useful when you are searching for text in files, because MatchInfo objects have properties such as Filename and Line. When the input is not from the file, the value of these parameters is “InputStream”.

        If you do not need the information in the MatchInfo object, use the Quiet parameter, which returns a Boolean value (true or false) to indicate whether it found a match, instead of a MatchInfo object.

        When matching phrases, Select-String uses the current that is set for the system. To find the current culture, use the Get-Culture cmdlet.

        To find the properties of a MatchInfo object, type the following:

        Select-String -path test.txt -Pattern “test” | Get-Member | Format-List -property *

    ————————– EXAMPLE 1 ————————–

    C:\PS>”Hello”,”HELLO” | Select-String -Pattern “HELLO” -CaseSensitive

    Description
    ———–
    This command performs a case-sensitive match of the text that was piped to the Select-String command.

    As a result, Select-String finds only “HELLO”, because “Hello” does not match.

    Because each of the quoted strings is treated as a line, without the CaseSensitive parameter, Select-String would recognize both of the strings as matches.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Select-String -path *.xml -Pattern “the the”

    Description
    ———–
    This command searches through all files with the .xml file name extension in the current directory and displays the lines in those files that include the string “the the”.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Select-String -path $pshome\en-US\*.txt -Pattern “@”

    Description
    ———–
    This command searches the Windows PowerShell conceptual Help files (about_*.txt) for information about the use of the at sign (@).

    To indicate the path, this command uses the value of the $pshome automatic Variable, which stores the path to the Windows PowerShell installation directory. In this example, the command searches the en-US subdirectory, which contains the English (US) language Help files for Windows PowerShell.

    ————————– EXAMPLE 4 ————————–

    C:\PS>function search-help
    {
        $pshelp = “$pshome\es\about_*.txt”, “$pshome\en-US\*dll-help.xml”
        Select-String -path $pshelp -Pattern $args[0]
    }

    Description
    ———–
    This simple Function uses the Select-String cmdlet to search the Windows PowerShell Help files for a particular string. In this example, the Function searches the “en-US” subdirectory for English-United States language files.

    To use the Function to find a string, such as “psdrive”, type “search-help psdrive”.

    To use this Function in any Windows PowerShell console, change the path to point to the Windows PowerShell Help files on your system, and then paste the Function in your Windows PowerShell profile.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$events = Get-Eventlog -logname application -newest 100

    C:\PS> $events | Select-String -InputObject {$_.message} -Pattern “failed”

    Description
    ———–
    This example searches for the string “failed” in the 100 newest events in the Application log in Event Viewer.

    The first command uses the Get-EventLog cmdlet to get the 100 most recent events from the Application event log. Then it stores the events in the $events Variable.

    The second command uses a pipeline operator (|) to send the objects in the $events Variable to Select-String. It uses the InputObject parameter to represent the input from the $events Variable. The value of the InputObject parameter is the Message property of each object as it travels through the pipeline. The current object is represented by the $_ symbol.

    As each event arrives in the pipeline, Select-String searches the value of its Message property for the “failed” string, and then displays any lines that include a match.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Get-ChildItem c:\windows\system32\* -Include *.txt -recurse |
    Select-String -Pattern “Microsoft” -CaseSensitive

    Description
    ———–
    This command examines all files in the subdirectories of C:\Windows\System32 with the .txt file name extension and searches for the string “Microsoft”. The CaseSensitive parameter indicates that the “M” in “Microsoft” must be capitalized and that the rest of the characters must be lowercase for Select-String to find a match.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Select-String -path process.txt -Pattern idle, svchost -NotMatch

    Description
    ———–
    This command finds lines of text in the Process.txt file that do not include the words “idle” or “svchost”.

    ————————– EXAMPLE 8 ————————–

    C:\PS>$f = Select-String -path audit.log -Pattern “logon failed” -Context 2, 3

    C:\PS> $f.count

    C:\PS> ($f)[0].context | Format-List

    Description
    ———–
    The first command searches the Audit.Log file for the phrase “logon failed.” It uses the Context parameter to capture 2 lines before the match and 3 lines after the match.

    The second command uses the Count property of object arrays to display the number of matches found, in this case, 2.

    The third command displays the lines stored in the Context property of the first MatchInfo object. It uses array notation to indicate the first match (match 0 in a zero-based array), and it uses the Format-List cmdlet to display the value of the Context property as a list.

    The output consists of two MatchInfo objects, one for each match detected. The context lines are stored in the Context property of the MatchInfo object.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$a = Get-ChildItem $pshome\en-us\about*.help.txt | Select-String -Pattern transcript

    C:\PS> $b = Get-ChildItem $pshome\en-us\about*.help.txt | Select-String -Pattern transcript -AllMatches

    C:\PS> $a
    C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:39:     Start-Transcript and Stop-Transcript.

    C:\PS> $b
    C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:39:     Start-Transcript and Stop-Transcript.

    C:\PS>> $a.matches
    Groups : {Transcript}
    Success : True
    Captures : {Transcript}
    Index    : 13
    Length : 10
    Value    : Transcript

    C:\PS> $b.matches
    Groups : {Transcript}
    Success : True
    Captures : {Transcript}
    Index    : 13
    Length : 10
    Value    : Transcript

    Groups : {Transcript}
    Success : True
    Captures : {Transcript}
    Index    : 33
    Length : 10
    Value    : Transcript

    Description
    ———–
    This example demonstrates the effect of the AllMatches parameter of Select-String. AllMatches finds all pattern matches in a line, instead of just finding the first match in each line.

    The first command in the example searches the Windows PowerShell conceptual Help files (“about” Help) for instances of the word “transcript”. The second command is identical, except that it uses the AllMatches parameter.

    The output of the first command is saved in the $a Variable. The output of the second command is saved in the $b Variable.

    When you display the value of the Variables, the default display is identical, as shown in the example output.

    However, the fifth and sixth commands display the value of the Matches property of each object. The Matches property of the first command contains just one match (that is, one System.Text.RegularExpressions.Match object), whereas the Matches property of the second command contains objects for both of the matches in the line.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113388
    about_Comparison_Operators
    about_regular_expressions

Group-Object

NAME
    Group-Object

SYNOPSIS
    Groups objects that contain the same value for specified properties.

SYNTAX
    Group-Object [-AsHashTable] [-AsString] [[-Property] <Object[]>] [-CaseSensitive] [-Culture <string>] [-InputObject <psobject>] [-NoElement] [<CommonParameters>]

DESCRIPTION
    The Group-Object cmdlet displays objects in groups based on the value of a specified property. Group-Object returns a table with one row for each property value and a column that displays the number of items with that value.

    If you specify more than one property, Group-Object first groups them by the values of the first property, and then, within each property group, it groups by the value of the next property.

PARAMETERS
    -AsHashTable [<SwitchParameter>]
        Returns the group as a hash table. The keys of the hash table are the property values by which the objects are grouped. The values of the hash table are the objects that have that property value.

        By itself, the AsHashTable parameter returns each hash table in which each key is an instance of the grouped object. When used with the AsString parameter, the keys in the hash table are strings.

        Required?                    false
        Position?                    named
        Default value                GroupInfo object
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsString [<SwitchParameter>]
        Converts the hash table keys to strings. By default, the hash table keys are instances of the grouped object. This parameter is valid only when used with the AsHashTable parameter.

        Required?                    false
        Position?                    named
        Default value                GroupInfo objects
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CaseSensitive [<SwitchParameter>]
        Makes the grouping case-sensitive. Without this parameter, the property values of objects in a group might have different cases.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Culture <string>
        Specifies the culture to use when comparing strings.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies the objects to group. Enter a Variable that contains the objects, or type a command or expression that gets the objects.

        When you use the InputObject parameter to submit a collection of objects to Group-Object, Group-Object receives one object that represents the collection. As a result, it creates a single group with that object as its member.

        To group the objects in a collection, pipe the objects to Group-Object.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -NoElement [<SwitchParameter>]
        Omits the members of a group from the results.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Property <Object[]>
        Specifies the properties for grouping. The objects are arranged into groups based on the value of the specified property.

        The value of the Property parameter can be a new calculated property. To create a calculated, property, create a hash table with an Expression key that specifies a string or script block value.

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.PSObject
        You can pipe any object to Group-Object

OUTPUTS
    Microsoft.PowerShell.Commands.GroupInfo or System.Collections.Hashtable
        When you use the AsHashTable parameter, Group-Object returns a hash table. Otherwise, it returns a GroupInfo object.

NOTES

        You can also use the GroupBy parameter of the formatting cmdlets (such as Format-Table [m2] and Format-List [m2]) to group objects. Unlike Group-Object, which creates a single table with a row for each property value, the GroupBy parameters create a table for each property value with a row for each item that has the property value.

        Group-Object does not require that the objects being grouped be of the same Microsoft .NET Framework type. When grouping objects of different .NET Framework types, Group-Object uses the following rules:

        — Same Property Names and Types: If the objects have a property with the specified name, and the property values have the same .NET Framework type, the property values are grouped by using the same rules that would be used for objects of the same type.

        — Same Property Names, Different Types: If the objects have a property with the specified name, but the property values have a different .NET Framework type in different objects, Group-Object uses the .NET Framework type of the first occurrence of the property as the .NET Framework type for that property group. When an object has a property with a different type, the property value is converted to the type for that group. If the type conversion fails, the object is not included in the group.

        — Missing Properties: Objects that do not have a specified property are considered ungroupable. Ungroupable objects appear in the final GroupInfo object output in a group named AutomationNull.Value.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Get-ChildItem *.doc | Group-Object -Property length

    Description
    ———–
    This command gets the files in the current location that have a .doc extension and groups them by size.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Get-ChildItem | Sort-Object -Property extension | Group-Object -Property extension

    Description
    ———–
    This command gets the files in the current location, sorts them by file name extension, and then groups them by file name extension. Note that the files are sorted before they are grouped.

    ————————– EXAMPLE 3 ————————–

    C:\PS>1..35 | Group-Object -Property {$_ % 2},{$_ % 3}

    Description
    ———–
    This example shows how to use script blocks as the value of the Property parameter.

    This command displays the integers from 1 to 35, grouped by the remainder left when they are divided by 2 or 3.

    ————————– EXAMPLE 4 ————————–

    C:\PS>$events = Get-Eventlog -logname system -newest 1000

    C:\PS> $events | Group-Object -Property eventID

    Count Name                     Group
    —– —-                     —–
     44 Information             {System.Diagnostics.EventLogEntry,
        5 Error                     {System.Diagnostics.EventLogEntry,
        1 Warning                 {System.Diagnostics.EventLogEntry}

    Description
    ———–
    These commands display the 1,000 most recent entries in the System event log, grouped by Event ID.

    The first command uses the Get-EventLog cmdlet to retrieve the events and the assignment operator (=) to save them in the $events Variable.

    The second command uses a pipeline operator (|) to send the events in the $events Variable to the Group-Object cmdlet. The command uses the Property parameter to specify that the events should be grouped according to the value of their EventID property.

    In the output, the Count column represents the number of entries in each group, the Name column represents the EventID values that define a group, and the Group column represents the objects in each group.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Get-Process | Group-Object -Property priorityclass

    Count Name                Group
    —– —-                —–
     55 Normal             {System.Diagnostics.Process (AdtAgent), System.Diagnostics.Process (alg), System.Dia…
        1                     {System.Diagnostics.Process (Idle)}
        3 High                {System.Diagnostics.Process (Newproc), System.Diagnostics.Process (winlogon), System.D…
        2 BelowNormal         {System.Diagnostics.Process (winperf),

    C:\PS>Get-Process | Group-Object -Property company -NoElement
    Count Name
    —– —-
     55 Normal
        1
        3 High
        2 BelowNormal

    Description
    ———–
    This example demonstrates the effect of the NoElement parameter. These commands group the processes on the computer by priority class.

    The first command uses the Get-Process cmdlet to get the processes on the computer. It uses a pipeline operator (|) to send the results to Group-Object, which groups the objects by the value of the PriorityClass property of the process.

    The second command is identical to the first, except that it uses the NoElement parameter to eliminate the members of the group from the output. The result is a table with only the count and property value name.

    The results are shown in the following sample output.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Get-Eventlog -logname system -newest 1000 | Group-Object -Property {$_.TimeWritten – $_.TimeGenerated}

    Description
    ———–
    This command demonstrates how to provide the value of the Property parameter as a script block.

    This command displays the most recent 1,000 entries from the system event log, grouped according to the time between when they were generated and when they were written to the log.

    The command uses the Get-EventLog cmdlet to get the event log entries. It uses a pipeline operator (|) to send the entries to the Group-Object cmdlet. The value of the Property parameter is specified as a script block (an expression in braces). The result of evaluating the script block is the time between when the log entry was generated and when it was written to the log. That value is used to group the 1,000 most recent events.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Get-ChildItem | Group-Object extension -NoElement

    Count Name
    —– —-
     21
     82 .txt
        9 .cmd
        5 .log
     12 .xml
        5 .htm
     36 .ps1
        1 .psc1
        3 .exe
        6 .csv
        1 .psd1
        2 .bat

    Description
    ———–
    This command groups the items in the current directory by file name extension. It uses the NoElement parameter to omit the members of the group.

    The results are shown in the following sample output.

    ————————– EXAMPLE 8 ————————–

    C:\PS>”a”, “b”, “c”, “c”, “d” | Get-Unique

    a
    b
    c
    d

    C:\PS> “a”, “b”, “c”, “c”, “d” | Group-Object -NoElement | where {$_.Count -gt 1}
    Count Name
    —– —-
        2 c

    C:\PS> Get-Process | Group-Object -Property Name -NoElement | where {$_.count -gt 1}
    Count Name
    —– —-
        2 csrss
        5 svchost
        2 winlogon
        2 wmiprvse

    Description
    ———–
    This example shows how to find the unique and non-unique (repeated) property values in a collection.

    The first command gets the unique elements of an array by piping the array to the Get-Unique cmdlet.

    The second command gets the non-unique elements of an array. It pipes the array to the Group-Object cmdlet, which groups the objects by value. The resulting groups are piped to the Where-Object cmdlet, which selects objects with groups with more than one member.

    The third command shows a practical use for this technique. It uses the same method to find processes on the computer that have the same process name.

    The results are shown in the following sample output.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$a = Get-Command get-*, set-* -type cmdlet | Group-Object -Property verb -AsHashTable -AsString

    C:\PS> $a

    Name    Value
    —-    —–
    Get     {Get-PSCallStack, Get-PSBreakpoint, Get-PSDrive, Get-PSSession…}
    Set     {Set-Service, Set-StrictMode, Set-PSDebug, Set-PSSessionConfiguration…}

    C:\PS> $a.get

    CommandType     Name                 Definition
    ———–     —-                 ———-
    Cmdlet         Get-PSCallStack     Get-PSCallStack [-Verbose] [-Debug] [-ErrorAction <ActionPrefer…
    Cmdlet         Get-PSBreakpoint     Get-PSBreakpoint [[-Id] <Int32[]>] [-Verbose] [-Debug] [-ErrorA…
    Cmdlet         Get-PSDrive         Get-PSDrive [[-Name] <String[]>] [-Scope <String>] [-PSProvider…
    …

    Description
    ———–
    This example uses the AsHashTable and AsString parameters to return the groups in a hash table, that is, as a collection of key-value pairs.

    In the resulting hash table, each property value is a key, and the group elements are the values. Because each key is a property of the hash table object, you can use dot notation to display the values.

    The first command gets the Get and Set cmdlets in the session, groups them by verb, returns the groups as a hash table, and saves the hash table in the $a Variable.

    The second command displays the hash table in $a. There are two key-value pairs, one for the Get cmdlets and one for the Set cmdlets.

    The third command uses dot notation to display the values of the Get key in $a. The values are CmdletInfo object. The AsString parameter does not convert the objects in the groups to strings.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113338

Compare-Object

NAME
    Compare-Object

SYNOPSIS
    Compares two sets of objects.

SYNTAX
    Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObject[]> [-CaseSensitive] [-Culture <string>] [-ExcludeDifferent] [-IncludeEqual] [-PassThru] [-Property <Object[]>] [-SyncWindow <int>] [<CommonParameters>]

DESCRIPTION
    The Compare-Object cmdlet compares two sets of objects. One set of objects is the Reference set, and the other set is the Difference set.

    The result of the comparison indicates whether a property value appeared only in the object from the Reference set (indicated by the <= symbol), only in the object from the Difference set (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects (indicated by the == symbol).

PARAMETERS
    -CaseSensitive [<SwitchParameter>]
        Indicates that comparisons should be case-sensitive.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Culture <string>
        Specifies the culture to use for comparisons.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -DifferenceObject <PSObject[]>
        Specifies the objects that are compared to the reference objects.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -ExcludeDifferent [<SwitchParameter>]
        Displays only the characteristics of compared objects that are equal.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -IncludeEqual [<SwitchParameter>]
        Displays characteristics of compared objects that are equal. By default, only characteristics that differ between the reference and difference objects are displayed.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -PassThru [<SwitchParameter>]
        Passes the objects that differed to the pipeline. By default, this cmdlet does not generate any output.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Property <Object[]>
        Specifies the properties of the reference and difference objects to compare.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ReferenceObject <PSObject[]>
        Objects used as a reference for comparison.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -SyncWindow <int>
        Defines a search region in which an attempt is made to re-synchronize the order if there is no match. The default value is [Int32]::MaxValue.

        Required?                    false
        Position?                    named
        Default value                [Int32]::MaxValue
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.PSObject
        You can pipe a DifferenceObject object to Compare-Object.

OUTPUTS
    None, or the objects that are different
        When you use the PassThru parameter, Compare-Object returns the objects that differed. Otherwise, this cmdlet does not generate any output.

NOTES

    ————————– EXAMPLE 1 ————————–

    C:\PS>Compare-Object -ReferenceObject $(Get-Content C:\test\testfile1.txt) -DifferenceObject $(Get-Content C:\test\testfile2.txt)

    Description
    ———–
    This command compares the contents of two text files. It displays only the lines that appear in one file or in the other file, not lines that appear in both files.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Compare-Object -ReferenceObject $(Get-Content C:\Test\testfile1.txt) -DifferenceObject $(Get-Content C:\Test\testfile2.txt) -IncludeEqual

    Description
    ———–
    This command compares each line of content in two text files. It displays all lines of content from both files, indicating whether each line appears in only Textfile1.txt or Textfile2.txt or whether each line appears in both files.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$processes_before = Get-Process

    C:\PS> notepad

    C:\PS> $processes_after = Get-Process

    C:\PS> Compare-Object -ReferenceObject $processes_before -DifferenceObject $processes_after

    Description
    ———–
    These commands compare two sets of process objects.

    The first command uses the Get-Process cmdlet to get the processes on the computer. It stores them in the $processes_before Variable.

    The second command starts Notepad.

    The third command uses the Get-Process cmdlet again and stores the resulting processes in the $processes_after Variable.

    The fourth command uses the Compare-Object cmdlet to compare the two sets of process objects. It displaysthe differences between them, which include the new instance of Notepad.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113286
    Group-Object
    Measure-Object
    Sort-Object
    ForEach-Object
    New-Object
    Select-Object
    Tee-Object
    Where-Object