Scripting

Cmdlets

Cmdlets are the heart-and-soul of Windows Powershell. Cmdlets include everything from reading and writing text files, to managing event logs, to sorting and filtering data. Unlike traditional command-line interface commands, Windows Powershell Cmdlets are designed to deal with objects - structured information that is more than just a string of characters appearing on the screen. Powershell Cmdlets use the Verb-Noun pairs. The Verb part of the name identifies the action the Cmdlet will perform.

Key built-in Cmdlets

Get-Help → Retrieves a list of all available Powershell Cmdlets.

Get-Command → Retrieves a list of all available Powershell Cmdlets.

Get-ChildItem → Gets the files and folders in a file system drive (has as alias 'dir' and 'ls').

Get-Content → Gets the contents of a file.

Where-Object → Selects Objects from a collection based on their property values.

ForEach-Object → Performs an operation against each item in a collection of input objects.

Select-Object → Selects objects or object properties.

Out-File → Finds text in strings and files.

Out-Null → Sends output to a file.

Out-Grid → Sends output to an interactive table in a separate window.

New-Object → Creates an instance of a Microsoft .NET Framework or COM object.

Write-Host → Writes customized output to a host.

Write-output → Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.

Pipelines

Cmdlets are most powerful when working together. The output from one command can be sent to another command through a "pipeline" by using the | character.

Examples

Get-ChildItem | Select-Object name, length | sort-object length

Get-Command -verb write | Get-Help | out-file write-commands.txt

Get-Content "D:\\Samples\\Nmap_scanme.xml" | Select-String "<port "

Variables

Variables are universal in-memory data storage, and variable names always start with a "$". Any command output can be stored in a variable for later use.

$Name = "Inigo Montoya"
Write-Host "Hello My Name is $Name. You killed my father prepare to die!"

$files = Get-ChildItem "D:\\Samples\\"

You can specify what type of variable to save by using the [_type] notation. Powershell will automatically attempt to convert the output to that type of object is possible.

The following automatically attempts to parse an input file as an XML object.

[xml]$scan = Get-Content "D:\\Samples\\Nmap_scanme.xml"
$scan.nmaprun.host.ports.port | select-object portid, protocol | Out-GridView

[int32] $intTest = 20

You can save any object into variables, including .NET and COM objects, even applications.

$sw = New-Object "System.Diagnostics.Stopwatch"
$sw | Get-Member
$sw.start
$sw.stop
$sw.Elapsed

$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate("<http://www.hack3rcon.org>")
$html = $ie.Document.Body.InnerText
$ie.Quit()
Remove-Variable $ie

Scripts

Scripts allow you to combine multiple commands into one easy to run file. Scripts can be entirely self contained or can take command-line arguments.

To start Powershell's script editor type powershell_ise.exe in the command-line.

base64.ps1

$string = "Random text to convert to base 64" #Store a string into a variable

$bytes = [System.Text.Encoding]::UTF8.GetBytes($string) #Convert string to bytes
$b64 = [System.Convert]::ToBase64String($bytes) #Convert bytes to base 64
Write-Host $b64 #Print base 64 convertion of the string

$bytes2 = [System.Convert]::FromBase64String($b64) #Convert base 64 to bytes
$output = [System.Text.Encoding]::UTF8.GetString($bytes2) #Convert bytes to string
Write-Host $output #Prints the string

base64_input.ps1

Param (
[Parameter(Mandatory=$True)]
[string] $string
) #Gets input from the user

#The rest of the code does the same as the script before
$bytes  = [System.Text.Encoding]::UTF8.GetBytes($string)
$b64 = [System.Convert]::ToBase64String($bytes)
Write-Host $b64

$bytes2  = [System.Convert]::FromBase64String($b64)
$output = [System.Text.Encoding]::UTF8.GetString($bytes2)
Write-Host $output

Functions

Functions allow you to create something in memory that looks, works, smells and feels almost exactly like a native Cmdlet. While it is not mandatory to do so, it is highly encourage to follow the Verb-Noun rules using approved verbs when naming functions.

The basic construct of a function is:

Function Verb-Noun {
    [CmdletBinding()]
    param
    (
        ValueFromPipeline=$True,
        [string]$input
    )
	
	Begin{
		Write-Host "This is run once at the start of the function and is used to set-up the function"
	}
	Process{
		Write Host "This is run for each object passed through the pipeline"
	}
	End{
		Write-Host "This is run once at the end of the function and is used to tear down the function"
	}
}

convert-StringToBase64.ps1

function Convert-StringToBase64 {
  <#
  .SYNOPSIS
  Converts a string into a Base64 String
  .DESCRIPTION
  Converts a string into a Base64 String
  .EXAMPLE
  Convert-StringToBase64 -String "This is my String"
  .PARAMETER Input
  The String to convert
  #>
  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$True,
    ValueFromPipeline=$True,
      HelpMessage='String to Convert')]
    [string]$string
  )

  begin {

  }

  process {

        write-verbose "Converting $string"

        $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string)
        $b64 = [System.Convert]::ToBase64String($bytes)
        Write-Output $b64
  }
  
  end{
     
  }
}

function Convert-Base64toString {
  <#
  .SYNOPSIS
  Converts a Base64 String to and String
  .DESCRIPTION
  Converts a Base64 String to and String
  .EXAMPLE
  Convert-Base64toString -String "VGhpcyBpcyBteSBTdHJpbmc="
  .PARAMETER Input
  The String to convert
  #>
  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$True,
    ValueFromPipeline=$True,
      HelpMessage='String to Convert')]
    [string]$string
  )

  begin {

  }

  process {

    write-verbose "Converting $String"

    $bytes2  = [System.Convert]::FromBase64String($String)
    $output = [System.Text.Encoding]::UTF8.GetString($bytes2)
    Write-Host $output
  }
  
  end{
     
  }
}

Modules

"A script module is a file (.psm1) that contains any valid Windows PowerShell code. Script developers and administrators can use this type of module to create modules whose members include functions, variables, and more"

Last updated