Disable all the unwanted Windows Firewall rules using PowerShell - powershell

In my Windows Firewall, I've created certain rules that give me more control over my PC. But my rules have become somewhat useless since Windows and other apps are kept adding rules that I don't want.
I've tried to prevent this from happening, but the only way I've found is to use a third-party tool like Tinywall, which isn't exactly what I'm looking for.
So, to fix this, I want to create a PowerShell script that will disable and rename all rules that are not added by me. This way, I can manage them easily.
Rules that are added by me can be easily recognized because all of them start with certain words.
In this case, let's assume it starts with either 'Sample XYZ' or 'Sample ABC'.
Sample XYZ - Windows Update
Sample ABC - MPC-HC
Sample ABC - Firefox
Sample XYZ - Windows News
So far, this is what I have done.
In this part, the script will filter all the rules that I have created and then it'll disable & block all other rules.
To my surprise, this is working as expected.
# This will get all firewall rules
$NR = Get-NetFirewallRule
# This will exclude all the rules added by the user
$NR = $NR | Where-Object DisplayName -NotMatch "Sample ABC"
$NR = $NR | Where-Object DisplayName -NotMatch "Sample XYZ"
# Disable all other rules that are not added by the user
$NR | Set-NetFirewallRule -Enabled False
# Set rules' action to block
$NR | Set-NetFirewallRule -Action Block
These are the parts that don't work.
Task: Add a custom word to the beginning of the rules' display name
Example: If a rule name is 'Microsoft Photos', then it'll be renamed to 'IDWTFR - Microsoft Photos'.
# Add a custom word to the beginning of the rules' display name
# Custom word = 'IDWTFR - '
# Attempt 01: Fail
$NR | Set-NetFirewallRule -DisplayName "IDWTFR - " + $NR.DisplayName
# Attempt 02: Fail
$NR = $NR | ForEach-Object -MemberName DisplayName "IDWTFR - " + $NR.DisplayName | Set-NetFirewallRule
Task: Add unwanted rules to a group named 'Junk Rules'.
# Add to a group
# Attempt 01: Fail
$NR | Set-NetFirewallRule -DisplayGroup "Junk Rules"
To clarify it a bit more, this is the summary of what I am trying to do.
+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+
| Rule Name | New Rule Name | Group | Action | Status | Created by |
+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+
| Sample XYZ - Windows Update | Same as before | Same as before | Same as before | Same as before | User |
| Sample ABC - MPC-HC | Same as before | Same as before | Same as before | Same as before | User |
| Sample ABC - Firefox | Same as before | Same as before | Same as before | Same as before | User |
| Sample XYZ - Windows News | Same as before | Same as before | Same as before | Same as before | User |
| Microsoft Photos | IDWTFR - Microsoft Photos | Junk Rules | Block | Disable | Not by user |
| App Installer | IDWTFR - App Installer | Junk Rules | Block | Disable | Not by user |
| Feedback Hub | IDWTFR - Feedback Hub | Junk Rules | Block | Disable | Not by user |
| Microsoft Edge | IDWTFR - Microsoft Edge | Junk Rules | Block | Disable | Not by user |
+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+
I'm new to PowerShell, so any help will be appreciated. Thanks.

Since this is your special use case, it's going to a challenge for one to validate without setting up an environment as close as possible to what you show here. I am in no position to do that.
Yet, looking at what you say you have done, here is a refactor option to try. Refactor a bit (again, not tested)
# Get all firewall rule name, and filter out the named rules
Get-NetFirewallRule |
Where-Object -Property Name -notlike 'Sample ABC|Sample XYZ' |
ForEach {
# Disable all other rules that are not added by the user
Set-NetFirewallRule -Name $PSItem.DisplayGroup -Enabled False
# Set rules' action to block
$PSItem.DisplayName |
Set-NetFirewallRule -Action Block
# Rename firewall rule
If ($PSItem.DisplayName -like '*Microsoft*')
{Rename-NetFirewallRule -Name $PSItem.DisplayName -NewName "IDWTFR-$($PSitem.DisplayName)"}
# Create new firewall group
$PSItem.Group = 'JunkRules' |
Set-NetFirewallRule -NewDisplayName $PSItem.DisplayName
}

Related

Returning the Wear counter from a disk

Just trying to automate some things for my job and I need to report the wear to a txt file that I can later compile into a report that gets emailed.
Having some trouble with getting it to populate the txt file with the wear indication, below is what I'm running and it gives me the variable I want to export to a file
Get-Disk | Where-Object {$_.IsBoot -eq 'True'} | Get-StorageReliabilityCounter | Select Wear
Below is what I'm running that generates the file I need but doesn't actually fill with anything
$DiskWear = Get-Disk | Where-Object {$_.IsBoot -eq 'True'} | Get-StorageReliabilityCounter | Select Wear
$DiskWear.Trim > trimmed.txt
Any help appreciated :)

PowerShell - Find Oldest Email

I am stuck, I am trying to find the oldest "EMAIL" in a person's mailbox, but I don't know what else to try. I think I need to add the ContainerClass -eq "IPF.Note" somewhere, but I am not sure where.
The following script works, but it finds the oldest ITEM, which in my case it is a contact. I want to look at each container (Email, Chats, Calendar, Contacts) separately, but for this script, I just want to know the oldest email.
Thank you
Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity USERID |
Where OldestItemReceivedDate -ne $null |
Sort OldestItemReceivedDate |
Select -First 1 OldestItemReceivedDate
You can filter what you have by item type, but I would do it after getting the statistics so you only have to query exchange once:
# Get the folder statistics for all folders
$stats = Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity $USERID
# Get the oldest email. Can re-use $stats for the other item types
$OldestEmail = $stats |
Where-Object {$_.OldestItemReceivedDate -and $_.ContainerClass -eq 'IPF.Note'} |
Sort-Object OldestItemReceivedDate |
Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
# Outputs
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
IPF.Note 2/8/2016 2:07:50 PM /Inbox
You are correct that the mailbox folder statistics command does not search recoverable items by default. It also does not search the mailbox archive unless you specify -Archive. If you need these, you'll have to do additional searches:
# Get recoverable items:
Get-MailboxFolderStatistics -Identity $USERID -FolderScope 'RecoverableItems' -IncludeOldestAndNewestItems |
Where-Object OldestItemReceivedDate |
Sort-Object OldestItemReceivedDate |
Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
# Note that deleted item containers do not have an item type!
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
2/5/2016 3:41:33 PM /Deletions
Presuming this is for compliance reasons to search a mailbox for items on an Exchange Server you should be using the Search-Mailbox cmdlet - https://learn.microsoft.com/en-us/powershell/module/exchange/search-mailbox?view=exchange-ps
For Exchange Online to search a mailbox for items you should use the New-ComplianceSearch cmdlet https://learn.microsoft.com/en-us/powershell/module/exchange/new-compliancesearch?view=exchange-ps
This web page shows how to search by date - New-ComplianceSearch: how to use the newer version of Search-Mailbox https://www.codetwo.com/admins-blog/new-compliancesearch-new-version-of-search-mailbox/
This web page has a script to search mailboxes, including dates PowerShell – New-ComplianceSearch script to go through all mailboxes, find a target message, and remove it - https://365basics.com/powershell-new-compliancesearch-script-to-go-through-all-mailboxes-find-a-target-message-and-remove-it/
Using your original approach, should be done like this. Presuming you have appropriate permissions.
Get-MailboxFolderStatistics -ID <mailboxemailaddress> -IncludeOldestAndNewestItems | select Identity, Name, FolderPath, ItemsInFolder, FolderSize, OldestItemReceivedDate | Export-Csv C:\temp\Mailbox.csv -NoTypeInformation

How to transcript everything in console

Hey i'm trying to get the device code that's being printed to the console in powershell when running "Connect-ExchangeOnline -Device". However it doesn't get appended to the output file along with everything else when I use start transcribe.
Start-Transcript -path "Path" -append
$DebugPreference = 'Continue'
$VerbosePreference = 'Continue'
$InformationPreference = 'Continue'
Connect-ExchangeOnline -Device -Verbose
Expected output:
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code CDWS27A56 to authenticate.
Actual output:
The module allows access to all existing remote PowerShell (V1) cmdlets in addition to the 9 new, faster, and more reliable cmdlets.
|--------------------------------------------------------------------------|
| Old Cmdlets | New/Reliable/Faster Cmdlets |
|--------------------------------------------------------------------------|
| Get-CASMailbox | Get-EXOCASMailbox |
| Get-Mailbox | Get-EXOMailbox |
| Get-MailboxFolderPermission | Get-EXOMailboxFolderPermission |
| Get-MailboxFolderStatistics | Get-EXOMailboxFolderStatistics |
| Get-MailboxPermission | Get-EXOMailboxPermission |
| Get-MailboxStatistics | Get-EXOMailboxStatistics |
| Get-MobileDeviceStatistics | Get-EXOMobileDeviceStatistics |
| Get-Recipient | Get-EXORecipient |
| Get-RecipientPermission | Get-EXORecipientPermission |
|--------------------------------------------------------------------------|
To get additional information, run: Get-Help Connect-ExchangeOnline or check https://aka.ms/exops-docs
Send your product improvement suggestions and feedback to exocmdletpreview#service.microsoft.com. For issues related to the module, contact Microsoft support. Don't use the feedback alias for problems or support issues.
----------------------------------------------------------------------------

Powershell - "Expressions are only allowed as the first element of a pipeline"

Could someone please tell me how to avoid this error in the below circumstance?
$codegenDir = "Z:\Desktop\Song-Renamer"
$PowerShellRepresentation = dir -path $MyMusicFolder -recurse -include *.mp3,*.m4a,*.wma,*.flac,*.ape | select -ExpandProperty FullName | $codegenDir\codegen.exe -s 10 20 | Out-String | ConvertFrom-Json
What completely puzzles me is if simply omit $codegenDir (see below), the code operates correctly. I "think" I understand the concept of placing the expression first (ahead of other items in the pipeline. But I'm not sure how to rearrange/split this code so the expression in question the Codegen.exe external commandline is the first item in the pipeline (and still be able to pass data to it via pipeline).
$PowerShellRepresentation = dir -path $MyMusicFolder -recurse -include *.mp3,*.m4a,*.wma,*.flac,*.ape | select -ExpandProperty FullName | .\codegen.exe -s 10 20 | Out-String | ConvertFrom-Json
Ideally, it would be nice to do this using the least amount of code as possible.
Give the following a shot (only difference is the &):
$PowerShellRepresentation = dir -path $MyMusicFolder -recurse -include *.mp3,*.m4a,*.wma,*.flac,*.ape | select -ExpandProperty FullName | & $codegenDir\codegen.exe -s 10 20 | Out-String | ConvertFrom-Json
Here's a link to a technet article about executing commands in powershell in different ways.

Get-mailboxdatabase | clean-mailboxdatabase - not on all databases

We have a few Servers/Databases and I'd like to write a cleanDB script that only runs on half of them. The names that i want to alter start with exch-ms-01, 02, 03, 04. We have 3 others that I do not want to include in the clean.
Get-mailboxDatabase -server exch-ms-* returns : there are multiple exchange servers matching the identity "exch-ms-*". Please specify a unique value.
dug around and found something that works.
get-mailboxserver | Where-Object {($_.name -like "exch-ms-*")} | get-mailboxdatabase | clean-mailboxdatabase