Skip to content

Commit

Permalink
Create ShortenString.ps1
Browse files Browse the repository at this point in the history
  • Loading branch information
ninmonkey committed Dec 25, 2023
1 parent 2678054 commit 6f34ef3
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Pwsh/Formatting/ShortenString.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
function testShortenStr {
<#
.NOTES
Silly. I didn't realize -Process will *always* run even without a pipeline
#>
[OutputType('String')]
[CmdletBinding()]
param(
# Text to format
[Alias('Text', 'String')]
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[AllowEmptyString()]
[AllowNull()]
[string[]]$InputObject,
[int]$maxLength = 80
)
begin {
function truncateString {
[outputType('String')]
param( [string]$Text, [int]$maxLength )
if($null -eq $Text -or $Text.Length -eq 0) { return '' }
[int]$selectedCount = [math]::Clamp(
<# value #> $maxLength, <# min #> 0, <# max #> $Text.Length )
return $Text.SubString(0, $selectedCount )
}
}
process {
if($MyInvocation.ExpectingInput ) {
foreach($item in $InputObject) {
truncateString -Text $item -maxLength $maxLength
}
}
}
end {
if(-not $MyInvocation.ExpectingInput ) {
foreach($item in $InputObject) {
truncateString -Text $item -maxLength $maxLength
}
}
}
}

0 comments on commit 6f34ef3

Please sign in to comment.