【发布时间】:2021-07-16 10:00:03
【问题描述】:
我这里有这个 for 循环:
$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 中的每个数字循环。 非常感谢您一如既往的帮助!
【问题讨论】:
-
如果我理解正确,那么您只需将
for更改为foreach -
“但它不像 for 循环中的那样对我有用” - 那么,它是如何工作的?你是唯一能看到你屏幕的人,请不要让我们猜测你的问题是什么:-)
-
好吧,抱歉,忘记提了。它的工作方式是它不会将 0-s 附加到共享名称位置的 conc 中。意思是当用户输入 1, 2, 3... 完整共享名称的 conc 应该是 '\\pc00001\$shareName\$dupDir' 而不是这样: "'\\pc1\$shareName\$dupDir '。在 for 循环中,串联是应该的。
-
我已经修复了
for/foreach问题以防止分心,因为第二个循环的真正问题是 缺少零填充格式化字符串中的数字。
标签: powershell foreach string-formatting