Output the PowerShell assignment command from an array

This function will take an array and output the PowerShell assignment command with the elements from the array. It would be useful if you want to hardcode a string array and don’t want to manually format it.

The function is below, along with an example usage and example output.

function ArrayAssignment ($MyArray) {
    $ArrayContent = "`$Array = @("
    # Output elements except the last
    $MyArray[0..$($MyArray.Count-2)] | foreach {$ArrayContent += "`"$_`","}
    # Output the last element
    $ArrayContent += "`"$($MyArray[$MyArray.Count-1])`")"
    $ArrayContent
    }

# Create an array of the first 20 services names for an example
$Example = (Get-Service).DisplayName[0..19]

# Use the function
ArrayAssignment $Example

# Example Output:
PS C:\>
$Array = @("Adobe Flash Player Update Service","AllJoyn Router Service","Application Layer Gateway Service","AMD External Events Utility","AMD FUEL Service","Application Identity","Application Information","Apple Mobile Device Service","Application Management","App Readiness","AppX Deployment Service (AppXSVC)","ASP.NET State Service","Windows Audio Endpoint Builder","Windows Audio","ActiveX Installer (AxInstSV)","BitLocker Drive Encryption Service","Base Filtering Engine","Background Intelligent Transfer Service","Bonjour Service","Background Tasks Infrastructure Service")

Leave a Reply

Your email address will not be published. Required fields are marked *