Powershell foreach 循环遍历从用户输入拆分的列表

问题描述

在这里有这个 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)

    }

我如何制作一个 foreach 循环,它接受 $userInput,将其拆分为 $numberList,然后按照上面显示的方式对 $numberList 中的每个数字进行循环。 我一如既往地感谢您的帮助!

解决方法

主要问题是您将格式 (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]。如果该数据出于某种原因需要采用不同的类型,则需要进行隐式或显式转换。

,

首先,对于用户输入,我建议您使用以下内容:

$userInput = Read-Host "Input numbers divided by a comma [","]"
try
{
    [int[]]$numberList = $userInput.split(',')
}
catch
{
    'Input only numbers separated by commas.'
    break
}

要解释为什么 [int[]] 存在以及为什么 try {...} catch {...} 语句:

我们正在尝试将 string 转换为 array,并将结果元素转换为 int。因此,我们应该得到一个整数数组,如果不是这种情况,这意味着如果用户输入的内容与逗号分隔的数字不同,我们将得到一个错误,该错误由 catch 块捕获和处理.

在这种情况下,需要通过向您展示一个简单的示例将字符串转换为整数:

PS /> '{0:d5}' -f '1' # String formatting on a string
1

PS /> '{0:d5}' -f 1 # String formatting on an integer
00001

现在进行循环,这里是我看到的 3 个简单的替代方案:

  • 使用 for 循环:
for($i=$numberList[0];$i -le $numberList.Count;$i++)
{
    $destinationDir = "\\pc{0:d5}\$shareName\$dupDir" -f $i
    $netUseDir = "\\pc{0:d5}\$shareName" -f $i
    $passObj = 'pass@{0:d3}' -f $i
}
  • 使用 foreach 循环:
foreach($i in $numberList)
{
    $destinationDir = "\\pc{0:d5}\$shareName\$dupDir" -f $i
    $netUseDir = "\\pc{0:d5}\$shareName" -f $i
    $passObj = 'pass@{0:d3}' -f $i
}
  • 使用 ForEach-Object 循环:
$numberList | ForEach-Object {
    $destinationDir = "\\pc{0:d5}\$shareName\$dupDir" -f $_
    $netUseDir = "\\pc{0:d5}\$shareName" -f $_
    $passObj = 'pass@{0:d3}' -f $_
}