Public/Get-LeadingSpaceCount.ps1
|
<# .SYNOPSIS Returns the number of leading whitespace characters (spaces or tabs) in a string. .DESCRIPTION Get-LeadingSpaceCount matches spaces and tabs at the beginning of the input string and returns the length of that match. Useful for indentation detection, alignment checks, or when normalizing or comparing indentation in scripts or config files. .PARAMETER InputString The string to inspect. Leading spaces and tabs are counted; the count stops at the first character that is not a space or tab. .EXAMPLE Get-LeadingSpaceCount -InputString ' four spaces' Returns 4. .EXAMPLE ' two' | Get-LeadingSpaceCount Returns 2 when the string is piped. .INPUTS System.String. A string whose leading whitespace length is to be measured. .OUTPUTS System.Int32. The number of leading whitespace characters (0 or positive). .NOTES Author: TheCodeSaiyan Uses [regex]::Match; not compatible with Constrained Language Mode if that restricts the Regex type. #> function Get-LeadingSpaceCount { [CmdletBinding()] [OutputType([int])] param ( [Parameter(ValueFromPipeline = $true)] [AllowEmptyString()] [AllowNull()] [string]$InputString ) begin { $TelemetryArgs = @{ ModuleName = $MyInvocation.MyCommand.Module.Name ModuleVersion = [string]$MyInvocation.MyCommand.Module.Version CommandName = $MyInvocation.MyCommand.Name ExecutionID = [guid]::NewGuid().ToString() } Invoke-TelemetryCollection @TelemetryArgs -Stage Start -ClearTimer $TelemetryFailed = $false } process { try { if ([string]::IsNullOrEmpty($InputString)) { return 0 } # Match leading spaces and tabs only (a leading line break is not indentation) [regex]::Match($InputString, '^[ \t]*').Length } catch { if (-not $TelemetryFailed) { $TelemetryFailed = $true Invoke-TelemetryCollection @TelemetryArgs -Stage End -Failed $true -Exception $_ } throw } } end { if (-not $TelemetryFailed) { Invoke-TelemetryCollection @TelemetryArgs -Stage End } } } |