Powershell Code Snippits and Commands

in #powershell7 years ago

Powershell Code Snippits and Commands


Conditional or Comparison Operators


OperatorDefinition
## The hash key is for comments
+Add
-Subtract
*Multiply
/Divide
%Modulus (Some call it Modulo) - Means remainder 17 % 5 = 2 Remainder
=equal
-notlogical not equal
!logical not equal
-bandbinary and
-borbinary or
-bnotbinary not
-replaceReplace (e.g. "abcde" –replace "b","B") (case insensitive)
-ireplaceCase-insensitive replace (e.g. "abcde" –ireplace "B","3")
-creplaceCase-sensitive replace (e.g. "abcde" –creplace "B","3")
-andAND (e.g. ($a -ge 5 -AND $a -le 15) )
-orOR (e.g. ($a –eq "A" –OR $a –eq "B") )
-isIS type (e.g. $a -is [int] )
-isnotIS not type (e.g. $a -isnot [int] )
-asconvert 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)
-FFormat operator (e.g. foreach ($p in Get-Process) { "{0,-15} has {1,6} handles" –F$p.processname,$p.Handlecount } )
-ltLess than
-leLess than or equal to
-gtGreater than
-geGreater than or equal to
-eqEqual to
-neNot Equal to
-containsDetermine elements in a group. (This always returns Boolean $True or $False)
-notcontainsDetermine excluded elements in a group (This always returns Boolean $True or $False)
-likeLike - uses wildcards for pattern matching
-notlikeNot Like - uses wildcards for pattern matching
-matchMatch - uses regular expressions for pattern matching
-notmatchNot Match - uses regular expressions for pattern matching
-bandBitwise AND
-borBitwise OR
-isIs of Type
-isnotIs not of Type
ifIf condition
elseIfElseIF
elseElse
>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