Home > front end >  Converting array variable in powershell to a comma delimited list
Converting array variable in powershell to a comma delimited list

Time:11-02

I have a powershell code which retrieves some data from the database, the declared data type is an array.

    @my_data = @()
    
    $x = (invoke-sqlcmd -serverinstance x -database y -Query "select name from first_table")
    $y = (invoke-sqlcmd -serverinstance xx -database yy -Query "select name from second_table")
    $my_data = $x   $y
    $my_data = $my_data | select -unique
    $my_data = "Tom Tim Jo"
    $required_format = "Tom,Tim,Jo"

In the example above, I require the format to be comma delimited, at the moment its space delimited.

The issue is that a function that I am passing $my_data to requires it to be comma delimited.

I have tried to use -join ',' as suggested on other SO pages and examples to no avail, as the variable isn't getting comma delimited.

CodePudding user response:

The .Net method Replace() will work

$my_data.Replace(' ',',')

CodePudding user response:

Try splitting $my_data first.

$required_format = my_data -split " " -join ","
  • Related