Search code examples
powershellforeachstring-formatting

Powershell foreach loop through a list that is split from user input


I have this here for loop:

$fromInput = 1
$toInput = 99

for ($i = $fromInput; $i -le $toInput; $i++) {
            
    $destinationDir = '\\pc' + '{0:d5}' -f @($i) + "\$shareName\$dupDir"
    $netUseDir = '\\pc' + '{0:d5}' -f @($i) + "\$shareName"
    $passObj = 'pass@' + '{0:d3}' -f @($i)
        
    }

So it would loop through PC's from 1 to 99 but what I need now is to loop through a list of numbers that User inputs that are split

I am trying to do that with a foreach loop but it is not working for me like the one in the for loop:

$userInput = Read-Host "Input numbers divided by a comma [", "]"
$numberList = $userInput.split(", ")

foreach ($i in $numberList) {

    $destinationDir = '\\pc' + '{0:d5}' -f @($i) + "\$shareName\$dupDir"
    $netUseDir = '\\pc' + '{0:d5}' -f @($i) + "\$shareName"
    $passObj = 'pass@' + '{0:d3}' -f @($i)

    }

How do I make a foreach loop that takes the $userInput, splits it into $numberList and then loops for each of the numbers in the $numberList the way it is shown above. I much appreciate your help as always!


Solution

  • The main issue is that you are applying formatting (d5) to a string that is intended for an integer type. You can simply cast to [int] to get the desired result.

    foreach ($i in $numberList) {
    
        $destinationDir = '\\pc' + '{0:d5}' -f [int]$i + "\$shareName\$dupDir"
        $netUseDir = '\\pc' + '{0:d5}' -f [int]$i + "\$shareName"
        $passObj = 'pass@' + '{0:d3}' -f [int]$i
    
        }
    

    Read-Host reads data as a [string]. If that data needs to be a different type for whatever reason, a conversion will be needed whether that be implicit or explicit.