powershell - 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 中的每个数字。我非常感谢您一如既往的帮助!
解决方案
主要问题是您将格式 ( 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]
. 如果该数据出于某种原因需要为不同的类型,则无论是隐式还是显式,都需要进行转换。
推荐阅读
- javascript - 被视为外部 URL 的子域
- java - 错误:包 org.apache.commons.math.distribution 不存在
- html - 将表单呈现为继承的 html 将我带到基本 html 页面
- neural-network - 如何在神经网络中应用多项式函数?
- python - 从桌面子文件夹中读取 XLSX 数据
- node.js - 在sequelize findAll中重命名列
- python - 您如何删除条形图中的条形之间的空格,以便绘制值为零?
- entity-framework-core - EF Core Power Tools 不保留标识列名称
- visual-studio - 使用 VisualStudio 2015 安装服务结构 SDK
- powershell - Powershell 选择字符串