Posts

Showing posts from March, 2023

Install All Microsoft Updates Older Than 7 Days Using PowerShell and PSWindowsUpdate

To create a PowerShell script that leverages the PSWindowsUpdate module to install all Windows updates over 7 days old, follow these steps: Make sure the PSWindowsUpdate module is installed. If not, install it by running the following command in an elevated PowerShell session: Install-Module -Name PSWindowsUpdate Create a new PowerShell script file, for example, ' Install-UpdatesOlderThan7Days.ps1 ', and open it in a text editor or PowerShell ISE. Add the following code to the script file: # Import the PSWindowsUpdate module Import-Module PSWindowsUpdate # Set the date to 7 days ago $DateThreshold = (Get-Date).AddDays(-7) # Get the list of available updates that are older than 7 days $Updates = Get-WUList -NotCategory "Drivers" | Where-Object { $_.LastDeploymentChangeTime -lt $DateThreshold } # If updates are found, install them if ($Updates) { Write-Host "Updates found: $($Updates.Count)" Write-Host "Installing updates..." # Instal...

Dynamically Download a Recordset of Lacework Alert Types and Store Them as a Custom Object in Zendesk Using PowerShell

 # API keys and credentials $lwApiKey = "your_lacework_api_key" $zdEmail = "your_zendesk_email" $zdPassword = "your_zendesk_password" $zdSubdomain = "your_zendesk_subdomain" # Lacework API endpoint $lwApiEndpoint = "https://api.lacework.net/api/v1/AlertTypes" # Zendesk API endpoint $zdApiEndpoint = "https://$zdSubdomain.zendesk.com/api/v2/objects/records" # Create authentication header for Zendesk $zdAuthHeader = @{ 'Authorization' = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$zdEmail:$zdPassword")) } # Get Lacework alert types $response = Invoke-RestMethod -Uri $lwApiEndpoint -Headers @{ "X-Api-Key" = $lwApiKey } -Method Get $alertTypes = $response.data # Create a custom object in Zendesk for each Lacework alert type foreach ($alertType in $alertTypes) { $customObject = @{ 'data' = @{ 'type' = 'custom_object...

Disable Microsoft Account Sync Using PowerShell

To disable Microsoft Account Sync using a PowerShell script, you can use the following script which will create a registry key to disable the sync: # DisableMicrosoftAccountSync.ps1 # Run PowerShell as Administrator if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { $arguments = "& '" + $myinvocation.mycommand.definition + "'" Start-Process powershell -Verb runAs -ArgumentList $arguments Break } # Create registry key to disable Microsoft Account Sync $path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\SettingSync" $key = "DisableSettingSync" if (-not(Test-Path $path)) { New-Item -Path $path -Force | Out-Null } Set-ItemProperty -Path $path -Name $key -Value 2 -Type DWord -Force Write-Host "Microsoft Account Sync has been disabled successfully." To execute this script, follow these steps: Ope...

Unveiling the Power of PowerShell Regions: A Comprehensive Guide

 Introduction PowerShell has gained widespread popularity as a powerful task automation and configuration management framework. As your PowerShell scripts grow in size and complexity, it's essential to maintain readability and organization. One often under-utilized feature of PowerShell that can significantly improve code readability is the use of 'regions'. In this blog post, we will delve into the concept of regions in PowerShell, exploring their applications, benefits, and how you can make the most of them in your scripts. What are PowerShell Regions? PowerShell regions are collapsible sections of code, demarcated by special comments, that allow you to group and organize related code snippets. The primary purpose of regions is to improve the readability of your scripts by allowing you to fold or collapse sections of code that are not actively being worked on. These regions can be expanded or collapsed using the 'Expand-Collapse' functionality available in most mo...

PowerShell Script to Harden a Windows 2019 Server to HITRUST Cybersecurity Standards

 HITRUST is a cybersecurity framework that aims to protect sensitive information and manage risks in the healthcare industry. Hardening a Windows Server 2019 to meet HITRUST standards involves implementing a range of security controls to ensure the confidentiality, integrity, and availability of the system and the data it processes. Here's a PowerShell script that you can use to harden a Windows Server 2019 to HITRUST standards: # Disable SMBv1 Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol # Enable SMBv2 and SMBv3 Set-SmbServerConfiguration -EnableSMB2Protocol $true Set-SmbServerConfiguration -EnableSMB3Protocol $true # Disable NetBIOS over TCP/IP Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object { $_.TcpipNetbiosOptions -ne 0 } | ForEach-Object { $_.DisableNetbios() } # Enable Windows Defender Set-MpPreference -DisableRealtimeMonitoring $false Set-MpPreference -DisableBehaviorMonitoring $false Set-MpPreference -DisableBlockAtFirstSeen...

PowerShell Script to Check the CMOS Battery Level for All Computer Objects in the Domain

 Here is an PowerShell script that checks the CMOS battery of all computer objects in the domain: # Define the domain name $domain = "yourdomain.com" # Get a list of all computer objects in the domain $computers = Get-ADComputer -Filter {OperatingSystem -Like "*Windows*"} -Properties Name | Select-Object -ExpandProperty Name # Loop through each computer and check the CMOS battery foreach ($computer in $computers) { Write-Host "Checking CMOS battery of computer $computer..." $session = New-PSSession -ComputerName $computer $wmi = Invoke-Command -Session $session -ScriptBlock { Get-WmiObject win32_battery | Where-Object {$_.Name -match "CMOS"} } $wmi | Select-Object PSComputerName, EstimatedChargeRemaining Remove-PSSession $session }

What Does The Future Hold for PowerShell?

PowerShell is a powerful and versatile automation tool developed by Microsoft. It was first released in 2006, and since then, it has become the go-to tool for IT professionals to automate tasks in Windows environments. In recent years, PowerShell has evolved significantly, and there are many exciting developments on the horizon for this tool. In this blog post, we will explore the future of PowerShell and what it means for IT professionals. PowerShell 7 and Beyond Microsoft released PowerShell 7 in early 2020, and it introduced several new features and improvements over the previous version. PowerShell 7 is cross-platform, meaning that it can run on Windows, Linux, and macOS, making it a more versatile tool for IT professionals who work in heterogeneous environments. PowerShell 7 also supports new operators and pipeline improvements, making it more efficient and easier to use. Looking ahead, Microsoft is working on PowerShell 7.2, which is expected to be released in 2022. PowerShell 7....

PowerShell Script to Clean Up Erroring OWA Rules

A PowerShell script that cleans up erroring OWA (Outlook Web App) rules should follow these steps: Connect to Exchange Online via PowerShell. Retrieve the user mailboxes. Loop through each user mailbox and identify erroring OWA rules. Remove the erroring rules. Here's a sample script to achieve this:  # Connect to Exchange Online $UserCredential = Get-Credential $ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection Import-PSSession $ExchangeSession -DisableNameChecking # Retrieve all user mailboxes $Mailboxes = Get-Mailbox -ResultSize Unlimited # Loop through each user mailbox foreach ($Mailbox in $Mailboxes) { Write-Host "Processing mailbox: $($Mailbox.PrimarySmtpAddress)" # Get inbox rules $InboxRules = Get-InboxRule -Mailbox $Mailbox.PrimarySmtpAddress # Loop through each rule foreach ($Rule...

PowerShell Script to Reset Permissions on all Documents in a Document Library in SharePoint Online.

Here's a PowerShell script that resets permissions on all documents in a SharePoint Online document library: #Connect to SharePoint Online Site $SiteURL = "https://yourdomain.sharepoint.com/sites/sitename" $UserName = "yourusername@yourdomain.com" $Password = "yourpassword" $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential($UserName, $SecurePassword) Connect-PnPOnline -Url $SiteURL -Credentials $Cred #Set Variables $ListName = "Documents" $FolderPath = "/Shared Documents" #Get all Documents from the document library $Documents = Get-PnPListItem -List $ListName -Folder $FolderPath #Loop through each document and reset permissions foreach ($Doc in $Documents) { Set-PnPListItemPermission -List $ListName -Identity $Doc.Id -InheritPermissions $true -ClearAllPermissions $true } Write-Host "Permissions reset complete." You will need to re...

Reboot a Remote Windows Computer and Wait Until It is Back Online to Continue PowerShell Script

This script will reboot the specified remote computer, wait for it to go offline, and then wait for it to come back online before moving on with the rest of the script. # Set the target computer name and credentials $ComputerName = "TargetComputerName" $Username = "YourUserName" $Password = "YourPassword" # Convert the plain text password to a secure string $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force # Create a PSCredential object $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword # Function to test the target computer's availability function Test-ComputerAvailability { param($ComputerName) try { $PingResult = Test-Connection -ComputerName $ComputerName -Count 1 -ErrorAction Stop -Quiet } catch { $PingResult = $false } return $PingResult } # Reboot the target computer Restart-Computer -ComputerName $ComputerNa...

Use Python to Auto-Enhance All Photos in a Folder

import os from PIL import Image, ImageEnhance # Set input and output folders input_folder = 'input_photos' output_folder = 'output_photos' # Set enhancement factors color_factor = 1.2 contrast_factor = 1.2 brightness_factor = 1.2 vibrancy_factor = 1.2 # Create output folder if it doesn't exist if not os.path.exists(output_folder): os.makedirs(output_folder) def enhance_image(image_path): # Open image image = Image.open(image_path) # Enhance color enhancer = ImageEnhance.Color(image) image = enhancer.enhance(color_factor) # Enhance contrast enhancer = ImageEnhance.Contrast(image) image = enhancer.enhance(contrast_factor) # Enhance brightness enhancer = ImageEnhance.Brightness(image) image = enhancer.enhance(brightness_factor) # Enhance vibrancy (saturation) enhancer = ImageEnhance.Color(image) image = enhancer.enhance(vibrancy_factor) return image # Iterate through all images in the input folde...

PowerShell to Replicate UDM-Pro DNS Records to Windows DNS Server

 Hello Friends... Thought some of you might find value in this... The following script will SSH to your UDM-Pro, export the DNS data, and parse the data to add host and PTR records in Windows DNS. The script removes any outdated/duplicate records before adding the new record. Please note you will need the Posh-SSH module installed and SSH enabled on your UDM-Pro. # Define variables $UDMProHost = "UDMPro_IP" $UDMProUsername = "UDMPro_Username" $UDMProPassword = "UDMPro_Password" $WindowsDNSServer = "Windows_DNS_IP" $WindowsDNSZone = "yourdomain.local" $WindowsDNSReverseZone = "0.168.192.in-addr.arpa" # Connect to UDM-Pro using SSH $UDMProCreds = New-Object System.Management.Automation.PSCredential ($UDMProUsername, ($UDMProPassword | ConvertTo-SecureString -AsPlainText -Force)) $UDMProSession = New-SSHSession -ComputerName $UDMProHost -Credential $UDMProCreds # Export UDM-Pro DNS data $UDMProDNSExport = Invoke-SSHCommand -SS...

PowerShell to Download All Critical/High Lacework Alerts From the Last 24 Hours

Not sure how many folks here would use this but I needed this as part of a larger project so I thought I would share: # Define Lacework API key, endpoint, and time range $APIKey = "your_lacework_api_key" $BaseURI = "https://api.lacework.net/api/v1" $TimeRange = (Get-Date).AddHours(-24).ToString("yyyy-MM-ddTHH:mm:ssZ") # Create authentication headers $Headers = @{ 'Content-Type' = 'application/json' 'x-api-key' = $APIKey } # Define function to get alerts function Get-LaceworkAlerts($severity, $since) { $URI = "$BaseURI/external/vulnerabilities/container?start_time=$since&severity=$severity" try { $Response = Invoke-WebRequest -Uri $URI -Headers $Headers -Method Get $Alerts = ($Response.Content | ConvertFrom-Json).data } catch { Write-Error "Error fetching Lacework alerts: $_" $Alerts = $null } return $Alerts } # Get critical and high alerts ...

Python Script to Use the Computer Camera to Scan Barcodes

I was going to buy a Honeywell MS7120 but ended up writing this Python code to use the camera on my Surface as a UPC barcode scanner for when I'm listing and don't want to transpose numbers. It will copy the barcode into your clipboard to be pasted into eBay. Hope it helps someone else, too: import cv2 from pyzbar import pyzbar import sys import pyperclip import time def set_focus(camera, value): camera.set(cv2.CAP_PROP_AUTOFOCUS, 0) camera.set(cv2.CAP_PROP_FOCUS, value) def scan_barcode(): # Change the camera index to use the front or rear-facing camera camera_index = 0 cap = cv2.VideoCapture(camera_index) # Set an initial focus value focus_value = 0.0 set_focus(cap, focus_value) last_focus_change_time = time.time() while True: ret, frame = cap.read() barcodes = pyzbar.decode(frame) for barcode in barcodes: (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h...

PowerShell Script to Remotely Update Firmware on Brother Printers Microsoft

While this does not work for all models or configurations of Brother printers, it can be a lifesaver so I thought I would share: # Set your printer's IP address and model number $PrinterIP = "192.168.1.100" $PrinterModel = "HL-L8360CDW" # Define the URL for the firmware download page $FirmwareURL = "https://support.brother.com/g/b/downloadtop.aspx?c=us&lang=en&prod=$($PrinterModel.ToLower())_eus" # Get the latest firmware version from Brother's website $LatestFirmwareInfo = (Invoke-WebRequest -Uri $FirmwareURL -UseBasicParsing).Links | Where-Object { $_.href -like "*.firm" } | ForEach-Object { @{ Version = $_.innerText.Trim() -replace '[^0-9.]', ''; DownloadUrl = $_.href } } | Sort-Object -Descending -Property Version | Select-Object -First 1 if (!$LatestFirmwareInfo) { Write-Host "Couldn't retrieve the latest firmware version for the printer model. Please verify the printer model an...