Powershell Notes

Powershell Notes

PS C:\Users\aleescob> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.22621.2506
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22621.2506
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
PS C:\Users\aleescob> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      22621  2506

Filter Based on the Verb and Noun

PS C:\Users\aleescob> get-command -Verb delete

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Delete-DeliveryOptimizationCache                   1.0.3.0    DeliveryOptimization


PS C:\Users\aleescob> get-command -Verb update

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Update-AutologgerConfig                            1.0.0.0    EventTracingManagement
Function        Update-Disk                                        2.0.0.0    Storage
Function        Update-DscConfiguration                            1.1        PSDesiredStateConfiguration
Function        Update-EtwTraceSession                             1.0.0.0    EventTracingManagement


PS C:\Users\aleescob> get-command -Verb write

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Write-FileSystemCache                              2.0.0.0    Storage
Alias           Write-FileSystemCache                              1.0.0.0    VMDirectStorage
Function        Write-DtcTransactionsTraceSession                  1.0.0.0    MsDtc
Function        Write-PrinterNfcTag                                1.1        PrintManagement

PS C:\Users\aleescob> get-command -Verb Write -Noun debug

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Write-Debug                                        3.1.0.0    Microsoft.PowerShell.Utility

Use “Get-Help”

PS C:\Users\aleescob>
PS C:\Users\aleescob> get-command -noun *request*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Invoke-WebRequest                                  3.1.0.0    Microsoft.PowerShell.Utility



PS C:\Users\aleescob>
PS C:\Users\aleescob> get-help Invoke-WebRequest

NAME
    Invoke-WebRequest

SYNTAX
    Invoke-WebRequest [-Uri] <uri> [-UseBasicParsing] [-WebSession <WebRequestSession>] [-SessionVariable <string>] [-Credential <pscredential>]
    [-UseDefaultCredentials] [-CertificateThumbprint <string>] [-Certificate <X509Certificate>] [-UserAgent <string>] [-DisableKeepAlive] [-TimeoutSec <int>]
    [-Headers <IDictionary>] [-MaximumRedirection <int>] [-Method {Default | Get | Head | Post | Put | Delete | Trace | Options | Merge | Patch}] [-Proxy <uri>]
    [-ProxyCredential <pscredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-ContentType <string>] [-TransferEncoding {chunked | compress | deflate |
    gzip | identity}] [-InFile <string>] [-OutFile <string>] [-PassThru]  [<CommonParameters>]


ALIASES
    iwr
    wget
    curl


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Invoke-WebRequest -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=217035.

Get-Help with Example

PS C:\Users\aleescob> Get-help Invoke-WebRequest -Examples

NAME
    Invoke-WebRequest

SYNOPSIS
    Gets content from a web page on the internet.


    ---------------- Example 1: Send a web request ----------------

    $Response = Invoke-WebRequest -UseBasicParsing -URI https://www.bing.com?q=how+many+feet+in+a+mile
    $Response.InputFields |
        Where-Object name -like "* Value" |
        Select-Object name, value

    name       value
    ----       -----
    From Value 1
    To Value   5280

    The data returned by `Invoke-WebRequest` is stored in the `$Response` variable. The InputFields property of the response contains the form fields.
    `Where-Object` is used to filter the form fields to those where the name property is like "* Value". The filtered results are piped to `Select-Object` to
    select the name and value properties.
    ------------ Example 2: Use a stateful web service ------------

    $R = Invoke-WebRequest https://www.facebook.com/login.php -SessionVariable fb
    # This command stores the first form in the Forms property of the $R variable in the $Form variable.
    $Form = $R.Forms[0]
    # This command shows the fields available in the Form.
    $Form.fields

    Key                     Value
    ---                     -----
    ...
    email
    pass
    ...

    # These commands populate the username and password of the respective Form fields.
    $Form.Fields["email"]="User01@Fabrikam.com"
    $Form.Fields["pass"]="P@ssw0rd"
    # This command creates the Uri that will be used to log in to facebook.
    # The value of the Uri parameter is the value of the Action property of the form.
    $Uri = "https://www.facebook.com" + $Form.Action
    # Now the Invoke-WebRequest cmdlet is used to sign into the Facebook web service.
    # The WebRequestSession object in the $FB variable is passed as the value of the WebSession parameter.
    # The value of the Body parameter is the hash table in the Fields property of the form.
    # The value of the *Method* parameter is POST. The command saves the output in the $R variable.
    $R = Invoke-WebRequest -Uri $Uri -WebSession $FB -Method POST -Body $Form.Fields
    $R.StatusDescription

    The first command uses the `Invoke-WebRequest` cmdlet to send a sign-in request. The command specifies a value of "FB" for the value of the SessionVariable
    parameter, and saves the result in the `$R` variable. When the command completes, the `$R` variable contains an HtmlWebResponseObject and the `$FB` variable
    contains a WebRequestSession object.

    After the `Invoke-WebRequest` cmdlet signs in to facebook, the StatusDescription property of the web response object in the `$R` variable indicates that the
    user is signed in successfully.
    ------------- Example 3: Get links from a web page -------------

    (Invoke-WebRequest -Uri "https://devblogs.microsoft.com/powershell/").Links.Href

    The `Invoke-WebRequest` cmdlet gets the web page content. Then the Links property of the returned HtmlWebResponseObject is used to display the Href property
    of each link.
    - Example 4: Catch non success messages from Invoke-WebRequest -

    try
    {
        $Response = Invoke-WebRequest -Uri "www.microsoft.com/unkownhost"
        # This will only execute if the Invoke-WebRequest is successful.
        $StatusCode = $Response.StatusCode
    }
    catch
    {
        $StatusCode = $_.Exception.Response.StatusCode.value__
    }
    $StatusCode

    404

    The terminating error is caught by the `catch` block, which retrieves the StatusCode from the Exception object.
    ----- Example 8: Download multiple files at the same time -----

    $baseUri = 'https://github.com/PowerShell/PowerShell/releases/download'
    $files = @(
        @{
            Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.msi"
            OutFile = 'PowerShell-7.3.0-preview.5-win-x64.msi'
        },
        @{
            Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.zip"
            OutFile = 'PowerShell-7.3.0-preview.5-win-x64.zip'
        },
        @{
            Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.msi"
            OutFile = 'PowerShell-7.2.5-win-x64.msi'
        },
        @{
            Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.zip"
            OutFile = 'PowerShell-7.2.5-win-x64.zip'
        }
    )

    $jobs = @()

    foreach ($file in $files) {
        $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock {
            $params = $using:file
            Invoke-WebRequest @params
        }
    }

    Write-Host "Downloads started..."
    Wait-Job -Job $jobs

    foreach ($job in $jobs) {
        Receive-Job -Job $job
    }

    > [!NOTE] > To use the `Start-ThreadJob` cmdlet you must install the ThreadJob module from the PowerShell > Gallery.

Help instead of Get-Help

PS C:\Users\aleescob> help Invoke-WebRequest -examples

NAME
    Invoke-WebRequest

SYNOPSIS
    Gets content from a web page on the internet.


    ---------------- Example 1: Send a web request ----------------

    $Response = Invoke-WebRequest -UseBasicParsing -URI https://www.bing.com?q=how+many+feet+in+a+mile
    $Response.InputFields |
        Where-Object name -like "* Value" |
        Select-Object name, value

    name       value
    ----       -----
    From Value 1
    To Value   5280

    The data returned by `Invoke-WebRequest` is stored in the `$Response` variable. The InputFields property of the response contains the form fields.
    `Where-Object` is used to filter the form fields to those where the name property is like "* Value". The filtered results are piped to `Select-Object` to
    select the name and value properties.

NOTE: Here it looks the same but the difference is that it provides pagination.

Use Get-Member

PS C:\Users\aleescob> get-process -Name powershell

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
   1696      74   240016     283184      18.78   7576   2 powershell



PS C:\Users\aleescob> get-process -Name powershell | Get-member


   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64
PM                         AliasProperty  PM = PagedMemorySize64
SI                         AliasProperty  SI = SessionId
VM                         AliasProperty  VM = VirtualMemorySize64
WS                         AliasProperty  WS = WorkingSet64
Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Object, System.Diagnostics.DataReceivedEventArgs)
Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Object, System.Diagnostics.DataReceivedEventArgs)
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()
CancelErrorRead            Method         void CancelErrorRead()
CancelOutputRead           Method         void CancelOutputRead()


PS C:\Users\aleescob>
PS C:\Users\aleescob> get-process -Name powershell | Get-member | Select-Object name, membertype

Name                           MemberType
----                           ----------
Handles                     AliasProperty
Name                        AliasProperty
NPM                         AliasProperty
PM                          AliasProperty
SI                          AliasProperty
VM                          AliasProperty
WS                          AliasProperty
Disposed                            Event
ErrorDataReceived                   Event
Exited                              Event

 Share!

 
comments powered by Disqus