一个循环中有两个变量

时间:2016-10-18 14:28:42

标签: loops powershell foreach powershell-v5.0

我目前正在开发一个脚本,该脚本应该通过hostname和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++ )

如何实现我的循环从一个文件中获取一行而从另一个文件中获取一行?

1 个答案:

答案 0 :(得分:2)

假设$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 访问当前行。 注意:您还必须使用$()来使用子表达式来插入字符串。

相关问题