2

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 ?

irvnriir
  • 673
  • 5
  • 14

2 Answers2

2

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • I was worrying about any size-per-operation limitations, thats why used foreach – irvnriir Dec 12 '21 at 00:01
  • 1
    @irvnriir, the pipeline _streams_ output objects, so that `Out-File` writes them to the file _one by one_, _as they're being received_, so there should be no concern about the overall size of the input. I assume that's what you meant, right? Also note that with per-object `Out-File` calls that result in _tabular_ formatting (not in your case), you'll get a header for each and every object. – mklement0 Dec 12 '21 at 00:13
0

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 ."
irvnriir
  • 673
  • 5
  • 14