Home > Net >  Command console output -- to file . Get { Windows Filtering Platform / Windows Firewall } rules
Command console output -- to file . Get { Windows Filtering Platform / Windows Firewall } rules

Time:12-12

Output of this doesn't fit into the window

get-netFirewallRule | where { $_.Action -eq 'Block' -and $_.Enabled -eq 'True' }

read-host -prompt "Press Enter to continue..."

When i try

Remove-Item -Path ($env:userprofile   "\Desktop\enabledBlockRules_WindowsFilteringPlatform.txt")

get-netFirewallRule | where { $_.Action -eq 'Block' -and $_.Enabled -eq 'True' } | forEach {
    $_ | Add-Content -Path ($env:userprofile   "\Desktop\enabledBlockRules_WindowsFilteringPlatform.txt") -Encoding "utf8"
}

read-host -prompt "Exported to desktop ."

I get nonsense results . How could i do this ?

CodePudding user response:

To streamline your answer and add some context:

Get-NetFirewallRule | 
  Where-Object { $_.Action -eq 'Block' -and $_.Enabled } | 
    Out-File -Encoding utf8 -FilePath "$env:userprofile\Desktop\enabledBlockRules_WindowsFilteringPlatform.txt"

Note how Out-File is directly piped to, which obviates the need for removing the output file first and the inefficient loop with -Append.

As for why switching from Add-Content to Out-File made the difference:

  • Set-Content / Add-Content perform simple .ToString() stringification of its input objects, which for complex objects more often than not results in unhelpful string representations.

  • By contrast, Out-File (>) / Out-File -Append (>>) use the usual for-display output-formatting system, yielding the same rich formatting you'd see when outputting to the console.

    • Do note, however, that these representations are for the human observer, and therefore not generally suited to programmatic processing; for the latter, use a structured text format, such as CSV or JSON.

See this answer for more information, including about the different default character encodings between the cmdlets in Windows PowerShell.

CodePudding user response:

damn

Remove-Item -Path ($env:userprofile   "\Desktop\enabledBlockRules_WindowsFilteringPlatform.txt")

get-netFirewallRule | where { $_.Action -eq 'Block' -and $_.Enabled -eq 'True' } | forEach {
    $_ | Out-File -FilePath ($env:userprofile   "\Desktop\enabledBlockRules_WindowsFilteringPlatform.txt") -Encoding "utf8" -Append
}

read-host -prompt "Exported to desktop ."
  • Related