Concept Flow - Type casting
Start with a value
Choose target type
Apply cast operator ([type
Value converted to new type
Use converted value in script
Type casting changes a value from one type to another using the cast operator in PowerShell.
[int]$num = "123" Write-Output $num [int]$num2 = 45.67 Write-Output $num2 [string]$text = 100 Write-Output $text
| Step | Expression | Action | Result | Output |
|---|---|---|---|---|
| 1 | [int]"123" | Cast string "123" to int | 123 (int) | 123 |
| 2 | Write-Output $num | Print variable $num | 123 | 123 |
| 3 | [int]45.67 | Cast float 45.67 to int (drops decimal) | 45 (int) | 45 |
| 4 | Write-Output $num2 | Print variable $num2 | 45 | 45 |
| 5 | [string]100 | Cast int 100 to string | "100" (string) | 100 |
| 6 | Write-Output $text | Print variable $text | 100 | 100 |
| 7 | End | No more commands | Script ends |
| Variable | Start | After Step 1 | After Step 3 | After Step 5 | Final |
|---|---|---|---|---|---|
| $num | null | 123 (int) | 123 (int) | 123 (int) | 123 (int) |
| $num2 | null | null | 45 (int) | 45 (int) | 45 (int) |
| $text | null | null | null | "100" (string) | "100" (string) |
[type]value casts value to the specified type. Casting truncates decimals when converting to int. Casting non-numeric strings to int causes errors. Casting int to string converts number to text. Use casting to ensure variables have correct types.