2017-04-19 132 views
0
#gets the file location/file name of the IP address 
Param($addr) 
$file = Get-Content $addr 
$i = 0 
while ($i -ne $file.Count) { 
    Write-Host $file 
    $i++ 
} 

输出:PowerShell的循环迭代

 
8.8.8.8 127.0.0.1 208.67.222.222 
8.8.8.8 127.0.0.1 208.67.222.222 
8.8.8.8 127.0.0.1 208.67.222.222 

文件内容:

 
8.8.8.8 
127.0.0.1 
208.67.222.222 

我只希望它遍历并打印出一条线,不是所有的三条线在一行3倍。我需要这个,所以我可以在每个地址上运行一个ping命令。

+2

如果你只想要一条线,那么你应该索引,哪些你是不是目前,在你行'直写主机$文件“。所以简单的_fix_将会是'$ file [$ i]'。但是你可以一起使用不同的循环结构。 'get-content $ addr | Foreach-Object {“用$ _做些事情”} – Matt

+0

这工作,谢谢:) –

回答

0

您必须使用$file上的索引运算符[]

#gets the file location/file name of the IP address 
param($addr) 
$file = get-content $addr 
$i=0 
while ($i -ne $file.count){ 
    write-host $file[i] 
    $i++ 
} 
0

可以使用$ _作为文件排,管这样的:

Param($addr) 
Get-Content $addr | foreach{ $_ } 


#short version 
Param($addr) 
gc $addr | %{ $_ }