Search code examples
arrayspowershellstring-conversion

How dow I stringify an array without spaces between its elements?


$readFile = get-content $readInput

#create an empty array to be filled with bank account numbers
$fNameArray = @()

for($i = 0; $i -lt $readFile.length; $i++){

    #assigns a random letter from the list to $letter.
    #$letter = get-random -inputobject ("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z") -count $readFile.length 
    $letter = $readFile[$i] | foreach-object{get-random -inputobject ("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z") -count $readFile[$i].length}

    $fnameArray += "$letter"
}
$fnameArray

the code is reading in a file that has a list of names and randomizing the letters for Data Masking. The only problem I am running into is the output is like such:

L R Y E B
R O M I
U Q N G R
H K Y
M G A W Q
J G W Y D K T
X E Q
J Y P I G

It looks like it is output with spaces between the letters. How do I eliminate them?


Solution

  • The unary form of the -join operator joins (concatenates) all array elements without a separator.

    > -join ('a', 'b', 'c')
    abc
    

    Therefore, simply use:

    $fnameArray += -join $letter
    

    By contrast, "$letter" stringifies the array using $OFS (the output field separator) as the separator, which defaults to a space, which explains your output.

    Therefore, you could alternatively set $OFS to '' (the empty string) and use "$letter". However, the -join approach is simpler and doesn't require you to create a local scope for / restore the previous $OFS value.