【问题标题】:trying to figure out how to call two variables in an array in powershell试图弄清楚如何在powershell中调用数组中的两个变量
【发布时间】:2013-05-09 18:50:06
【问题描述】:

刚开始学习循环和数组。我了解如何调用数组中的单个变量,即:

$animals = gc "c:\temp\animals.txt"
foreach ($animal in $animals)
{write-host "The"$animal "sleeps tonight."}

我想弄清楚的是如何从两个不同的数组中调用两个不同的变量...即:

$animals = gc "c:\temp\animals.txt"
$colors = gc "c:\temp\colors.txt"

这是我感到困惑的部分。如何调用 foreach 循环来同时循环两个文件?

期望的输出:白狮子今晚睡觉,黑豹今晚睡觉,等等......

【问题讨论】:

    标签: variables loops powershell foreach


    【解决方案1】:

    一种方法是使用数组索引。假设两个文件的行数相同:

    $animals = gc c:\temp\animals.txt
    $colors = gc c:\temp\colors.txt
    
    for($i=0; $i -lt $animals.length; $i++)
    {
        #print first line from animals  
        $animals[$i]
    
        #print first line from colors
        $colors[$i]
    }
    

    【讨论】:

    • 感谢两位的建议。谢伊,看起来 $i 表示文件中的行号。 $i 如何与 $animals.length 相关?另外,是否有关于变量上那个参数“.length”的帮助文件?如何找出它的用途以及字符串值是否还有其他参数?最后一件事,-lt 开关是做什么用的?少于?除此之外,代码完美运行。必须安排它以满足我的需要,但它确实可以完成工作。再次感谢谢伊!
    • 是的,$i 指的是行号。长度是集合(数组)的属性,表示集合中对象的数量。查找对象功能的最佳方法是将其通过管道传送到 Get-Member cmdlet。 -lt 是小于运算符,只要当前行号小于文件中的行数(长度),您就希望 for 语句运行。请记住,我们从 0 开始计数。
    【解决方案2】:

    假设您在 C:\ 中有两个文本文件(条目数相同),您可以编写如下内容 -

    $c = 0
    $animal = Get-Content C:\Animal.txt
    
    Get-Content C:\Color.txt | Foreach-Object{
        Write-Host "The $_ $($animal[$c]) sleeps at night"
        $c++
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 2021-08-27
      • 2011-09-22
      相关资源
      最近更新 更多