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
How are true, false and null represented in PS?
$true
$false
$NULL
What is the built in variable for getting the current directory?
$pwd
Print Working Directory
What is the built in variable for getting the user’s home directory
$Home
How can we view info about a users scripting environment?
$Host
How can we view the current process id?
$PID
How do we get the current version of powershell?
$PSVersionTable
How is the “current item” represented in PS?
$_
How do you explcitly create a new variable in PS?
New-Variable -Name varName -Value varValue
Note that you don’t use the $ at the beginning of the variable name
Once a variable is created can you create it again with New-Variable?
No, you have to use Set-Variable instead
E.g.
Set-Variable -Name varName -Value varValue
How do you explicitly get the value of a variable?
Get-Variable varName -valueonly
Again, no $ at the beginning of the variable name.
Calling Get-Variable varName without the -valueonly switch returns?
A table with the variable name and the value.
How do you get all variables?
Get-Variable
How can we clear the value of a variable?
Clear-Variable -Name varName
How do we totally get rid of a variable?
Remove-Variable -Name varName