下面的代码关闭每台远程计算机上的防火墙,并返回所有已关闭的计算机。我还试图检索已被授权通过每台计算机的防火墙的软件。

我了解我正在使用try,catch,所以有什么方法可以将$Appfilter的输出打印到offComp&programsALLO.txt吗?文本文件仅显示$Appfilter的值。

理想情况下,输出应如下所示:

Computers:
"name of computer" followed by "programs allowed"

这是代码:
Get-ADComputer -Filter * | Select-Object -ExpandProperty Name | Out-File .\ADcomputers.txt

$LaunchLine = 'powershell.exe -Version 4.0 -Command "& {netsh advfirewall set allprofiles state off}"'
$Appfilter = 'powershell.exe -Version 4.0 -Command "& {Get-NetFirewallApplicationFilter -program * | fl program}"'
$ComputerList = Get-Content .\adcomputers.txt

foreach($Computer in $ComputerList) {
    [String]$wmiPath = "\\{0}\root\cimv2:win32_process" -f $computer

    try {
        [wmiclass]$Executor = $wmiPath
        $executor.Create($LaunchLine, $Appfilter)
    } catch {
        Add-Content offComp&programsALLO.txt "computers:$Computer, $Appfilter "
    }
}

最佳答案

如果可能,我将Invoke-Command-ComputerName参数一起使用:

#store AD Computer names in an array
$computerList = (Get-ADComputer -Filter *).Name

#declare results arrays
$results = @()
$offline = @()

#for each computer
foreach($computer in $computerList) {

    #if computer responds to ping
    if(Test-Connection $computer -Count 2 -Quiet -ErrorAction SilentlyContinue) {

        #disable firewall
        Invoke-Command -ComputerName $computer -ScriptBlock {
            netsh advfirewall set allprofiles state off
        } | Out-Null

        #store retrieved authorized programs list in an array
        $programs = Invoke-Command -ComputerName $computer -ScriptBlock {
            (Get-NetFirewallApplicationFilter).Program
        }

        #build results object and add it to results array
        $results += [PSCustomObject]@{
            ComputerName = $computer
            Programs = $programs -join ";"
        }
    } else {
        #build results object and add it to offline array
        $offline += [PSCustomObject]@{
            ComputerName = $computer
            Status = "OFFLINE"
        }
    }
}

#export results to files
$results | Out-File "report.txt"
$offline | Out-File "offline.txt"

07-24 09:39