Write-PluralString

Ok, this one is perhaps a little silly, but have you ever struggled with writing output involving an integer with an unknown value together with some text? Don’t know what I’m talking about? I don’t blame you!

I mean this kind of output:

1 file processed
2 files processed
0 files processed
125 files processed

The easy way out would be to write something like this:

Write-Output "$int files processed"

This would mean that for int = 1, the output will be “1 files processed”, but hey – who cares right? I have tried using an if-statement to get the desired result, and while it works, the code don’t look pretty.

So I thought I’d take the time to write a proper function for this. I decided to write a full advanced function, which means that it might feel a bit bloated, but luckily copy/paste don’t care about number of lines.

Anyway, here is the code:


function Write-PluralString{
<#
.SYNOPSIS
Write string with built-in handling of plural-s for variable integer.
.DESCRIPTION
Write string with built-in handling of plural-s for variable integer.
.EXAMPLE
Write-PluralString "$($computer): " $num 'file' 'processed'
.EXAMPLE
Write-Verbose (Write-PluralString "$($computer): " $num 'file' 'processed')
.EXAMPLE
Write-PluralString '' $num 'file' $processed
Omitting the PreString
.NOTES
Name: Write-PluralString
Author: Øyvind Kallstad
Created: 18.08.2014
Version: 1.0
#>
[CmdletBinding()]
param (
# Define a starting string.
[Parameter(Position = 0, Mandatory = $false)]
[string]$PreString,
# Integer that will be used as part of the string, and will decide if the StringPart should include the plural-s or not.
[Parameter(Position = 1, Mandatory = $true)]
[int]$IntPart,
# String that will display with or without 's' based on value of the integer before it
[Parameter(Position = 2, Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$StringPart,
# Define a string to display at the end.
[Parameter(Position = 3, Mandatory = $false)]
[string]$PostString
)
Write-Output "$(@{$false="$($PreString) "}[[System.String]::IsNullOrWhiteSpace($PreString)])$($IntPart) $(@{$true = $StringPart; $false = "$($StringPart)s"}[$IntPart -eq 1]) $($PostString)"
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s