0
0
PowerShellscripting~5 mins

Type casting in PowerShell

Choose your learning style9 modes available
Introduction

Type casting changes a value from one type to another. It helps PowerShell understand how to treat the data.

When you get input as text but need a number to do math.
When you want to convert a number to text to show it nicely.
When you want to make sure a value is treated as a specific type before using it.
When reading data from files or user input that is always text but you need other types.
When you want to force PowerShell to store a value in a smaller or different type.
Syntax
PowerShell
[Type]$variable = ([Type])$value
Use square brackets [ ] to specify the type you want.
Put the value in parentheses ( ) to convert it.
Examples
This converts the string "123" to an integer number 123.
PowerShell
[int]$number = [int]("123")
This converts the number 456 to the string "456".
PowerShell
[string]$text = [string](456)
This converts the number 0 to the boolean value False.
PowerShell
[bool]$flag = [bool](0)
Sample Program

This script shows how to convert a string to an integer, then back to a string, and also how to convert a number to a boolean.

PowerShell
$inputString = "100"
[int]$number = [int]$inputString
[string]$text = [string]$number
[bool]$flag = [bool](0)

Write-Output "Original string: $inputString"
Write-Output "After casting to int: $number"
Write-Output "After casting back to string: $text"
Write-Output "Casting 0 to bool: $flag"
OutputSuccess
Important Notes

Type casting only changes how PowerShell treats the value, it does not change the original data source.

If the value cannot be converted, PowerShell will give an error.

Common types are int, string, bool, double, datetime, and more.

Summary

Type casting changes data from one type to another in PowerShell.

Use [Type](value) to convert values safely.

It helps when you need specific data types for calculations or display.