首页 > 解决方案 > Powershell foreach 循环遍历从用户输入中拆分出来的列表

问题描述

我在这里有这个循环:

$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)
        
    }

所以它会从 1 到 99 循环遍历 PC,但我现在需要的是循环遍历用户输入的数字列表

我正在尝试使用 foreach 循环来做到这一点,但它不像 for 循环中的那样对我有用:

$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)

    }

如何创建一个获取 $userInput 的 foreach 循环,将其拆分为 $numberList,然后按照上面显示的方式循环 $numberList 中的每个数字。我非常感谢您一如既往的帮助!

标签: powershellforeachstring-formatting

解决方案


主要问题是您将格式 ( d5) 应用于用于整数类型的字符串。您可以简单地转换为[int]以获得所需的结果。

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将数据读取为[string]. 如果该数据出于某种原因需要为不同的类型,则无论是隐式还是显式,都需要进行转换。


推荐阅读