FormatWrap.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
<#PSScriptInfo
.VERSION 1.0.1 .GUID 80339863-e3c5-4a1c-a995-bc344f339e46 .AUTHOR Anthony J. Raymond .COMPANYNAME .COPYRIGHT (c) 2022 Anthony J. Raymond .TAGS word wrap wordwrap word-wrap string text format .LICENSEURI https://github.com/CodeAJGit/posh/blob/main/LICENSE .PROJECTURI https://github.com/CodeAJGit/posh .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES 20220307-AJR: v1.0.0 - Initial Release 20220314-AJR: v1.0.1 - Removed Hyphen from Naming .PRIVATEDATA #> <# .DESCRIPTION Formats the output as a text wrapping string. .PARAMETER InputObject Specifies the objects to be formatted. .PARAMETER Width Specifies the number of characters in the display. .PARAMETER AutoSize Adjusts the number of characters based on the width of the display. .PARAMETER Collapse Removes duplicate instances of white-space characters from the output. #> function Format-Wrap { [CmdletBinding( DefaultParameterSetName = "Width" )] [OutputType([object])] ## PARAMETERS ############################################################# param ( [Parameter( Position = 0, Mandatory, ValueFromPipeline )] [object] $InputObject, [Parameter( ParameterSetName = "Width" )] [ValidateRange(1, [int]::MaxValue)] [int] $Width = 128, [Parameter( ParameterSetName = "AutoSize" )] [switch] $AutoSize, [Parameter()] [ValidateSet( "None", "NewLine", "Space", "TabToSpace", "SpaceTab", "All" )] [string] $Collapse = "None" ) ## EXECUTION ############################################################## Process { foreach ($Object in $InputObject) { $br = [System.Environment]::NewLine if ($AutoSize) { $Width = $Host.UI.RawUI.WindowSize.Width } $String = switch ($Collapse) { default {[string]$Object} "NewLine" {[string]$Object -replace "(\r?\n)+", "$br"} "Space" {[string]$Object -replace "\ +", " "} "TabToSpace" {[string]$Object -replace "\t", " "} "SpaceTab" {[string]$Object -replace "[^\S\r\n]+", " "} "All" {[string]$Object -replace "\s+", " "} } # regex based on answer from user557597 (anonymous) # https://stackoverflow.com/a/20434776 ($String -replace "((?>.{1,$Width}(?:(?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|-|$|[^\S\r\n]))|.{1,$Width})", "`$1$br").TrimEnd($br) } } ## CLEAN UP ############################################################### End { $null = [System.GC]::GetTotalMemory($true) } } Set-Alias -Name Wrap -Value Format-Wrap Export-ModuleMember -Function Format-Wrap -Alias Wrap |