function <name>
{
[CmdletBinding(SupportsShouldProcess=$True)] Param (
[type] $var1 [= <var1-default-value>],
[type] $var2 [= <var2-default-value>] ...
) Begin{
# optional one-time preprocessing
# for the function
}
Process{
# provide record-by-record processing for
# the function.
# can use a Process block without defining
# Begin/End blocks.
} End{
# optional one-time post-processing
# for the function
}
}
eg. 1 - without parameters
function Get-ServiceInfo
{
Get-Service -Name spooler -ComputerName MyServer
}
e.g. 1 use it to compare content of 2 text files
$ref = get-content c:\temp\A.txt
$diff = get-content c:\temp\B.txt
Compare-Object -ReferenceObject $ref -DifferenceObject $diff
Note for exponetiation, use [Math]::Pow(x, y) for x raise to the power of y.
Comparison operators
-eq Equal
-ne Not equal
-gtGreater than
-geGreater than or equal
-ltLess than
-leLess than or equal
-Likepositive wildcard match
-NotLikenegative wildcard match
-Matchpositive Regex match
-NotMatchnegative Regex match
-Containsscalar (on the right)
is a member of the list (on the left)
-NotContainsscalar (on the right)
not member of a list (on the left)
-InTRUE when test value matches
at least one of the reference values
-NotInTRUE when test value does not match
any of the reference values
-ReplaceChanges the specified elements of a
value
Example : -eq
> 1+1 -eq 2
True
Example : -ne
> 1+1 -ne 3
True
Example : -gt
> 1+1 -gt 1
True
Example : -ge
> 1+1 -ge 2
True
Example : -lt
> 1+1 -lt 3
True
Example : -le
> 1+1 -le 2
True
Example : -like
> "Hello" -like "Hell*"
True
Example : -notlike
> "Hello" -notlike "Hea*"
True
Example : -match > "two words" -match 'two (\w+)'
True
> # capturing groups () results saved in array $matches
> $matches
Name Value
---- -----
1 words
0 two words
Example : -notmatch
> "two words" -notmatch 'three \w+'
True
Example: -contains
> 1,2,3,4,5 -contains 3
True
Example : -notcontains > 1,2,3,4,5 -notcontains 6
True
example for If
if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}
example for if-else
if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}
else
{Write-Host "Another Language" -ForegroundColor Cyan}
example for if-elseif if ($Language -eq "1033")
{
Write-Host "Language = English US" -ForegroundColor Magenta
}
elseif ($Language –eq "1078")
{
Write-Host "Language = Afrikaans" -Foregroundcolor Green
}
example for if-elseif-else if ($Language -eq "1033")
{
Write-Host "Language = English US" -ForegroundColor Magenta
}
elseif ($Language –eq "1078")
{
Write-Host "Language = Afrikaans" -Foregroundcolor Green
}
else
{
Write-Host "Another Language" -ForegroundColor Cyan
}
global: - Specifies that the name exists in the Global scope.
local: - Specifies that the name exists in the Local scope. The current scope is always the Local scope.
private: - Specifies that the name is Private and only visible to the current scope.
script: - Specifies that the name exists in the Script scope. Script scope is the nearest ancestor script file's scope or Global if there is no nearest ancestor script file.
using: - Used to access variables defined in another scope while running scripts via cmdlets like Start-Job and Invoke-Command.
workflow: - Specifies that the name exists within a workflow. Note: Workflows are not supported in PowerShell Core.
function scope modifier
function [<scope-modifier>]:<name>
{<function-body>}
Dot Source Notation
. <scriptname>
By default, child scope created when script or function runs, but prefixing with dot and space (i.e. Dot-source) does not create a child scope
#Retrieve the current date and time, but display only the date:
> get-date -DisplayHint date
Tuesday, November 26, 2019
#Retrieve the current date and time in specific format
> get-Date -format "dd-MMM-yyyy HH:mm"
26-Nov-2019 18:06
#Retrieve the current date and time, display as a General short date/time:
> get-date -format g
11/26/2019 6:06 PM
#Display the day of the year:
> (get-date).dayofyear
330
#Get the day of the week as an integer (0=Sunday, 6=Saturday):
> [Int]$dow = Get-Date | Select-Object -ExpandProperty DayOfWeek
> $dow
2
# Display yesterdays date, using the .AddDays method:
> (get-date).AddDays(-1)
Monday, November 25, 2019 6:09:10 PM
# Get a specific date:
> Get-Date -date "2018-02-28"
Wednesday, February 28, 2018 12:00:00 AM
# Display daylight savings and UTC:
> (get-date).IsDaylightSavingTime()
False
> (get-date).ToUniversalTime()
Tuesday, November 26, 2019 10:10:39 AM
# or display in ISO 8601 format:
> (get-date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')
2019-11-26 10:10:39
try {
$wc = new-object System.Net.WebClient
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
} catch [System.Net.WebException],[System.IO.IOException] {
"Unable to download MyDoc.doc from http://www.contoso.com."
} catch {
"An error occurred that could not be resolved."
} finally {
"While trying to download http://www.contoso.com/MyDoc.doc and save"
}
enum <enum-name> {
<label> [= <int-value>]
...
}
# More info PS> get-help about_enum
enum is used to declare an enumeration; a distinct type that consists of a set of named labels called the enumerator list.
Enumerations are internally represented as integers with a starting value of zero. The first label in the list is assigned the value zero. The remaining labels are assigned with consecutive numbers.
In the definition, labels can be given any integer value. Labels with no value assigned take the next integer value.
The hidden keyword can hide properties, methods (including constructors, events, alias properties, and other member types, including static members, from the default results of the Get-Member cmdlet, and from IntelliSense and tab completion results
Example : hidden
class Car
{
# Properties
[String] $Color
[String] $ModelYear
[int] $Distance
# the Throw keyword in the parameter subexpression makes
# the Path parameter a required parameter in the function function Get-XMLFiles
{
param ($path = $(throw "The Path parameter is required."))
dir -path $path\*.xml -recurse |
sort lastwritetime |
ft lastwritetime, attributes, name -auto
}
Exampleif (-not (Test-Path -Path C:\DoesNotExist.txt)) { throw 'The file does not exist' } else { Write-Host 'The file does exist' }
The Trap statement includes a list of statements to run when a terminating error occurs. A Trap statement consists of the Trap keyword, optionally followed by a type expression, and the statement block containing the list of statements to run when an error is trapped. The type expression refines the types of errors the Trap catches
Example 1 - trap with break
function break_example {
trap {
"Error trapped"
break
}
1/$null
"Function completed."
} # call the function break_example
output
Error trapped
Attempted to divide by zero.
At line:4 char:7
Example 2 - trap with continue
function continue_example {
trap {
"Error trapped"
continue
}
1/$null
"Function completed."
} # call the function
continue_example
These variabls store state information for Powershell. These variables are created and maintained by PowerShell. More info here
Variable
Contains
$$
The last token in the last line received by the session
$?
Execution status of the last command
$^
First token in the last line received by the sesion
$_
The current obtain in the pipeline obtain. Same as $PSItem
$args
An array of values for undeclared parameters that are passed to a function, script of script block
$ConsoleFileName
Path of the console file (.psc1) that was most recently used in the session
$Error
An array of error objects representing the most recent errors. The most recent error is $Error[0]
$Event
PSEventArgs object that represents the event that is being processed
$EventArgs
An object that represents the first event argument that derives from EventArgs of the event that is being processed
$EventSubscriber
PSEventSubscriber object that represents the event subscriber of the event that is being processed
$ExecutionContext
an EngineIntrinsics object that represents the execution context of the PowerShell host
$false
False. Variable to represent the value of False
$foreach
the enumerator (not the resulting values) of a ForEach loop. The $ForEach variable exists only while the ForEach loop is running; it's deleted after the loop is completed
$HOME
full path of the user's home directory
$Host
an object that represents the current host application for PowerShell
$input
an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions
$LastExitCode
hash table of any string values that were matched by the -match or -notmatch operator. The $Matches hash table can also be populated with captures when you use regular expressions with the -match operator.
$Matches
information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command
$MyInvocation
Information about the current command, such as the name, parameters, parameter values, how the command was started, etc
$NestedPromptLevel
The current prompt level. 0 indicates the original prompt level. value is incremented when you enter a nested level and decremented when you exit
$null
Contains a null or empty value
$PID
The process identifier of the process that is hosting the current PowerShell session
$PROFILE
Full path of the PowerShell profile for the current user and the current host application
$PSBoundParameters
Dictionary of the parameters that are passed to a script or function and their current values. The variable has a value only in a scope where parameters are declared e.g. a script or function.
$PSCmdlet
Object that represents the cmdlet or advanced function that's being run
$PSCommandPath
Full path and file name of the script thats being run
$PSCulture
The name of the culture currently in use in the operating system. The culture determines the display format of items such as numbers, currency, and dates.
$PSDebugContext
Information about the debugging environment.
$PSHOME
The full path of the installation directory for PowerShell
$PSItem
Same as $_. The current object in the pipeline object. Can use this variable to perform an action on every object or on selected objects in a pipeline
$PSScriptRoot
The directory from which a script is being run
$PSSenderInfo
Information about the user who started the PSSession.
$PSUICulture
The name of the user interface culture that's currently in use in the OS.
$PSVersionTable
Read only hash table of details about the version of the PowerShell running in the current session
$PWD
A path object that represents the current dir.
$Sender
Object that generated this event. The variable is populated only within the Action block of an event registration command
$ShellId
Identifier of the current shell
$StackTrace
Stack trace for the most recent error
$switch
Enumerator of the switch statement. Exists only while the switch statement is running.
$this
defines the script property or method. refers to the object that is being extended.