PowerShell executes despite ‘syntax errors’

It came to my attention yet again how easily String.Split and the -split operator can cause confusing behavior, and I realized this is only because PowerShell allows and executes String.Split with a string argument whereas C# has compiler error.

The reason for this not obvious for beginners; PowerShell automatically iterates through arrays.

Examples include:

Piping an array to Get-Member gives distinct object types in the array, not the array type itself.


Automatically enumerates the array and outputs the Name property of each DirectoryInfo and FileInfo object.

This an important feature that produces unexpected behavior in this particular case:

The string argument to String.Split is automatically enumerated as a char array, so while it may seem like PowerShell allows you to split strings on a whole word, it actually splits on each individual character in the string argument.

submitted by /u/skuchoochum
[link] [comments]

Leave a Reply