Getting Started

PRACTICE ! PRACTICE ! PRACTICE !

In Powershell, Get-Help, Get-Command, Get-Alias are the most handful commands to ever exist

Aliases are the shorthand notes for the commandlets, it lets to identify the correct commandlet of the specified alias

Get-Alias iex

Operators in Powershell

Basic Math Operations

3 + 3
3 * 4
4 - 3
"Hello" + " World"
"Hello" + 3
3 + "Hello" - Gives Error, as operations in powershell is carried out by priortizing the the left most variable's data type. In this case it tried to convert the "Hello" string into integer but failed !

Assignment Operators

$a = 10
$b = 10
$result = $a + $b
echo $result

$a *= 4         // $a = $a * 4

Comparison Operators

3 -eq 4
3 -ne 4
3 -le 4
"Hello powershell" -match "power"
"Hello powershell" -replace "power","shark"
1 -in (1,2,3)

Redirections

  • Similar to Linux Shell

Get-Location > C:\Temp\loc.txt
Get-Location >> C:\Temp\loc.txt
Get-Process none,explorer 2>&1

Advanced Operators

  • Logical ( -and, -or, -xor -not, !)

  • Split and Join (-split, -join)

  • Type Operators (-is, -isnot, -as)

(1 -le 3) -and (1 -ge 0) = True
(1 -le 3) -or (1 -ge 2)  = True
(1 -eq 1) -xor (2 -eq 2) = False

"Welcome to my home" -split " "
"Wel","Please" -join "come",""

3 -is "int"
"3" -is "string"
0x12 -is "int"
0x12 -is "string"

Types in Powershell

$value = "string" + 1
$value.GetType()

$str1 = "akash"
$str2 = 'akash'
$str1.GetType(),$str2.GetType()

"another string: $str1"        - returns akash
'another string: $str2'        - returns $str2

Type Conversion

$a = 3.2 + 3
$a.GetType()        - Returns Double 

[int]$a = 3.2 + 3
$a.GetType()        - Returns Int32

Arrays

  • Commands in powershell return an array of objects[]

$result = Get-ChildItem
$result.GetType()    - Returns Object[]

$array = 1,2,3,4,5
$array.length
$array[1]
$array[3]

Conditional Statements

if (1 -ge 0) {"One"} else {"Something"}
One

if (1 -ge 3) {"One"} else {"Something"}
Something

if ( ((Get-Process).HandleCount) -ge 40) {"Many processes"} else {"OK"}
Many processes
switch (1) { 1 {"one"} 2 {"two"} default {"Default"}}
one

switch (3) { 1 {"one"} 2 {"two"} default {"Default"}}
Default

Loop Statements

  • while() {}

  • do {} while()

  • do {} until()

  • for(;;) {}

  • foreach(in) {}

$count = 3
while ($count -ge 0)
{
"Iteration $count"
$count--
}
$process = Get-Process
foreach ($i in $process) {
$i.name
$i.path
}
  • ForEach-Object

  • Where-Object

Get-Process | ForEach-Object {$_.name}
Get-ChildItem C:\test | Where-Object ($_.name -match "txt"}

Last updated