Skip to content

Instantly share code, notes, and snippets.

@jaredhaight
Last active November 7, 2018 14:17
Show Gist options
  • Save jaredhaight/f7961133c272143fa5e01c563ffe8723 to your computer and use it in GitHub Desktop.
Save jaredhaight/f7961133c272143fa5e01c563ffe8723 to your computer and use it in GitHub Desktop.
PowerShell script to split a string into arbitrary sizes, formatting the string for use in C# or PowerShell
function Split-String {
param (
[Parameter(Mandatory = $true)]
[string]$String,
[int]$MinLength = 50,
[int]$MaxLength = 120,
[string]$VariableName = "data",
[ValidateSet("PowerShell", "CSharp")]
$Format = "PowerShell"
)
$index = 0
$length = $String.length
if ($Format -eq "CSharp") {
Write-Output "string $VariableName = `"`";"
}
while ($index -lt $length) {
$substringSize = Get-Random -Minimum $MinLength -Maximum $MaxLength
if (($index $substringSize) -gt $length) {
$substringSize = $length - $index
}
$subString = $string.substring($index, $substringSize)
if ($Format -eq "PowerShell") {
Write-Output "`$$VariableName = `"$subString`""
}
if ($Format -eq "CSharp") {
Write-Output "$VariableName = `"$subString`";"
}
$index = $substringSize
}
}
@jaredhaight
Copy link
Author

Example Output:

PS> Split-String -String $example -MinLength 20 -MaxLength 75 -VariableName 'demo'
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
$demo  = "aaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
$demo  = "bbbbbbbbbbbbbbbbbbbbbbbbbb"
$demo  = "bb"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment