Reputation: 3678
Below is my Powershell script:
$server_file = 'serverlist.txt'
$servers = @{}
Get-Content $server_file | foreach-object -process {$current = $_.split(":"); $servers.add($current[0].trim(), $current[1].trim())}
foreach($server in $servers.keys){
write-host "Deploying $service on $server..." -foregroundcolor green
}
My serverlist.txt
looks like this:
DRAKE : x64 SDT: x64 IMPERIUS : x64 Vwebservice2012 : x64
Every time I run this script, I get IMPERIUS
as my server name. I would like loop through the servers in the order they are written in serverlist.txt
.
Am I missing anything in Get-Content
call?
Upvotes: 0
Views: 56
Reputation: 338336
Don't store servers in a temporary variable.
The iteration order of hashtables (@{}
) is not guaranteed by the .NET framework. Avoid using them if you want to maintain input order.
Simply do:
$server_file = 'serverlist.txt'
Get-Content $server_file | ForEach-Object {
$current = $_.split(":")
$server = $current[0].trim()
$architecture = $current[1].trim()
Write-Host "Deploying $service on $server..." -ForegroundColor Green
}
Note: Even if it probably won't make much of a difference in this particular case, in general you always should explicitly define the file encoding when you use Get-Content
to avoid garbled data. Get-Content
does not have sophisticated auto-detection for file encodings, and the default it uses can always be wrong for your input file.
Upvotes: 3