0% found this document useful (0 votes)
45 views25 pages

Powershell

Uploaded by

pathakshat1791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views25 pages

Powershell

Uploaded by

pathakshat1791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PowerShell Basics

PowerShell is a cross-platform and a commonly used task automation solution


combining the power of the command-line shell, a scripting language, and a
configuration management framework. You can run PowerShell on Windows, Linux, and
macOS operating systems. Unlike other available shells that only accept and return
data, PowerShell accepts and returns .NET objects.

This shell comes with the following features.

● Robust command-line history


● Extensive features, like tab completion and command prediction
● Command and parameter aliases
● Pipeline for changing commands
● In-console help system, like Unix man pages

Considering the features of any scripting language, you can use PowerShell to
automate the system management process and task. It lets you build, test, and deploy
solutions in CI/CD environments.
PowerShell is built on the .NET Common Language Runtime (CLR), which means all
the inputs and outputs are .NET objects. You do not have to parse text output to retrieve
information from it.

The PowerShell scripting language comes with the following features.

● Functions, classes, objects, and modules


● Easy formatting system for providing clear output for enhanced readability
● Built-in support for different data formats, such as CSV, JSON, and XML
● Type system for creating dynamic types

Now, let’s get into some useful PowerShell commands.

PowerShell Commands Cheat Sheet

cmdlets
Cmdlets are PowerShell’s internal commands. These cmdlets will return one or more
objects to the pipeline where at the end of that pipeline, we mention some properties of
the objects in the following table to see their values displayed on the screen.

Command Description

This command allows you to get support with PowerShell.


Get-Help

This command offers you a list of available PSDrives, such


Get-PSdrive as c, env, hklm, hkcu, alias, etc.

In any registry, children are the subkeys of the current key. To get
Get-ChildItem the required details, you can use the following command.

Get-ChildItem Run this command to list all the children recursively of the
-recurse current PSdrive, folder, or registry key.
Get-ChildItem -rec Use this command To include the hidden folders (directories).
-force

(Get-ChildItem).na Run any of these commands to get the list file and directory
me or names in the current folder.
Get-ChildItem
-name

(Get-ChildItem).co Use this command to get the number of entries in the


unt collection of objects returned by the Get-Children.

PSdrives
PSdrives are the collection of entities grouped together so they can be accessed as a
filesystem drive. The “PSprovider” does this grouping.

By default, a PS session can access several PSdrives including c:, env:, alias:, and
HKLM:, where c: refers to the usual Windows c-drive; env: is the space of Windows
environmental variables; alias: is the collection of cmdlet aliases; and HKLM is a hive in
the registry.

Any PS session will enter the user’s home folder. If you want to switch from a PS
session to another PSdrive and retrieve the information from that drive, consider the
following commands:

Commands Description

Switching to env- The prompt character will change to the “ENV:\>”.


Set-Location env by running the following command:

Set-Location env-

Env:\> This command will get you all the environment variables.
Get-Childitem
Env:\> Use this command to get the environment variables of
Get-Childitem “userprofile.”
userprofile

Env:\> Run the following command to change the prompt character


Set-Location to “Alias.”
alias:

Alias:\> Run this command to get all the children of all aliases.
Get-Childitem

Alias:\> Use this command to get the “C:/>” prompt again, back to
Set-Location C:\ the default drive.

C:\Users\user_na Run this command to find what alias “ls” stands for.
me>$alias:ls

Pipelines
Cmdlets uses the pipelines to pass the objects but not the character streams like Unix.
The pipeline character is | (ASCII 124), followed by a command that handles the output
passed through the pipeline. The pipeline consists of the following three stages.

Get-ChildItem *.txt | Where-Object length -lt 1000 | Sort-Object length

The following table highlights some of the basic pipeline commands:

Command Description

(Get-Item Easily sets the value of the ‘lastwritetime.year’ property to the


/Users/praashibansal/Des present date and time without affecting the file’s content.
ktop).lastwritetime.year

(Get-ChildItem data.txt.rtf Provides an empty result


-name).name # -> null

"data.txt.rtf" | Changes the old file names and file extensions to the new
Rename-Item -NewName ones
"data_new.txt.rtf"

Get-ChildItem data.txt | A trivial renaming command that invokes an automatic


Rename-Item -new variable
{$_.name}
Get-ChildItem data.txt.rtf If the piped object $_ doesn't have the member property
-name | Rename-Item (name), you will receive an error, as parameter $_.name is
-new {$_.name} null

Get-ChildItem | Displays the list of the names of all the files that are present
Select-Object basename | in the current folder sorted in alphabetical order.
Sort-Object *

Move-Item *.txt Moves all the files to the folder subdirectory


subdirectory

Get-ChildItem *.txt | Gives the error message that Move-Item lacks input
Move-Item ..\

Alias
Cmdlets come with several aliases. The following table highlights a few of aliases, along
with their descriptions:

Command Description

Add-Content Appends value to a file

Get-Content Finds file content in an array

Set-Location Changes folder, key, or PS drive

Clear-Host Clears console

Remove-Item Delete files

Get-ChildItem -Path .\ Lists Folder, Key, or PSDrive Children

Write-Output Sends the array to the console, pipeline, or redirect it to the


file

Foreach-Object Traverses each object in a pipeline

Format-Table Formats the table with selected properties for each object in
each column

Format-List Formats the process properties by name

Get-Alias Provides Cmdlet Alias

Get-Command Provides you with commands from the current session only

Get-Member Retrieves all the object members


Get-ItemProperty Provides the specified item’s properties
.\data.txt | Format-List

Get-ItemPropertyValue Gives the current value for a specified property while using
-Path '.\data.txt' -Name the name parameter
LastWriteTime

Get-Variable m* Finds session variable names and sessions

New-Item -Path .\ -Name Creates a new file, directory, symbolic link, registry key, or
"testfile1.txt" -ItemType registry entry
"file" -Value "This is a text
string."

Get-Process Gives the entire list of all the running processes

Get-Location Provides the current directory’s or registry key’s location

Rename-Item -Path Renames the old item name with the new name
“old_name” -NewName
“new_name”

Remove-Item Removes the specified directory, files, or registry keys


.\testfile1.txt

Remove-Variable Removes the specified variable

Start-Sleep Suspends an activity for a specified period of time

Operators

● Arithmetic Operators
Operator Description Example
+ Adds integers; concatenates 6+2
strings, arrays, and hash tables. "file" + "name"
@(1, "one") + @(2.0, "two")
@{"one" = 1} + @{"two" = 2}
+ Makes a number out of an object 123
- Subtracts one value from another 6-2
- Calculates the opposite number - -6
(Get-Date).AddDays(-1)

* Multiply numbers or copy strings 6 * 2


and arrays for a specified number
of times
@("!") * 4
"!" * 3
/ Divides two values 6/2
% Modulus - returns the remainder of 7 % 2
a division operation
-band Bitwise AND 5 -band 3
-bnot Bitwise NOT -bnot 5
-bor Bitwise OR 5 -bor 0x03
-bxor Bitwise XOR 5 -bxor 3
-shl Shifts bits to the left 102 -shl 2
-shr Shifts bits to the right 102 -shr 2

Operator Precedence

Precedence Operator Description


1 () Parentheses
2 - For a negative number or unary operator

3 *, /, % For multiplication and division

4 +,- For addition and subtraction

5 -band, -bnot, For bitwise operations


-bor, -bxor,
-shr, and -shl

● Assignment Operators

Operator Description
= Sets a variable’s value to the specified value
+= Increases a variable’s value by the specified value or appends the
specified value to the existing value
-= Decreases a variable’s value by a specified value
*= Multiplies a variable’s value by a specified value, or appends the
specified value to the existing value
/= Divides a variable’s value by a specified value
%= Divides the variable’s value by a specified value and then assigns the
remainder (modulus) to the variable.
#ERROR Increases a variable’s value, assignable property, or array element by 1.
!
-- Decreases the variable’s value, assignable property, or array element by
1.

● Comparison Operators

Type Operator Comparison test

Equality -eq equals


-ne not equals
-gt greater than
-ge greater than or equal

-lt less than


-le less than or equal
Matching -like string matches wildcard pattern

-notlike string doesn't match wildcard pattern

-match string matches regex pattern

-notmatch string doesn't match regex pattern

Replacement -replace replaces strings matching a regex pattern


Containment -contains collection contains a value
-notcontains collection doesn't contain a value
-in value is in a collection

-notin value is not in a collection

Type -is both objects are the same type

-isnot objects are not the same type

● Logical Operators

Operator Description Example


-and Logical AND. TRUE when both (1 -eq 1) -and (1 -eq 2)
statements are true.
FALSE
-or Logical OR. TRUE when either of (1 -eq 1) -or (1 -eq 2)
the statements is TRUE. TRUE

-xor Logical EXCLUSIVE OR. TRUE (1 -eq 1) -xor (2 -eq 2)


when only one statement is TRUE. FALSE
-not Logical not. Negates the statement -not (1 -eq 1)
that follows. FLASE
! Same as -not !(1 -eq 1)
FALSE

● Redirection Operator

Operator Description Syntax


> Send specified stream to a file n>
>> Append specified stream to a file n>>
>&1 Redirects the specified stream to the Success stream n>&1

● Type Operators

Operator Description Example


-isNot Returns TRUE when the (get-date) -isNot [DateTime]
input not an instance of the FALSE
specified.NET type.

-as Converts the input to the "5/7/07" -as [DateTime]


specified .NET type. Monday, May 7, 2007 00:00:00

Some Other Operators

Operator Description

() Grouping Allows you to override operator precedence in expressions


Operator

&() Subexpression Gives you the result of one or more statements


Operator

@( ) Array Returns the results of one or more statements in the form of


Subexpression arrays.
Operator

& Background The pipeline before & is executed by this command in a


Operator Powershell job.

[] Cast Operator Converts objects to the specific type.

Regular Expressions
A regular expression is a pattern that is used to match text that includes literal
characters, operators, and other constructs. PowerShell regular expressions are
case-insensitive by default.

Method Case Sensitivity


Select-String use -CaseSensitive switch
switch use the -casesensitive option
statement
operators prefix with 'c' (-cmatch, -csplit, or -creplace)
● Character Literals
A regular expression can be a literal character or a string.

● Character Groups
These allow you to match any number of characters one time, while [^character group]
only matches characters NOT in the group.

● Character Range
A pattern can also be a range of characters. The characters can be alphabetic [A-Z],
numeric [0-9], or even ASCII-based [ -~] (all printable characters).

● Numbers
The \d character class will match any decimal digit. Conversely, \D will match any
non-decimal digit.

● Word Character
The \w character class will match any word character [a-zA-Z_0-9]. To match any
non-word character, use \W.
● Wildcard
The period (.) is a wildcard character in regular expressions. It will match any character
except a newline (\n).

● Whitespace
Whitespace is matched using the \s character class. Any non-whitespace character is
matched using \S. Literal space characters ' ' can also be used.

● Escaping Characters
The backslash (\) is used to escape characters so the regular expression engine doesn’t
parse them.

The following characters are reserved: []().\^$|?*+{}.

● Substitution in Regular Expression.


The regular expressions with the -replace operator allows you to dynamically replace
text using captured text.
<input> -replace <original>, <substitute>

Flow Control

● ForEach-Object
ForEach-Object is a cmdlet that allows you to iterate through items in a pipeline, such
as with PowerShell one-liners. ForEach-Object will stream the objects through the
pipeline.

Although the Module parameter of Get-Command accepts multiple values that are
strings, it will only accept them via pipeline input using the property name, or parameter
input.

If you want to pipe two strings by value to Get-Command for use with the Module
parameter, use the ForEach-Objectcmdlet:

$ComputerName = 'DC01', 'WEB01'


foreach ($Computer in $ComputerName) {
Get-ADComputer -Identity $Computer
}

● For
A “for” loop iterates while a specified condition is true.

For example:

for ($i = 1; $i -lt 5; $i++) {


Write-Output "Sleeping for $i seconds"
Start-Sleep -Seconds $i
}
● Do
There are two different “do” loops in PowerShell. Do Until runs while the specified
condition is false.

Example 1:
$number = Get-Random -Minimum 1 -Maximum 10
do {
$guess = Read-Host -Prompt "What's your guess?"
if ($guess -lt $number) {
Write-Output 'Too low!'
}
elseif ($guess -gt $number) {
Write-Output 'Too high!'
}
}
until ($guess -eq $number)

Example 2:

$number = Get-Random -Minimum 1 -Maximum 10


do {
$guess = Read-Host -Prompt "What's your guess?"
if ($guess -lt $number) {
Write-Output 'Too low!'
} elseif ($guess -gt $number) {
Write-Output 'Too high!'
}
}
while ($guess -ne $number)
● While
Similar to the Do While loop, a While loop runs as long as the specified condition is true.
The difference however, is that a While loop evaluates the condition at the top of the
loop before any code is run. So, it doesn't run if the condition evaluates to false.

For example:

$date = Get-Date -Date 'November 22'


while ($date.DayOfWeek -ne 'Thursday') {
$date = $date.AddDays(1)
}
Write-Output $date

Variables
PowerShell allows you to store all types of values. For example, it can store command
results and command expression elements like names, paths, and settings. Here are
some of PowerShell’s different variables.

● User-created variables: These are created and maintained by the user. The
variables you create at the PowerShell command line will only exist until the
PowerShell window is open. When you close the PowerShell window, these
variables are deleted. If you want to save a variable, you need to add it to your
PowerShell profile. You can create variables and declare them with three
different scopes: global, script, or local.

● Automatic variables: These variables store the state of PowerShell and are
created by PowerShell. Only PowerShell can change their values as required to
maintain accuracy. Users can’t change these variables’ value. For example, the
$PSHOME variable will store the path to the PowerShell installation directory.

● Preference variables: These variables store user preferences for PowerShell


and are created by PowerShell. These variables are populated with default
values and can be changed by the users. For example, the
$MaximumHistoryCount variable specifies the maximum number of entries in the
session history.

To create a new variable, you need to use an assignment statement and assign a value to the
variable. There is no need to declare the variable before using it. The default value of all
variables is $null.

For example-
$MyVariable = 1, 2, 3
$MyVariable

Function

● Naming Your Function


Use a Pascal case name with an approved verb and a singular noun to name a
function. You can get a list of approved verbs by running Get-Verb:

Get-Verb | Sort-Object -Property Verb


● Creating a Simple Function
Use a function keyword followed by the function name to create a simple function. Then,
use an open and closing curly brace. The function will execute code contained within
those curly braces.

For example:

function Get-Version {
$PSVersionTable.PSVersion
}

Working with Modules


A module is a package containing PowerShell members, such as cmdlets, providers,
functions, workflows, variables, and aliases. You can implement package members in a
PowerShell script, a compiled DLL, or both. PowerShell automatically imports the
modules the first time you run any command in an installed module. You can use the
commands in a module without setting up or profile configuration.

● How to Use a Module


To use any module, you need to first install them. Then, find the command that comes
with the module and use them.
● Installing a Module
If you get a module as a folder, install it before you use it on the PowerShell command
line. Some modules are preinstalled. You can use the following command to create a
Modules directory for the current user:

New-Item -Type Directory -Path $HOME\Documents\PowerShell\Modules

Copy the entire module folder into the Modules directory. You can use any method to
copy the folder, including Windows Explorer, Cmd.exe, and PowerShell.

● Finding the Installed Modules


Run the following to find the modules installed in a default module location (not
imported).

Get-Module -ListAvailable

● Finding Commands in a Module


Run the following command to find a module’s commands:

Get-Command -Module <module-name>


Get-Command -Module Microsoft.PowerShell.Archive
● Importing a Module
Run the following command with the proper module name:

Import-Module <module-name>

● Removing a Module Name


You can run the following command with the proper module name:

Remove-Module <module-name>

● View Default Module Locations


Use the following command to view default module locations:

$Env:PSModulePath

● Add a Default Module Location


You can use the following command format:

$Env:PSModulePath = $Env:PSModulePath + ";<path>"

● Add a Default Module Location on Linux or MacOS


Use the following to execute the same command as above, only with Linux or macOS:

$Env:PSModulePath += ":<path>"

Hash Tables
A hash table is a complex data structure to store data in the form of key-value pairs. We
also refer to a hash table as a dictionary or associative array. To understand a hash
table, consider a series of IP addresses and the respective computer names. A hash
stores this data in the form of key-value pairs, where IP addresses refer to keys and
computer names to their corresponding values.

The hash table syntax is as follows:

@{ <name> = <value>; [<name> = <value> ] ...}


An ordered dictionary’s syntax is as follows:

[ordered]@{ <name> = <value>; [<name> = <value> ] ...}

● Creating Hash Tables


If you want to create a hash table, follow these steps:
● Start the hash table with an at sign (@) and enclose it in curly braces ({}).
● A hash table should contain at least one key-value pair, and hence, enter the
data after creating a hash table.
● Separate key from its value using an equal sign (=).
● Separate the key/value pairs in a hash table with a semicolon (;).
● Enclose the space between the keys in quotation marks. Values must be valid
PowerShell expressions. Also, enclose strings in quotation marks, even if there
are no spaces between them.
● Save a hash table as a variable to manage it efficiently.
● When assigning an ordered hash table to a variable, place the [ordered] attribute
before the @ symbol. If you place it before the variable name, the command fails.

For example:
$hash = @{}
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}

[hashtable]$hash = [ordered]@{
Number = 1; Shape = "Square"; Color = "Blue"}
$hash

● Adding and Removing Keys and Values


To add keys and values to a hash table, use the following command format:

$hash["<key>"] = "<value>"

For example, you can add a "Time" key with a value of "Now" to the hash table with the
following statement format:
$hash["Time"] = "Now"

Or

$hash.Add("Time", "Now")

Or, you can remove the key with this statement format:

$hash.Remove("Time")

Asynchronous Event Handling


These cmdlets allow you to register and unregister event subscriptions and list the
existing subscriptions. You can also list pending events and handle or remove them as
desired.
PowerShell eventing cmdlets

Eventing Cmdlet name Description

Register-ObjectEvent This cmdlet registers an event subscription for events


generated by .NET objects
Register-WmiEvent Registers an event subscription for events generated by
WMI objects
Register-EngineEvent Registers an event subscription for events generated by
PowerShell itself
Get-EventSubscriber Gets a list of the registered event subscriptions in the
session
Unregister-Event Removes one or more of the registered event
subscriptions
Wait-Event Waits for an event to occur. This cmdlet can wait for a
specific event or any event. It also allows a timeout to be
specified, limiting how long it will wait for the event. The
default is to wait forever.
Get-Event Gets pending unhandled events from the event queue

Remove-Event Removes a pending event from the event queue


New-Event This cmdlet is called in a script to allow the script to add its
own events to the event queue
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Useful Commands Bitwise Operators , Comma operator (Array


-band Bitwise AND constructor)
Update-Help Downloads and installs newest help -bor Bitwise OR (inclusive) . Dot-sourcing operator runs a
files -bxor Bitwise OR (exclusive) script in the current scope
Get-Help Displays information about -bnot Bitwise NOT . c:\scripts\sample.ps1
commands and concepts -shl, -shr Bitwise shift operators. Bit
Get-Command Gets all commands shift left, bit shift right $( ) Subexpression operator
Get-Member Gets the properties and methods (arithmetic for signed, @( ) Array subexpression operator
of objects logical for unsigned values) & The call operator, also known as
Get-Module Gets the modules that have been the "invocation operator," lets
imported or that can be imported Other Operators you run commands that are
into the current session -Split Splits a string stored in variables and
“abcdefghi” -split “de” represented by strings.
Operators $a = "Get-Process"
-join Joins multiple strings & $a
Assignment Operators $sb = { Get-Process | Select –First 2 }
“abc”,”def”,”ghi” -join “;”
=, +=, -=, *=, /=, %=, ++, -- Assigns one or more values & $sb
to a variable
.. Range operator Logical Operators
1..10 | foreach {$_ * 5} -and, -or, -xor, -not, ! Connect expressions and
Comparison Operators
-eq, -ne Equal, not equal statements, allowing you to test
-is, -isnot Type evaluator (Boolean). for multiple conditions
-gt, -ge Greater than, greater than
Tells whether an object is an Redirection Operators
or equal to
instance of a specified .NET >, >> The redirection operators enable
-lt, -le Less than, less than or
Framework type. you to send particular types of
equal to
42 –is [int] output (success, error, warning,
-replace changes the specified
elements of a value verbose, and debug) to files and
-as Type convertor. Tries to to the success output stream.
“abcde” -replace “bc”, “TEST”
convert the input object to Output streams * All output
the specified .NET 1 Success output
-match, -notmatch Regular expression match
Framework type. 2 Errors
-like, -notlike Wildcard matching
$a = 42 –as [String] 3 Warning messages
-contains, -notcontains Returns TRUE if the scalar
value on its right is 4 Verbose output
-f Formats strings by using the 5 Debug messages
contained in the array on
format method of string # Writes warning output to warning.txt
its left
objects Do-Something 3> warning.txt
1,2,3,4,5 -contains 3
1..10 | foreach { "{0:N2}" -f $_ } # Appends verbose.txt with the verbose output
-in, -notin Returns TRUE only when Do-Something 4>> verbose.txt
[] Cast operator. Converts or # Writes debug output to the output stream
test value exactly matches
limits objects to the Do-Something 5>&1
at least one of the
specified type # Redirects all streams to out.txt
reference values.
[datetime]$birthday = "1/10/66" Do-Something *> out.txt
“Windows”-in “Windows”,”PowerShell”
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Arrays $hash.key1 Returns value of key1 $a.Substring(0,3)


$hash["key1"] Returns value of key1 $a | Get-Member -MemberType Method -Static
"a", "b", "c" Array of strings $hash.GetEnumerator | sort Key Sorts a hash table by
1,2,3 Array of integers the Key property Static methods are callable with the "::" operator.
@() Empty array [pscustomobject]@{x=1; y=2} Creates a custom
@(2) Array of one element object [DateTime]::IsLeapYear(2012)
1,(2,3),4 Array within array
,"hi" Array of one element Comments Strings
$arr[5] Sixth element of array*
$arr[2..20] Returns elements 3 thru 21 # This is a comment because # is the first character of a "This is a string, this $variable is expanded as is $(2+2)"
$arr[-1] Returns the last array token ‘This is a string, this $variable is not expanded”
element
$arr[-3..-1] Displays the last three $a = "#This is not a comment…" @"
elements of the array $a = "something" # …but this is. This is a here-string which can contain anything including
$arr[1,4+6..9] Displays the elements at carriage returns and quotes. Expressions are evaluated:
index positions 1,4, and 6 Write-Host Hello#world $(2+2*5). Note that the end marker of the here-string must
through 9 be at the beginning of a line!
@(Get-Process) Forces the result to an Block Comments "@
array using the array sub-
expression operator <# This is @'
$arr=1..10 A multi-line comment #> Here-strings with single quotes do not evaluate expressions:
$arr[($arr.length-1)..0] Reverses an array $(2+2*5)
$arr[1] += 200 Adds to an existing value of Object Properties '@
the second array item
An object’s properties can be referenced directly with the Variables
(increases the value of the
"." operator.
element) Format: $[scope:]name or ${anyname} or ${any path}
$b = $arr[0,1 + 3..6] Creates a new array based $a = Get-Date
on selected elements of an $a | Get-Member –MemberType Property $path = "C:\Windows\System32"
existing array $a.Date Get-ChildItem ${env:ProgramFiles(x86)}
$z = $arr + $b Combines two arrays into a $a.TimeOfDay.Hours $processes = Get-Process
single array, use the plus $a | Get-Member -MemberType Property –Static
operator (+) $global:a =1 # visible everywhere
Static properties can be referenced with the "::" operator. $local:a = 1 # defined in this scope and visible to children
*Arrays are zero-based $private:a = 1 # same as local but invisible to child scopes
[DateTime]::Now $script:a = 1 # visible to everything is this script
Associative Arrays (Hash tables) # Using scope indicates a local variable in remote commands
Methods and with Start-Job
$hash = @{} Creates empty hash table
$localVar = Read-Host "Directory, please"
@{foo=1; bar='value2'} Creates and initialize a
Methods can be called on objects. Invoke-Command -ComputerName localhost -ScriptBlock {
hash table
dir $using:localVar }
[ordered]@{a=1; b=2; c=3}Creates an ordered $a = "This is a string" Start-Job { dir $using:localVar -Recurse}
dictionary $a | Get-Member –MemberType Method $env:Path += ";D:\Scripts"
$hash.key1 = 1 Assigns 1 to key key1 $a.ToUpper()
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Get-Command -Noun Variable # the Variable Cmdlets $Host Reference to the application hosting the $OFS Output Field Separator. Specifies
Get-ChildItem variable: # listing all variables using the POWERSHELL language the character that separates the
variable drive $Input Enumerator of objects piped to a script elements of an array when the
$LastExitCode Exit code of last program or script array is converted to a string. The
# strongly-typed variable (can contain only integers) $Matches Exit code of last program or script default value is: Space.
[int]$number=8 $MyInvocation An object with information about the $OutputEncoding Determines the character
current command encoding method that Windows
# attributes can be used on variables $PSHome The installation location of Windows PowerShell uses when it sends
[ValidateRange(1,10)][int]$number = 1 PowerShell text to other applications
$number = 11 #returns an error $profile The standard profile (may not be $PSDefaultParameterValues Specifies default values for the
present) parameters of cmdlets and
# flip variables $Switch Enumerator in a switch statement advanced functions
$a=1;$b=2 $True Boolean value for TRUE $PSEmailServer Specifies the default e-mail server
$a,$b = $b,$a $False Boolean value for FALSE that is used to send e-mail
$PSCulture Current culture messages
# multi assignment $PSUICulture Current UI culture $PSModuleAutoLoadingPreference Enables and disables
$a,$b,$c = 0 $PsVersionTable Details about the version of Windows automatic importing of modules
$a,$b,$c = 'a','b','c' PowerShell in the session. "All" is the default.
$a,$b,$c = 'a b c'.split() $Pwd The full path of the current directory $PSSessionApplicationName Specifies the default application
name for a remote command that
# create read only variable (can be overwritten with - Windows PowerShell Preference Variables uses WS-Management technology
Force) $PSSessionConfigurationName Specifies the default session
Set-Variable -Name ReadOnlyVar -Value 3 -Option $ConfirmPreference Determines whether Windows configuration that is used for
ReadOnly PowerShell automatically PSSessions created in the current
prompts you for confirmation session
# create Constant variable (cannot be overwritten) before running a cmdlet or $PSSessionOption Establishes the default values for
Set-Variable -Name Pi -Value 3.14 -Option Constant function advanced user options in a
$DebugPreference Determines how Windows remote session
Windows PowerShell Automatic Variables PowerShell responds to
(not exhaustive) $VerbosePreference Determines how Windows
debugging PowerShell responds to verbose
$$ Last token of the previous $ErrorActionPreference Determines how Windows messages generated by a script,
command line PowerShell responds to a non- cmdlet or provider
$? Boolean status of last command terminating error $WarningPreference Determines how Windows
$^ First token of the previous $ErrorView Determines the display format PowerShell responds to warning
command line of error messages in Windows messages generated by a script,
$_, $PSItem Current pipeline object PowerShell cmdlet or provider
$Args Arguments to a script or function $FormatEnumerationLimitDetermines how many $WhatIfPreference Determines whether WhatIf is
$Error Array of errors from previous enumerated items are included automatically enabled for every
commands in a display command that supports it
$ForEach Reference to the enumerator in a $MaximumHistoryCount Determines how many
foreach loop commands are saved in the
$Home The user’s home directory command history for the
current session

You might also like