【问题标题】:Two variables in one loop [duplicate]一个循环中有两个变量[重复]
【发布时间】:2017-02-27 21:19:05
【问题描述】:

我目前正在编写一个脚本,该脚本应该通过主机名和 ip 查询机器。

$IP = (get-content "C:\Users\me\Desktop\PowerShell\ips.txt")
$hostname = (get-content "C:\Users\me\Desktop\PowerShell\hostnames.txt")

现在我需要将$IP$hostname 插入到一个字符串中。

write-host "This is my $IP, this is my $hostname"

到目前为止,我尝试使用 for 循环并在每个循环中递增 I,但不是只从我的 txt 文件中插入一个,而是全部插入。

for ($i=0; $i -lt 1; $i++ )

我怎样才能使我的循环从一个文件中获取一行,从另一个文件中获取一行?

【问题讨论】:

  • 这个问题做得更多,但你要找的设置是一样的。

标签: loops powershell foreach powershell-5.0


【解决方案1】:

假设$IP是一个与$hostname长度相同的IP数组:

$IP = (get-content "C:\Users\me\Desktop\PowerShell\ips.txt")
$hostname = (get-content "C:\Users\me\Desktop\PowerShell\hostnames.txt")

for ($i=0; $i -lt $IP.Length; $i++ )
{
    write-host "This is my $($IP[$i]), this is my $($hostname[$i])"
}

Get-Content cmdlet 返回一个字符串数组,因此您必须通过 index 访问当前行。 注意:您还必须使用 子表达式 使用 $() 来插入字符串。

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2013-10-12
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多