PoshCode Archive  Artifact [d0d5ba72ec]

Artifact d0d5ba72ec72e11a739e0484b356b83a81727b87b95769b558af91988f052f93:

  • File Split-ByLength.ps1 — part of check-in [8f4cf5804b] at 2018-06-10 13:38:18 on branch trunk — http://stackoverflow.com/questions/17171531/powershell-string-to-array/17173367#17173367 (user: Dang_it_Bobby size: 1596)

# encoding: ascii
# api: powershell
# title: Split-ByLength
# description: http://stackoverflow.com/questions/17171531/powershell-string-to-array/17173367#17173367
# version: 0.1
# type: function
# author: Dang_it_Bobby
# license: CC0
# function: Split-ByLength
# x-poshcode-id: 4205
# x-archived: 2016-08-27T11:17:48
# x-published: 2013-06-18T17:02:00
#
#
function Split-ByLength{
    <#
    .SYNOPSIS
    Splits string up by Split length.

    .DESCRIPTION
    Convert a string with a varying length of characters to an array formatted to a specific number of characters per item.

    .EXAMPLE
    Split-ByLength '012345678901234567890123456789123' -Split 10

    0123456789
    0123456789
    0123456789
    123

    .LINK
    http://stackoverflow.com/questions/17171531/powershell-string-to-array/17173367#17173367
    #>

    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$InputObject,

        [int]$Split=10
    )
    begin{}
    process{
        foreach($string in $InputObject){
            $len = $string.Length

            $repeat=[Math]::Floor($len/$Split)

            for($i=0;$i-lt$repeat;$i++){
                #Write-Output ($string[($i*$Split)..($i*$Split+$Split-1)])
                Write-Output $string.Substring($i*$Split,$Split)
            }
            if($remainder=$len%$split){
                #Write-Output ($string[($len-$remainder)..($len-1)])
                Write-Output $string.Substring($len-$remainder)
            }
        }        
    }
    end{}
}