Posted On October 12, 2022

PowerShell: How to Convert Multi-Line Texts Into an Array of Strings

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: How to Convert Multi-Line Texts Into an Array of Strings

Significance: we often run into situations where a list of items (such as usernames, computernames, etc.) that are needed to be actioned within a PowerShell script. Instead of manually creating double quotes around each string, we could quickly paste them into a text file or a text variable signified with the @ symbol as demonstrated below

Example 1:

# Paste a list of names here
# Important: there could spaces on each line
$usersList = @'
username1
username2
username3
'@

$userNames = @($usersList -split "`n")|%{$_.Trim()}

Example 2:

# Paste a list of names here
# Important: there must be no spaces nor extra characters between each name
$computersList = @'
computername1
computername2
computername3
'@

$computerNames = @($computersList -split "`n" -replace "\..*$")

Leave a Reply

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

Related Post

PowerShell: removing elements of an immutable “fixed size” array

By default, PowerShell's Array is an object class; hence, its length a "fixed size" as…

Quick & Useful Snippet to Set SSL TLS Protocol of PowerShell

$requiredTls='Tls12' $availableSslProtocols=[enum]::getnames([net.securityprotocoltype]) if([Net.ServicePointManager]::SecurityProtocol -notin $requiredTls -and $requiredTls -in $availableSslProtocols){ [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::$requiredTls }

PowerShell: Activate Remote Windows

$remoteWindows="SHERVER01","SHERVER02"$licenseKey="XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"function activateWindows{ param( [string]$key ) $licensingService = get-wmiObject -query "select * from SoftwareLicensingService" -computername $env:computername;…