循环中断?我能正确处理吗?

时间:2019-08-01 17:46:47

标签: powershell

尝试建立一个循环,该循环将对文本文件中的每一行运行test_netconnection,然后将响应输出到另一个文件中

我尝试过不同的编写方式,只是不确定我的循环在哪里中断

$file = 'Z:\servers.txt'
$addresses = Get-Content $file
$reader = New-Object IO.Streamreader $file
while ($reader.ReadLine() -ne $null) { }

foreach ($address in $addresses) {
    try {
        $Test = Test-NetConnection -ComputerName $addresses -Port xxxx -InformationLevel Quiet
        Write-Host "$Test" 
    } 
    catch {
        Out-File z:/output.txt
    }
}

我没有收到任何发送到我的Out-File的输出,我怀疑我的循环坏了

2 个答案:

答案 0 :(得分:0)

如果servers.txt包含以下内容:

www.google.com
www.microsoft.com
www.stackoverflow.com
...

...然后,您可以遍历它,使用Test-NetConnection查看条目是否可ping(ICMP),然后将结果导出为带有以下代码的* .CSV文件:

$servers = Get-Content C:\path\to\servers.txt
$servers | % {
    Test-NetConnection $_ | Select ComputerName, PingSucceeded | Export-Csv C:\path\to\results.csv -NoTypeInformation -Append
}

您可以通过调整代码的Select部分来扩展导出的结果属性。

答案 1 :(得分:0)

这是这个想法的一个过高版本。 [ grin ]它使用Tet-Connection而不是较新的Test-NetConnection,因为win7ps5.1没有该cmdlet。

如果您以前从未见过它,则#region注释是代码折叠标记。可以将当前不感兴趣的部分折叠一倍。

#region - save default prefs
# the Verbose default is screen display OFF
$AllowVerboseOutput = $True
# the Warning default is screen display ON
$AllowWarningOutput = $True

# save the VerbosePref
$OldVPref = $VerbosePreference
if ($AllowVerboseOutput)
    {
    # enable screen display of Write-Verbose [it's OFF by default]
    $VerbosePreference = 'Continue'
    }

# save the WarningPref
$OldWPref = $WarningPreference
if (-not $AllowWarningOutput)
    {
    # DISABLE Write-Warning screen output [it's ON by default]
    $WarningPreference = 'SilentlyContinue'
    }
#endregion - save default prefs

# if you want _fewer_ reports, use a larger final time unit
#    minutes, hours, whatever suits your needs [*grin*] 
$TimeStamp = Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'

$SystemListDir = $env:TEMP
$SystemListFile = 'ServerList.txt'
$FullSystemListFile = Join-Path -Path $SystemListDir -ChildPath $SystemListFile

$ReportDir = $env:TEMP
# if you don't want multiple report files, comment OUT this line & UN-comment the line after it
$ReportFile = -join ('ConnectionRemport', '_-_', $TimeStamp, '.csv')
#$ReportFile = -join ('ConnectionRemport', '.csv')
$FullReportFile = Join-Path -Path $ReportDir -ChildPath $ReportFile

$NoResponse = '-- No Response --'

#region - sample data import
# fake reading in a file
#    in real life, use the Get-Content line below
# remove the leading "#" on the next line when you are ready to use a real file
#<#
$SystemList = @'
LocalHost
127.0.0.1
10.0.0.1
'@.Split("`n").Trim()
#>
#endregion - sample data import

# remove the leading "#" on the next line when you are ready to use a real file
#$SystemList = Get-Content -Path $FullSystemListFile


$Results = foreach ($SL_Item in $SystemList)
    {
    Write-Verbose "Connecting to $SL_Item ..."
    if (Test-Connection -ComputerName $SL_Item -Count 1 -Quiet)
        {
        Write-Verbose "    System $SL_Item reached successfully."
        $TempObject = [PSCustomObject]@{
            MachineName = $SL_Item
            Status = 'Online'
            # the resulting "sortable" date string is yyyy-MM-ddTHH:mm:ss
            TimeStamp = (Get-Date).ToString("s")
            }
        }
        else
        {
        Write-Warning "    Unable to reach $SL_Item."
        $TempObject = [PSCustomObject]@{
            MachineName = $SL_Item
            Status = $NoResponse
            # the resulting "sortable" date string is yyyy-MM-ddTHH:mm:ss
            TimeStamp = (Get-Date).ToString("s")
            }
        }
    $TempObject
    } # end = foreach ($SL_Item in $SystemList)

# display $Results on screen
$Results

# save $Results to CSV file
$Results |
    Export-Csv -LiteralPath $FullReportFile -NoTypeInformation

#region - restore default prefs
# restore previuos VerbosePref
$VerbosePreference = $OldVPref
# restore previous WarningPref
$WarningPreference = $OldWPref
#endregion - restore default prefs

运行时的屏幕输出...

VERBOSE: Connecting to LocalHost ...
VERBOSE:     System LocalHost reached successfully.
VERBOSE: Connecting to 127.0.0.1 ...
VERBOSE:     System 127.0.0.1 reached successfully.
VERBOSE: Connecting to 10.0.0.1 ...
WARNING:     Unable to reach 10.0.0.1.

$Results集合的最终屏幕输出...

MachineName Status            TimeStamp          
----------- ------            ---------          
LocalHost   Online            2019-08-02T12:16:43
127.0.0.1   Online            2019-08-02T12:16:43
10.0.0.1    -- No Response -- 2019-08-02T12:16:47

CSV文件内容...

"MachineName","Status","TimeStamp"
"LocalHost","Online","2019-08-02T12:16:43"
"127.0.0.1","Online","2019-08-02T12:16:43"
"10.0.0.1","-- No Response --","2019-08-02T12:16:47"