【问题标题】:PowerShell. Add +1 Digit For Each Object电源外壳。为每个对象添加 +1 位
【发布时间】:2020-03-12 22:27:50
【问题描述】:

我有一个存储在 C:\IPs.txt 的 .txt 文件中的 IP 列表

10.0.0.0
100.0.0.0

以及为该文件中的每个条目执行命令的 PowerShell 脚本。

Get-Content C:\IPs.txt |ForEach-Object { Write-Host 1 - $_ }

所以该命令返回

1 - 10.0.0.0
1 - 100.0.0.0

如何将 +1 添加到数字,以便 PowerShell 命令返回:

1 - 10.0.0.0
2 - 100.0.0.0

【问题讨论】:

  • 顺便说一句:Write-Host is typically the wrong tool to use,除非意图是仅写入显示器,绕过成功输出流,并且能够将输出发送到其他命令,将其捕获在变量中,将其重定向到文件。要输出一个值,请单独使用它;例如,$value 而不是 Write-Host $value(或使用 Write-Output $value,尽管这很少需要)。另见:stackoverflow.com/a/50416448/45375的底部

标签: powershell


【解决方案1】:

这不是一个单一的班轮,但你可以这样做:

$IPs = Get-Content C:\temp\text.txt #Note this was my test file
$i = 1

foreach($IP in $IPs)
{
    Write-Host "$i - $IP"
    $i ++
}

编辑:作为一个班轮:

Get-Content C:\temp\text.txt | ForEach-Object {$l++; Write-Host "$l - $_" }

【讨论】:

    【解决方案2】:

    这可能会给你想要的输出。

    Get-Content C:\IPs.txt | ForEach-Object { Write-Host "$($_.ReadCount) - $_" }
    

    【讨论】:

      【解决方案3】:

      与 -f 运算符有关的东西:

      get-content ips.txt | foreach { $i = 1 } { "{0} - {1}" -f $i++, $_ } 
      
      1 - 10.0.0.0
      2 - 100.0.0.0
      

      或者这个,我需要额外的括号让 $i++ 输出一些东西:

      get-content ips.txt | foreach { $i = 1 } { "$(($i++)) - $_" } 
      
      1 - 10.0.0.0
      2 - 100.0.0.0
      

      或者更强大的东西,输出一个对象:

      $i=1; get-content ips.txt | select @{n='index';e={($global:i++)}},
        @{n='address'; e={$_}}
      
      index address
      ----- -------
          1 10.0.0.0
          2 100.0.0.0
      

      【讨论】:

        猜你喜欢
        • 2020-07-27
        • 2013-11-26
        • 2011-02-20
        • 1970-01-01
        • 2012-09-12
        • 1970-01-01
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多