how do i get an array into a comma delimited string with single quotes in powershell

307 Views Asked by At

I have tried all the main PowerShell websites and have not found anything yet can someone please provide a code snippet that takes an array like this: and wree test the and converts it to: 'and','wree','test','the' .

here is some sample code #Define Variables $a = Get-Content 'c:\users\p3110458\PS test.txt'

'"' + $($(get-content 'c:\users\p3110458\PS test.txt' ) -join ',') + '"'

replace function needs to be written to make this code work.

$str_var = 123, 654, 283, 1344 $str_var = $str_var.Replace(" “, “”) $str_var = “’” + $str_var.Replace(”,", “’,’”) + “’” #--------------------------------------------------------------------

$a -join ","
$a -join "''"

$b = get-content $a

#Define Functions function append-text { process{ foreach-object {"'" + $_ + ",'"} } }

#Process Code $b | append-text

1

There are 1 best solutions below

1
mklement0 On

I assume you're looking for something like this:

123, 654, 283, 1344 -replace '^|$', "'" -join ','

Output (a single string):

'123','654','283','1344'

The above uses the regex-based -replace operator to effectively enclose each (stringified) array element in '...', and then -joins the resulting strings with ,

Regex '^|$' matches both the start (^) and the end ($) position of each element, and replacing them with verbatim ' effectively places a ' before and after each element.