首页 > 解决方案 > 同一文件中的不同结果(Powershell)

问题描述

我有这个脚本,它获取 IP 地址并 ping 它们,然后将结果保存到 TXT 文件或 EXCEL 文件。

问题是 - > 如果我将更改名称输出名称文件,甚至更改原始(或新)文件的 IP 地址,我将获得包含所有先前测试连接的最终文件。

剧本 :

$IPs = Get-Content "C:\IPs.txt"

foreach($name in $Ips){
    if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name is up" -ForegroundColor Green
    $output+="$name is up,"+"`n"
    }
    else{
Write-Host "$name is down" -ForegroundColor Red
$output+="$name is down,"+"`n"

        }
}
$output | Out-File "C:\IP_Result"

带有 IP 地址的 TXT 文件:

8.8.8.8
192.168.33.2
10.10.10.10
192.168.33.4
1.1.1.1

所以当我第一次运行脚本时,我收到:

8.8.8.8 is up,
192.168.33.2 is up,
10.10.10.10 is down,
192.168.33.4 is up,
1.1.1.1 is up,

现在,如果我将更$output | Out-File改为另一个文件名(这样我可以获得带有结果的新文件),我将收到新文件名,但会收到以前的结果

例如

新 IP 地址(以新名称插入新文件$IPs = Get-Content

2.2.2.2
3.3.3.3
4.4.4.4

现在我运行脚本和结果:

8.8.8.8 is up,
192.168.33.2 is up,
10.10.10.10 is down,
192.168.33.4 is up,
1.1.1.1 is up,
1.1.1.1 is up,
2.2.2.2 is down,
3.3.3.3 is down,
4.4.4.4 is down,

为什么我看到旧的结果?

标签: powershell

解决方案


您使用相同的变量$output并继续附加到它 ( $output +=)。如果您在一个全新的窗口中运行脚本,您将得到单一的结果。
为了防止这种行为$output在脚本的开头启动变量:

$output = $null # = empty

或者

$output = @() # = array

或者

$output = "" # = string

另一种方法是在使用完变量后删除它:

Remove-Variable output 

这是一个额外的提示:
使用+=将在每次迭代时重新创建集合。对于几十个值没关系,但对于数百个值,收集 foreach 本身的输出要快得多:

$output = foreach($name in $Ips){
    if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
        Write-Host "$name is up" -ForegroundColor Green
        "$name is up,"
    }
    else{
        Write-Host "$name is down" -ForegroundColor Red
        "$name is down,"
    }
}

而且您不必自己重新启动变量。


推荐阅读