The more I use PowerShell, the more convinced I am of how important it is to type variables and function parameters. Because of the way PowerShell works, specifying the types helps me avoid unwanted behavior.

For example, given this script:

Set-StrictMode -Version 2

$items = Get-ChildItem
if ($items) {
   $items.Count
}

If I run it in a directory with several files or folders, it will print the number of items. But if I run it in a directory with only one item, the result is a spectacular error saying it has no idea what this Count property is. Just by typing the $items variable, this example would work perfectly:

Set-StrictMode -Version 2

[array]$items = Get-ChildItem
if ($items) {
   $items.Count
}

Another common example I run into is when I have a function that receives the path to a directory. It’s very common to receive a string with the path. The problem is that with network paths this doesn’t work very well, and you have to add the string “filesystem::” in front of the path. Unless we’re interacting with .Net code, in which case it doesn’t like the path with “filesystem::” in front one bit. In the end it’s much easier if I type the parameter as System.IO.DirectoryInfo, FileInfo or whatever is appropriate.