Powershell – Basics 4

lets talk about the variables

# All variables start with a $. Show a simple assignment
$hi = "Hello World"

#Print the Value
$hi

Write-Host $hi

# Show the type
$hi.GetType()

#Types oare mutaple
Clear-Host
$hi = 5
$hi.GetType()

Clear-Host
[System.Int32]$myint = 42 # Can make strongly typed variables
$myint
$myint.GetType()

$myint = "This won't work will raise an exception"

# There are shortcuts for most .net types
clear-host
[int] $myotherint = 42
$myotherint.GetType()

[string] $mystring = "hansy"
$mystring.GetType()

# Others include short, float, decimal, single, bool, byte, etc

(42).GetType() # Not just varibles are types
"Hansy is cool".GetType()

# Accessing methods on objects
"Hansy is Cool".ToUpper()
"Hansy is cool".Contains("is")

# comparisons
$var = 42
$var -gt 40
$var -lt 40
$var -eq 42

# List is
# -eq Equals
# -ne not equal to
# -lt less than
# -gt Greater than
# -le Less than or equal to
# -ge Greater than or equal to

# -Like        Like wildcard pattern matchin
# -NotLike     Not like
# -Match       Matches based on regular expressions
# -NotMatch    Non-matches based on regular expressions

# Calculations are like any other language
$var = 3*11 # Also uses +, -, and /
$var

$var++ # supports unary operators ++ and --
$var

#implicit Type conversions
"43" -eq 42
42 -eq "42"

# Whatever is on the right is converted to the data type on the left
# can lead to some odd conversions
42 -eq "042" # True because the string is converted to int
"042" -eq 42 # False because the int is converted to string


#--------------------------------------------
# Using the *-Variable cndlets
#--------------------------------------------

Clear-Host

#normal variable usage
$normal = 33
$normal

$text = "in the morning"
$text

# Long version of $var = 123
New-variable -Name var -Value 123
$var

#Displays the variable and it's values
Get-Variable var -valueonly

Get-Variable var

Get-Variable # Without Patams it shows all variables

# Assign a new vale to an existing variable
# $var = 789
Set-Variable -Name var -value 789
$var

#clear the contents of a variable
# same as $var = null
Clear-variable -Name var
# After a clear you can still access $var, but it has no value
$var

#Wipe out a varilable
Remove-variable -Name var
# Now var is gone if you try to remove or clear again an error occurs
# (note if you try to access it by just doing a $var the var is recreated)

Get-Variable var # now produces an error

$var # recreates the object


#------------------------------------------
# String Handling
#------------------------------------------

# String Quoting
Clear-Host

"This is a string"
'This is a string too!'

# Mixed Quoted
'I just wanted to say "Hello World", OK?'
"I can't believe how cool powershell is!"

# You can also double quote to get quot3s in strings
"I just wanted to say ""Hello World"", OK?"
'I can''t believe how cool powershell is!'

#Escape sequences - use the backtick `
Clear-host
# backspace `b (have to show in rea window)
"hans`braj"

# newline `n
"Hans`nraj"

# carriage return `r (doesn't really show anything)
"Hans`sraj"

# crlf `r`n
"hans`r`nraj"

# tabs
"hans`traj"


# Here strings for large blocks of text----------------
clear-host
$hertext=@"
Some text here
more here and little
    bit more here

and a blank line above
"@

$hertext

# the @ and quote must be last on starting line then first on ending line
# also works with single quotes

$morehertext =@'
Some more text here
to test with single
   quote
   
 using a blank line too!.
'@
 
 # note how the nexted ' is handled ok, no double quoting needed

 $morehertext
# String interpolation
clear-host
$items = (Get-ChildItem).Count
$loc = Get-Location
"There are $items items are in the folder $loc" 

# To actually display the variable, excape it with a backtick
"There are `$items items are in the folder `$loc."

# String interpolation only works with double quotes
'There are $items items are in the folder $loc '

# It does work with here strings
$hereinterpolation = @"
Items`tFolder
-----`t------------
$items`t$loc

"@

$hereinterpolation

# Can use expressions in strings, need to be wrapped in $()
clear-host
"There are $((Get-ChildItem).COunt) items are in the folder $(Get-Location)."

"The 15% tip of a 33.33 dollar bill is $(33.33 * 0.15) dollars."

#String Formatting -C# like syntax is supported
# In C you'd use:

[string]::Format("There are {0} items.", $items)

#Powershell shortuct
"There are {0} items." -f $items

"There are {0} items in the location {1}." -f $items, $loc

"The 12% tip of a 33.33 dollar bill is {0} dollars" -f (33.33 * 0.12)

"The 12% tip of a 33.33 dollar bill is {0:0.00} dollars" -f (33.33 * 0.12)

#Wildcards
clear-host
"Hansraj" -like "hans*"
"Hansraj" -like "some*"
"Hansraj" -like "?ansraj" # question marks work for single characters
"Hansraj" -like "hans*[a-j]"   # ends in a char berween a and j
"Hansraj" -like "hans*"   # ends in a char between c and s

# Regular expressions
clear-host
"231-334-1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}"  #validdate phone number
"abc-334-1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" #validation fails
"231.334.1254" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" #validation fails


#---------------------------------------
# Arrays
#-----------------------------------------

# Simiple array
clear-host
$array = "some", "code"
$array[0]
$array[1]
$array

$array.GetType()

#Updating arrays
$array = "robert", "Rama"
$array

$array[0] = "roope"
$array[1] = "ssope"

$array

#Formal array creating syntax
$array = @("some", "code")
$array

$array = @() # only way to create an empty array
$array.Count

$array = 1..5 # Can load arrays using numeric range notation
$array

# Check to see if an item exists
clear-host
$numbers = 1, 42, 234
$numbers -contains 42

$numbers -notcontains 99

$numbers -notcontains 234

##

#----------------------------------------
# Hash Tables
#-----------------------------------------

$hash = @{"Key" = "Value";
           "Some" = "Code";
           "mcsft" = "Microsoft"}
$hash           #Displays all values
$hash["mcsft"]  # Get a single value for the key

$hash."mcsft" # Get a single value using object suntax

# You can use variables a keys
$mykey = "Some"
$hash.$mykey      #using variable as a property
$hash.$($mykey)   #Evaluating as an expression
$hash.$("So" + "me")

#Adding and removing values
$hash               #Here's what's there to start
$hash["Top Gear"] = "topgear.com"   # Add value using new key
$hash               #Show the additional row

$hash.Remove("Some")  # Remove by passing the key
$hash

# See if key exists
$hash.Contains("Top Gear")
$hash.Contains("Some")

$hash.ContainsValue("Code")
$hash.ContainsValue("Microsoft")

$hash.Keys
$hash.Values

$hash.Keys -Contains "mcsft"


##########--
### Built in variables
#########----

clear-host
set-location c:\New_folder
#Automatic variables

#False and true
$false
$true
#nUll
$null

# Current directory
$pwd

#Users HOme Direcotory
$home
#Info about a users machine
$host

# Process ID
$PID

#Info about the current version of powershell
$PSVersionTable

$_  # CurrentObject
Get-ChildItem | Where-Object {$_.Name -like "*.ps1"}

2 thoughts on “Powershell – Basics 4

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.