Using Variables in PS Flashcards
All variables start with…
$
Running $varName does what?
Echos the contents to the console.
How can we explicitly write to the host?
Write-Host $var
All variables in PS are…
objects
How can I display the type of the variable?
$myVar.GetType()
How can I display the properties and methods of a variable?
Pipe the variable to Get-Member cmdlet
eg:
$var | Get-Member
So how could I find all the properties and methods from an object returned by Get-ChildItem?
Get-ChildItem | Get-Member
This actually returns a separate list for each member type that is returned. So if you set path to env: the above command will return different values than if it’s looking at a file system drive.
How do you explicitly type a variable
Wrap it in square brackets e.g:
[System.Int32]$myInt = 42
What are the shortcuts for the .NET datatypes
[int] [string] [float] [short] [decimal] [single]
When should we strongly type variables
When it is required by something that we’re working with. Most of the time we just use the dynamic typing
For non-string datatypes, how do we use methods on literal values?
Wrap it in parentheses:
e.g. (33).GetType()
What does wrapping in parentheses on a literal values actually do?
Forces PowerShell to convert it to an object.
How do you specify:
>
=
- gt
- lt
- eq
- ne
- le
- ge
For collections, what operators are available?
- in
- notin
- Like
- NotLike
- Match (matches on regex)
How is implicit type coercion performed in PS?
Whatever value is on the right is converted to the data type on the left. So
42 -eq “042” == $True ..but
“042” -eq 42 == $False