Categories
Development Powershell Tutorials

PowerShell – What’s your type

It can be hard knowing what your type is but lets try to figure it out in this PowerShell tutorial about TYPES.

You can actually get pretty far with PowerShell without having to think much about types but it is handy to know a bit about them and how to utilize their properties and methods to improve your scripts.

Since PowerShell is very good at guessing the type we don’t always have to define it, but we can do so by prefixing the variable with the type name enclosed in square brackets.

We’ll begin with looking at some of the most common types that you most likely have already used, maybe without knowing the difference.

Integer

Integer (INT) comes in a few different sizes depending on how large a number you need stored.
A integer can only store numbers and nothing else.
When assigning a integer variable with a value, you do not use quotation marks.

# 64 bit integer
[int64]::MaxValue
9223372036854775807

[int64]::MinValue
-9223372036854775808

# Default integer which is 32 bit, [int32]
[int]::MaxValue
2147483647

[int32]::MinValue
-2147483648

# 16 bit integer
[int16]::MaxValue
32767

[int16]::MinValue
-32768

# Assigning a variable with a integer value
$myInt = 1337

String

Next up is string which is text and yes the text can contain numbers 😉

# Assign a string value to a variable
$myString = "Henlo fren, am string!!1!!1!"

# Use Read-Host to assign a string value to a variable
$name = Read-Host "Please enter your name"

Arrays of a type

We can also let PowerShell know that we want an array of a specific type, which mean a collection of something. Lets look at some examples.

[string[]]$stringsThatStings = "Bees","Wasps","Needles","TheTruth"

[int[]]$numbersForPlumbers = 85,86, 88, 88, 89, 90, 92, 95, 96, 02, 06, 07, 09, 10, 11, 12, 12, 13, 15, 16, 17, 19, 21

We still use the type definition [string] but now we also add an empty square bracket set, [string[]].
To seperate the values we use comma between them.


# These two values are different types, one is a int, the other a string
"1337" # string
1337 # int

# Addition differences between string and integer
"1337" + 3 # 13373

1337 + 3 # 1340

"1337" -as [int] # Also returns an int, but does not throw an error if the string can't be converted

Type Methods

These types also provides us with tools to work with them called methods.
We can call these methods from an object of that type or by using the type definition.
Lets jump into the examples and take a better look at this.

# String formatting
$car = "Corvette C06"
$message = "Did you see the {0} that just drove by?"
[string]::Format($message,$car)

# But I prefer this
"Did you see the $car that just drove by?"

# You can also do
"Did you see the " + $car + " that just drove by?"

# Lets use the stingy stringy again
[string[]]$stringsThatStings = "Bees","Wasps","Needles","TheTruth"

# Now we'll use the Join() method with two arguments, the first is what we want to add between the strings. 
# The second argument is our string array (stingray for short?)
[string]::Join(", ",$stringsThatStings)

# Converts the string representation of a number to an int
[int]::Parse("1337") # This returns an int

[int]::Parse("leet 1337") # This fails, the string to be parsed can only contain numbers "Input string was not in a correct format."
# As a side note, you could use regex to make sure that you only parse numbers
[int]::Parse(("leet 1337" -replace "[^0-9]","")) 
# Basically, replace everything that is NOT a number

First we have a couple of pretty self explanatory examples of building strings that contain variables.
When you add a variable in a string, the value of the variable will be displayed when the code is executed.

Next up is an example of how we can take an array of strings and merging them whilst adding something between them (called a delimiter).
In this example it just a simple comma and space, but it could be anything really, you could write something like: [string]::Join(” = sharp and can hurt a lot. “,$stringsThatStings)

Last example shows the parse method from the integer type which can convert a string representation of a integer to an actual integer.


Something I use quite a lot is checking if a string variable is empty. You might think it would be sufficient to just do If($myString -eq “”) but that will fail from time to time.
Best way I’ve found is to use if([string]::IsNullOrWhiteSpace($myString)).

# Type methods
[string[]]$ideas = "Waffle Truck made of waffles",""," ","Code that works the first time","   "

foreach($idea in $ideas){
    if([string]::IsNullOrWhiteSpace($idea)){
        Write-Host "You should think a bit more about the idea '$idea'"
    }
    else{
        Write-Host "Your idea '$idea' might just work, go for it!"
    }
}

DateTime

This type is used for, you guessed it – transporting wheat to… No wait, I meant dates and time!

Psst! Dont forget to follow along with the examples, and if you type them yourself it’ll be easier to remember!

[datetime]::DaysInMonth(2022,11) # Year, month

# Lets LEAP into some more examples
2000..2022 | foreach{ if([datetime]::DaysInMonth($_, 2) -gt 28){ "$_ was a leap year" } }

[int]$yourBirthYear = Read-Host "Enter your birth year as an int"
if([datetime]::DaysInMonth($yourBirthYear,2) -eq 29){ 
    "You were born during a leap year" 
} 
else{ 
    "You were not born during a leap year" 
}

# Lets improve it
if([datetime]::IsLeapYear($yourBirthYear)){
    "You were born during a leap year" 
} 
else{ 
    "You were not born during a leap year"
}

# Two ways of getting the current date
[datetime]::Now
# Or
Get-Date

$rubbishDateFormat = "Month10:Day5:Year2022"
[datetime]::ParseExact($rubbishDateFormat,"'Month'MM':Day'd':Year'yyyy",$null) | Get-Date -Format "yyyy-MM-dd" # We use both double qoutes (") and single qoutes (') in order to specify what is just a string, and what is the actual data 
# More about time, dates and what the formats mean: https://techmeaway.net/2021/03/21/powershell-how-to-get-a-date/

Boolean

These fellas are simple, they are either true or false.

[bool]$isPowerShellAwesome = $true

# IF our boolean is true
if($isPowerShellAwesome){
    "PowerShell is awesome, you are totally right!"
}
# Else if the boolean is false
else{
    "Sorry but you are wrong, PowerShell is awesome!"
    $isPowerShellAwesome = $true # ;)
}

Bonus

# You will encounter switches when running normal cmdlets 
Stop-Process Notepad -WhatIf 
# You do not need to add any value to a switch. If you use the switch then it use set to $true, else it is $false

# But quite often you'll encounter switches which has been implemented with $true as a default value, and if you just pass the switch again it wont remove that. 
# In order to remove a switch that has default value set to $true, pass the switch with a colon directly after followed by the static variable $false
Stop-Process Notepad -Confirm:$false 



function Write-Stuff{
    param(
        [string]$Text
        ,
        [switch]$Yell
    )
    
    if($PSBoundParameters.ContainsKey("Yell")){
        $Text = $Text.ToUpper()
    }

    Write-Host $Text
}

Write-Stuff "PowerShell rocks!" -Yell

Still loads of things to learn about types and how to best utilize them

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next