Reputation: 35
I've written the following code to build an array with sequential strings. It works like I expect, but I wish it ran quicker. Is there a more efficient way to produce my desired results in PowerShell?
I'm very new to PowerShell and appreciate your coaching.
$MIN = 1
$MAX = 20000
$ARRAY = @()
$PREFIX = "AA"
$startDTM = (Get-Date) # Start time
FOR ($i=$MIN; $i -le $MAX; $i++)
{
If ($i -gt 0 -and $i -lt 10) {
$ARRAY = $ARRAY + ($PREFIX+"00000"+$i)
}
If ($i -gt 9 -and $i -lt 100) {
$ARRAY = $ARRAY + ($PREFIX+"0000"+$i)
}
If ($i -gt 99 -and $i -lt 1000) {
$ARRAY = $ARRAY + ($PREFIX+"000"+$i)
}
If ($i -gt 999 -and $i -lt 10000) {
$ARRAY = $ARRAY + ($PREFIX+"00"+$i)
}
If ($i -gt 9999 -and $i -lt 100000) {
$ARRAY = $ARRAY + ($PREFIX+"0"+$i)
}
If ($i -gt 99999 -and $i -lt 1000000) {
$ARRAY = $ARRAY + ($PREFIX+$i)
}
}
$endDTM = (Get-Date) #End Time
"Elapsed Time: $(($endDTM-$startDTM).totalseconds) seconds"
$ARRAY.count #How many loaded.
Example of $ARRAY
:
AA000001
AA000002
...
AA019999
AA020000
Upvotes: 2
Views: 147
Reputation: 58931
The following one-liner tooked 0.4911672 seconds (your example 12.9638944 seonds). Results are the same. It uses the format string with decimal specifier to ensure there are 6 digits and just store the result in the array:
$MIN = 1
$MAX = 20000
$PREFIX = "AA"
$ARRAY = $MIN .. $MAX | % { "$PREFIX{0:D6}" -f $_ }
You can further improove the performance by using a while loop (thanks 4c74356b41 for mentioning that):
# ....
$array = while ($MIN -le $MAX)
{
"$PREFIX{0:D6}" -f $MIN++
}
This tooked 0.0970327 seconds on my computer.
Upvotes: 2