Convert-List2Array.ps1

<#PSScriptInfo
 
.VERSION 1.4
 
.GUID 9f45b1cc-f406-468c-ae9b-20b64ec5d746
 
.AUTHOR Kalichuza
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS "List" "Array" "Convert"
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
Takes a plane-text list and converts it into a powershell array that you can then copy an paste or assign to a variable
 
#>
 

param (
    [string]$VariableName, # Optional variable name
    [string[]]$UserList, # Required list of usernames
    [switch]$AssignToSession  # Flag to assign the variable to the session
)

# Ensure UserList is a proper array and filter out empty values
[array]$CleanUserList = $UserList | Where-Object { ($_ -ne '') -and ($_ -ne $null) } | Select-Object -Unique

# Format array correctly (prevent duplication)
[string]$formattedArray = "@(`n" + (($CleanUserList | ForEach-Object { " '$_'" }) -join ",`n") + "`n)"

# Assign to session variable if requested
if ($AssignToSession -and $VariableName) {
    Set-Variable -Name $VariableName -Value $CleanUserList -Scope Global
}

# Output correctly formatted array without duplication
if ($VariableName) {
    "`$$VariableName = $formattedArray"
}
else {
    $formattedArray
}