PS: Intro Commands

3 minute read

Description:

These are entry level Powershell Commands and how the language works:

NOTE: Almost all command prompt commands work just as well in Powershell. Search the “batch” label to see examples of them.

Syntax

Cmdlets are small scripts that follow a dash-separated verb-noun convention such as “Get-Process”. Similar Verbs with Different Actions:

– New- Creates a new resource
- Set- Modifies an existing resource
- Get- Retrieves an existing resource
- Read- Gets information from a source, such as a file
- Find- Used to look for an object
- Search- Used to create a reference to a resource
- Start- (asynchronous) begin an operation, such as starting a process
- Invoke- (synchronous) perform an operation such as running a command

Parameters: Each verb-noun named cmdlet may have many parameters to control cmdlet functionality.

Objects: The output of most cmdlets are objects that can be passed to other cmdlets and further acted upon. This becomes important in pipelining cmdlets.

ps-entry-commands

More: https://ramblingcookiemonster.wordpress.com/2012/09/07/powershell-cheat-sheet/

Useful Cmdlets (and aliases)

Get a directory listing (ls, dir, gci):

Get-ChildItem

Copy a file (cp, copy, cpi):

Copy-Item src.txt dst.txt

Move a file (mv, move, mi):

Move-Item src.txt dst.txt

Find text within a file:

Select-String –path c:users*.txt –pattern password
ls -r c:users -file | % {Select-String -path $_ -pattern password}

Display file contents (cat, type, gc):

Get-Content file.txt

Get present directory (pwd, gl):

Get-Location

Get a process listing (ps, gps):

Get-Process

Get a service listing:

Get-Service

Formatting output of a command (Format-List):

ls | Format-List –property name

Paginating output:

ls –r | Out-Host -paging

Get the SHA1 hash of a file:

Get-FileHash -Algorithm SHA1 file.txt

Exporting output to CSV:

Get-Process | Export-Csv procs.csv

Pipelining, Loops, and Variables

Piping cmdlet output to another cmdlet:

Get-Process | Format-List –property name

ForEach-Object in the pipeline (alias %):

ls *.txt | ForEach-Object {cat $_}

Where-Object condition (alias where or ?):

Get-Process | Where-Object {$_.name –eq "notepad"}

Generating ranges of numbers and looping:

1..10 | ForEach-Object{ New-Item -Name "$psitem.txt" -ItemType File} # creates 10 text files
1..10 | % {echo "Hello!"} # writes "Hello!" 10 times

Creating and listing variables:

$tmol = 42
ls variable:

Examples of passing cmdlet output down pipeline:

dir | group extension | sort
Get-Service dhcp | Stop-Service -PassThru | Set-Service -StartupType Disabled

To Give A Choice

$OUPathValidate = $true
While ($OUPathValidate) 
{
    $OUPath = Read-Host 'INTERN/EXTERN'
    If ($OUPath.ToUpper() -eq 'INTERN') 
	{
        $OUPath = 'OU=Intern,OU=Users,OU=Zero,DC=int,DC=zero,DC=com'
        $OUPathValidate = $false
    } 
	ElseIf ($OUPath.ToUpper() -eq 'EXTERN')
	{
        $OUPath = 'OU=Extern,OU=Users,OU=Zero,DC=int,DC=zero,DC=com'
        $OUPathValidate = $false
    }
	Else 
	{
        Write-Host 'That is not a valid input, please use INTERN or EXTERN'
    }
}

How to Trap Errors

# Run your code with the ErrorVariable switch. Remember to just use a string as the name, no $ required
Get-ChildItem $path | Move-Item -Destination $newlocation -ErrorVariable fileErrors

# Your exceptions are now here
$fileErrors

# or:
[System.Collections.ArrayList]$MoveItemErrors = @()
$ItemsToMove = Get-ChildItem $path
foreach ($item in $ItemsToMove) {
    try {
        $item | Move-item -Destination $newlocation -ErrorAction Stop
    }
    catch {
        $null = $MoveItemErrors.Add($_)
    }
}

Hashtables:

$Params = @{
    'Path' = "HKCU:\Some\Path"
    'Name' = "Category"
    'Value' = "1" 
    'Type' = "DWORD"
}
SetReg @Params | Out-Null


Arrays – Use lists instead where appropriate

$Array = [System.Collections.Generic.List[PSObject]]@()
foreach ($I in $Items) 
{ 
[void]$Array.Add($Item) 
}

To See If A Switch Was Used

If ([Bool]($MyInvocation.BoundParameters.Keys -match 'Recurse')) { # Parameter 'Recurse' was used } Else { # Parameter 'Recurse' was NOT used }

Learn to Use #Requires Statements

#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -PSEdition <PSEdition-Name>
#Requires -ShellId <ShellId>
#Requires -RunAsAdministrator

To Pause A Script

Function Stop-Script 
{
Write-Output "Press Any Key To Continue ..."
$Host.Ui.Rawui.Readkey("Noecho,Includekeydown") | Out-Null
}
# or
cmd /c "pause"

To Set Param Blocks

# If in PS ISE, just use Ctrl+J!!
# If not, something like
[Cmdletbinding()]
    Param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
		[String[]]$RegistryKey,
        
        [Parameter(Mandatory=$true, Position=1)]
		[String]$Username
    )