powershell - 在 for 循环中填充迭代器

标签 powershell

我尝试使用 PowerShell 将迭代器填充到 for 循环中,但收到错误消息。

正常的填充效果很好:

$mytext = "Test"
Write-Host $mytext.PadLeft(5, "0")
# Output: 0Test

但是使用迭代器不起作用:

for ($i=1; $i -lt 20; $i++) {
  Write-Host $i.PadLeft(2, "0")
}

Method invocation failed because [System.Int32] does not contain a method named 'PadLeft'.

即使我在填充之前将迭代器复制到变量中也不会:

for ($i=1; $i -lt 20; $i++) {
  $Iterator = $i
  Write-Host $Iterator.PadLeft(2, "0")
}

Method invocation failed because [System.Int32] does not contain a method named 'PadLeft'.

for 循环中根本不可能使用 PadLeft() 吗?

最佳答案

这是因为 $i 是一个 integer 并且正如错误消息告诉您的那样,它不包含 PadLeft 方法。无论如何,您可以将整数转换为字符串:

for ($i=1; $i -lt 20; $i++) {
  $Iterator = [string]$i
  Write-Host $Iterator.PadLeft(2, "0")
}

关于powershell - 在 for 循环中填充迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36642981/

相关文章:

powershell - 如何获取在 Excel VBA 中运行的 Powershell 脚本的返回值?

powershell - 导出 CSV 文件中的多个对象 PowerShell

git - Powershell/PoshGit - 'Could not find ssh-agent'

Powershell - 从远程计算机上运行 exe 的 Invoke-Command 捕获输出

windows - Powershell 是否存在语言中立的文件系统对象动词?

powershell - 如何阻止 PowerShell 解压 Enumerable 对象?

Powershell - 无需硬编码密码即可自动连接到 Power BI 服务

powershell - 如何获取使用 Copy-item 复制的文件数

powershell - 如何使用 PowerShell 检查数组元素是否与字符串匹配?

powershell - Test-Netconnection函数输出错误