Author Posts

November 27, 2017 at 4:31 pm

I'm generating random numbers using get-random. I want to add dashes every 4 numbers. I need some help in how to do this. Thanks.

November 27, 2017 at 4:36 pm

have you written any code to do that yet? Please post

November 27, 2017 at 5:07 pm

#region input
$myInput        = Get-Random
$SplitEvery     = 4
$SplitCharacter = '-'
#endregion

#region process
$myString = [String]$myInput
$i = 1
$myOutput = $myString.ToCharArray() | % { if ($i % $SplitEvery -eq 0) { "$_$SplitCharacter" } else { $_ }; $i++ }
#endregion

#region Output
$myOutput = $myOutput -join ''
#remove trailing SplitCharacter
if ($myOutput[-1] -eq $SplitCharacter) { $myOutput = $myOutput[0..($myOutput.Length-2)] -join ''}
$myOutput
#endregion

If you don't fully comprehend every line above, please ask..

November 27, 2017 at 5:52 pm

So far my code was "Get-Random -count 24". I played around with split and nothing I did worked. I remembered this website after erased everything. Thanks!!!

November 27, 2017 at 6:14 pm

How's this? Replace any 4 characters not at the end of the line.

'12345678911234567890' -replace '(....(?!$))','$1-'

1234-5678-9112-3456-7890

November 27, 2017 at 7:05 pm

That did work. What is going on here '(....(?!$))','$1- ? Where can I get more info? Thanks!!!

November 27, 2017 at 7:07 pm

.... is any 4 characters, () let's me refer to it later as $1, (?!$) means lookahead and match not, ! the end of the line, $. Maybe plug it into http://regex101.com