Powershell Code Snippits and Commands


Conditional or Comparison Operators


Operator Definition
# # The hash key is for comments
+ Add
- Subtract
* Multiply
/ Divide
% Modulus (Some call it Modulo) - Means remainder 17 % 5 = 2 Remainder
= equal
-not logical not equal
! logical not equal
-band binary and
-bor binary or
-bnot binary not
-replace Replace (e.g. "abcde" –replace "b","B") (case insensitive)
-ireplace Case-insensitive replace (e.g. "abcde" –ireplace "B","3")
-creplace Case-sensitive replace (e.g. "abcde" –creplace "B","3")
-and AND (e.g. ($a -ge 5 -AND $a -le 15) )
-or OR (e.g. ($a –eq "A" –OR $a –eq "B") )
-is IS type (e.g. $a -is [int] )
-isnot IS not type (e.g. $a -isnot [int] )
-as convert to type (e.g. 1 -as [string] treats 1 as a string )
.. Range operator (e.g. foreach ($i in 1..10) {$i } )
& call operator (e.g. $a = "Get-ChildItem" &$a executes Get-ChildItem)
. (space) call operator (e.g. $a = "Get-ChildItem" . $a executes Get-ChildItem in the current scope)
. .Period or .full stop for an objects properties ($CompSys.TotalPhysicalMemory)
-F Format operator (e.g. foreach ($p in Get-Process) { "{0,-15} has {1,6} handles" –F
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not Equal to
-contains Determine elements in a group. (This always returns Boolean $True or $False)
-notcontains Determine excluded elements in a group (This always returns Boolean $True or $False)
-like Like - uses wildcards for pattern matching
-notlike Not Like - uses wildcards for pattern matching
-match Match - uses regular expressions for pattern matching
-notmatch Not Match - uses regular expressions for pattern matching
-band Bitwise AND
-bor Bitwise OR
-is Is of Type
-isnot Is not of Type
if If condition
elseIf ElseIF
else Else
> Redirect, for example, output to text file (Example .\cmdlet > stuff.txt)
>> Same as Redirect except it appends to an existing file


Creating HTML Output

Get-Service | Select-object Status, Name, DisplayName | ConvertTo-HTML | Out-File C:\ServiceReport.htm


Formatting HTML Output

$HTM = "<style>table {font-size: 10pt; font-family: Arial;}"
$HTM = $HTM + "BODY{background-color:White;}"
$HTM = $HTM + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$HTM = $HTM + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:Orange}"
$HTM = $HTM + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:SkyBlue}"
$HTM = $HTM + "</style>"

Get-Service | Select-Object Status, Name, DisplayName | ConvertTo-HTML -head $HTM –body "<Center><H2><I><U>Service Information</U></I></H2>" | Out-File C:\ServiceReport.htm

Invoke-Expression C:\ServiceReport.htm