Search code examples
powershellfindstrselect-string

(powershell) Select-String vs Findstr


This is very simple... why first command working and second no?

Findstr looks to me for best use in "dos"like commands and not in powershell.

Get-AppXProvisionedPackage -online | findstr ^DisplayName

Get-AppXProvisionedPackage -online | Select-String -pattern "DisplayName"

powershell newbie :)


Solution

  • findstr is an operating system executable (findstr.exe actually), which you can see from within PowerShell:

    Get-Command findstr
    

    Output:

    CommandType     Name                                               Version    Source                                   
    -----------     ----                                               -------    ------                                   
    Application     findstr.exe                                        10.0.10... C:\WINDOWS\system32\findstr.exe
    

    Select-String is similar but more powerful and is a native PowerShell cmdlet

    CommandType     Name                                               Version    Source                                   
    -----------     ----                                               -------    ------                                   
    Cmdlet          Select-String                                      3.1.0.0    Microsoft.PowerShell.Utility
    

    They don't work exactly the same though or take the same input. Select-String is generally better for use in PowerShell, but check the help to see how it works.

    As Mathias pointed out, for what you're doing, you probably want Select-Object:

    Get-AppXProvisionPackage -online | Select-Object DisplayName
    

    This would return a new object with a single property DisplayName. To get the value of the property only you can use:

    Get-AppXProvisionPackage -online | Select-Object -ExpandProperty DisplayName
    

    (see also CapitanShinChan's answer)

    PowerShell cmdlets often return objects with various properties, and the stylized format you see is for display, but you can access properties programmatically without using string parsing. Select-Object is one way, another is to use dot . notation:

    $pkg = Get-AppXProvisionPackage -online
    $pkg.DisplayName