Power Shell for Loop not Looping

问题描述 投票:0回答:1

所以输出工作正常,但是我只输出它运行的最后一行时遇到了问题。无论如何,将来是否要检查循环以进行测试?

但是我有一个IP地址列表,我正在尝试检查Windows中的防火墙是启用还是禁用。他们在一个大型(300多个工作组)中。任何使此循环正确的帮助将不胜感激。安全和其他因素不是问题,因为我有其他运行良好的脚本。而且我没有任何错误。只是单个输出。

我已经尝试过移动阵列,但无济于事。我认为这可能是PSCustomObject的一部分,因为我才刚刚开始学习这些内容。还是我的输入和输出格式不同,这会导致问题?

clear
$ComputerList = get-content C:\Users\Administrator\Desktop\DavidsScripts\TurnOffFirewall\input.txt
$Status = @(
foreach ($Computer in $ComputerList) {

netsh -r $Computer advfirewall show currentprofile state})[3] -replace 'State' -replace '\s' 


$Object = [PSCustomObject]@{
    Computer = $Computer
    Firewall = $Status
}

Write-Output $Object
$Object | Export-Csv -Path "C:\FirewallStatus.csv" -Append -NoTypeInformation
powershell loops foreach windows-firewall
1个回答
0
投票

您以前的代码没有转义循环,而只是将循环中的最后一台计算机添加到对象。

我发现的最好方法是制作一个临时对象并将其添加到数组列表中,然后将其导出。好多了。

$ComputerList = get-content C:\Users\Administrator\Desktop\DavidsScripts\TurnOffFirewall\input.txt
$collectionVariable = New-Object System.Collections.ArrayList

ForEach ($Computer in $ComputerList) {
    # Create temp object
    $temp = New-Object System.Object
    # Add members to temp object
    $temp | Add-Member -MemberType NoteProperty -Name "Computer" -Value $Computer
    $temp | Add-Member -MemberType NoteProperty -Name "Firewall" -Value $((netsh -r $Computer advfirewall show currentprofile state)[3] -replace 'State' -replace '\s')
    # Add the temp object to ArrayList
    $collectionVariable.Add($temp) | Out-Null 
}

Write-Output $collectionVariable
$collectionVariable | Export-Csv -Path "C:\FirewallStatus.csv" -Append -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.