Categories:
  🠪  General

Email
  🠪  Servers
  🠪  Testing
  🠪  Tips

Hardware
  🠪  3D Printing
  🠪  Apple
  🠪  Batteries
  🠪  Drives
  🠪  Edgerouter
  🠪  Electronics
  🠪  Laptop
  🠪  Modems
  🠪  Phone
  🠪  Printers
  🠪  Raspberry Pi
  🠪  Tablets
  🠪  Testing
  🠪  Virtualization

hidden
  🠪  General

Links
  🠪  Interesting
  🠪  Media

Network
  🠪  Data
  🠪  Testing
  🠪  VPN

Scripts
  🠪  Batch
  🠪  Linux
  🠪  Powershell

Servers
  🠪  Databases
  🠪  Misc
  🠪  Website

Software
  🠪  Other

Utilities
  🠪  Backup
  🠪  Fix Issues
  🠪  Recovery

Video
  🠪  Editing

Websites
  🠪  HTML
  🠪  Testing

Windows
  🠪  Adjustments
  🠪  Issues
  🠪  Remote Desktop
  🠪  Security
  🠪  Slow
  🠪  Software
  🠪  Startup

Submit Entry
Airin's Notes

Category: Scripts 🠪 Powershell
Add full size logo to images
December 1, 2023

# Call script using:
# powershell.exe -File "AddLogo.ps1" -Filename "C:\Tools\Scripts\File.jpg" -Suffix "-Honor" -TemplateFile "C:\Tools\Scripts\Batch\Template.png"


param([String]$Filename="", [String]$Suffix="", [String]$TemplateFile="")

Add-Type -AssemblyName 'System.Drawing'


if ( $psise ){
$SourceImage = "C:\Tools\Scripts\Batch\test4.jpg"
$Suffix = "-Honor"
$TemplateFile = "C:\Tools\Scripts\Batch\Template-HH.png"
}else{
$SourceImage = $Filename
if ( $Suffix.length -lt 0 ){ $Suffix = "-New" }
}




$SpacingLeft = [Math]::Round( 50 * ( $Image.width / 2400 ) )
$SpacingRight = $SpacingLeft
$SpacingTop = [Math]::Round( 50 * ( $Image.height / 2051 ) )
$SpacingBottom = [Math]::Round( 277 * ( $Image.height / 2051 ) )


Write-Host "Loading picture: $($SourceImage)"
$Image = [System.Drawing.Bitmap]::FromFile($SourceImage)


$FinalImagePath = ( ( $SourceImage | Split-Path -Parent ) + '\' + [System.IO.Path]::GetFileNameWithoutExtension($SourceImage) + $Suffix + ".jpg" )

$Template = [System.Drawing.Bitmap]::FromFile($TemplateFile)
$TemplateResized = New-Object System.Drawing.Bitmap( ( $Image.width + $SpacingLeft + $SpacingRight ).ToInt32($null) , ( $Image.Height + $SpacingTop + $SpacingBottom ).ToInt32($null) )
$TemplateGraphics = [System.Drawing.Graphics]::FromImage($TemplateResized)
$TemplateGraphics.DrawImage($Template, 0, 0, ($Image.width + $SpacingLeft + $SpacingRight ) , ( $Image.Height + $SpacingTop + $SpacingBottom ))





$FinalCanvas = [System.Drawing.Bitmap]::new( ($Image.width + $SpacingLeft + $SpacingRight ).ToInt32($null) , ( $Image.Height + $SpacingTop + $SpacingBottom ).ToInt32($null) )

$g = [System.drawing.graphics]::FromImage($FinalCanvas)
$g.Clear([System.Drawing.Color]::Black)



# Put it there
#$g.DrawImage($Image, $SpacingLeft, $SpacingTop)
#$g.DrawImage($Image, [System.Drawing.Point]::new($SpacingLeft, $SpacingTop) , [System.Drawing.Rectangle]::new(0,0,100,100) )
$g.DrawImage($Image, [System.Drawing.Rectangle]::new($SpacingLeft,$SpacingTop,$Image.width,$Image.height) , [System.Drawing.Rectangle]::new(0,0,$Image.width,$Image.height) , [System.Drawing.GraphicsUnit]::Pixel)

$g.DrawImage($TemplateResized, 0, 0)
#$g.DrawString("test")

# Save it


Write-Host "Saving picture: $FinalImagePath"
$FinalCanvas.Save($FinalImagePath, [System.Drawing.Imaging.ImageFormat]::Jpeg)


Category: Scripts 🠪 Powershell
CPU Stress Test in Powershell
November 30, 2023

This script was found here: https://www.robvit.com/windows_server/generate-cpu-load-with-powershell/


ForEach ($core in 1..$NumberOfLogicalProcessors){

start-job -ScriptBlock{

$result = 1;
foreach ($loopnumber in 1..2147483647){
$result=1;

foreach ($loopnumber1 in 1..2147483647){
$result=1;

foreach($number in 1..2147483647){
$result = $result * $number
}
}

$result
...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Create daily exports of Hyper-V Virtual Machines
December 1, 2023

$BackupPathBase = "Z:\Backups\Hyper-V"
$Date = Get-Date

#Details on command lines: https://www.nakivo.com/blog/hyper-v-export-import/



$VMList = Get-VM
foreach ( $VM in $VMList){

$BackupPath = "$($BackupPathBase)\$($Date.DayOfWeek)"

If( ! ( Test-Path -PathType container $BackupPath ) ){
New-Item -ItemType Directory -Force -Path $BackupPath
}

Write-Host "Backup up $($VM.Name) to $($BackupPath)"
Export-VM -Name $VM.Name -Path $BackupPath
}



keyword...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Create files with random data in them of a specific size
November 28, 2023

$bytes = 50KB

[System.Security.Cryptography.RNGCryptoServiceProvider] $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$rndbytes = New-Object byte[] $bytes
$rng.GetBytes($rndbytes)
$Name = "$($bytes / 1024 )KB.bin"
if ( $bytes -ge ( 1024 * 1024 ) ){ $Name = "$($bytes / 1024 / 1024 )MB.bin" }
[System.IO.File]::WriteAllBytes("C:\Tools\TestFiles\Random\$($Name)", $rndbytes)


Category: Scripts 🠪 Powershell
Debugging
November 27, 2023

Debug another powershell process. I recommend using this in PSISE.
$ProcessList = Get-Process powershell
Enter-PSHostProcess -Process $ProcessList[correctindex]
Get-Runspace
Debug-Runspace -Id [RunspaceIndex]


Category: Scripts 🠪 Powershell
Delete duplicate files found with a suffix like (Copy)
November 29, 2023

$Folder = "E:\Recovered_Files"
$ScanSubfolders = $false

$SuffixForDuplicate = " - Copy"

$Files = get-childitem $Folder
$DeletedCount = 0

foreach ( $File in $Files ){
$MatchName = "$($File.BaseName)$($SuffixForDuplicate)$($File.Extension)"
$Match = $Files | Where-Object { $_.Name -eq $MatchName -and $_.Length -eq $File.Length }
if ( $Match.count -gt 0 ){
#Duplicate found!
write-host "Deleting $($Match.FullName)"
Remove-Item $Match.FullName -Force
...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Detect Keystrokes in console PowerShell scripts
November 30, 2023

https://powershell.one/tricks/input-devices/detect-key-press

if ([Console]::KeyAvailable)
{
# read the key, and consume it so it won't
# be echoed to the console:
$keyInfo = [Console]::ReadKey($true)
# exit loop
break
}


Category: Scripts 🠪 Powershell
Determine if Powershell is running in GUI or not
November 29, 2023

if ( ! ($PSISE -or $host.name.Contains('Studio'))) {




Keywords: VS Code, Powershell ISE


Category: Scripts 🠪 Powershell
Exchange Commands
December 2, 2023

Check exchange version. The best method is to visit link below and download the health check script. Alternately, the next two commands may show (get-exchangeserver may sometimes show old version).
Get-Command Exsetup.exe | ForEach {$_.FileVersionInfo}
Get-ExchangeServer | Format-List Name,Edition,AdminDisplayVersion
https://docs.microsoft.com/en-us/exchange/new-features/build-numbers-and-release-dates?view=exchserver-2019

Get-Mailbox -Identity first.last | fl DisplayName, Name, PrimarySmtpAddress, Se...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Exchange Online
February 16, 2024

Install ExchangeOnlineManagement if it isn't yet installed (run as Admin):
Install-Module -Name ExchangeOnlineManagement -RequiredVersion 3.4.0

Import module:
Import-Module ExchangeOnlineManagement

Connect-ExchangeOnline -UserPrincipalName user@yourdomainhere.com
Enable-OrganizationCustomization


Install ExchangeOnlineManagement
https://www.powershellgallery.com/packages/ExchangeOnlineManagement/3.4.0


Enable Forwarding for all accounts:
Remote Server returned '550 5.7.520 Access denied, ...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Hotkeys Test
November 27, 2023

#https://hinchley.net/articles/creating-a-key-logger-via-a-global-system-hoo
k-using-powershell/
Add-Type -TypeDefinition @"
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace KeyLogger {
public static class Program {
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;

private static HookProc hookProc = HookCallback;
private static IntPtr hookId = IntPtr.Zero;
...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
List all installed programs on a computer
December 1, 2023

Get-WmiObject -Class Win32_Product | Sort Name | Select Name


Category: Scripts 🠪 Powershell
Misc Snippets
November 28, 2023

### Text to Speech
$Path = "$env:temp\file.wav"
Add-Type -AssemblyName System.Speech
$synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$synthesizer.SetOutputToWaveFile($Path)
$synthesizer.Speak('This is a recording.')
$synthesizer.Speak('Adding more to it')
$synthesizer.SetOutputToDefaultAudioDevice()
# Play back the recorded file
Invoke-Item $Path



### View properties of an object
Get-Process *note* | ConvertTo-Json | Out-File $env:APPDATA\GM.json ; $IE=new-objec...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
My Powershell scripts
November 29, 2023

This lists some powershell scripts I have created which may be of interest to others.

To run a powershell script automatically using Task Scheduler, set the program to [ powershell.exe ] and the Add Arguments field to [ -File "PathToScript.ps1" ].
Link to more info on setting it.




If you have errors running powershell scripts, you need to run this command in an Ad...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Performance and Tips
November 29, 2023

Performance comparison of ArrayList, Generic List, hashtable, ordered dictionary, hashset, and stack.
https://www.norlunn.net/2019/10/17/powershell-performance-tips/


Category: Scripts 🠪 Powershell
Powershell Script Assistance
December 1, 2023

GUI Builder
https://poshgui.com/Editor


Category: Scripts 🠪 Powershell
Quick script to show all Hosts file from all online machines in Active Directory
November 28, 2023

$OnlyThisComputer = "" # Use this to limit it to working on a single machine, say 'PC17', or make it blank to apply to all computers starting with 'PC'.
$CheckHostsFile = $true


$Computers = Get-ADComputer -Filter '*' | Select -ExpandProperty Name | Sort
ForEach ($COMPUTER in $Computers){
if ( $true ){
if( ( $OnlyThisComputer.length -lt 1 -or $COMPUTER -eq $OnlyThisComputer ) ){
if (Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet){
...<Too long, click to read the rest>

Category: Scripts 🠪 Powershell
Regex
December 1, 2023

Online Regex testing
https://regex101.com/


Category: Scripts 🠪 Powershell
Set up SSH server for Powershell remote access
November 30, 2023

https://www.geekersdigest.com/how-to-use-ssh-from-windows-powershell/


Category: Scripts 🠪 Powershell
Show all files created/modified in the last 5 days
November 30, 2023

Change to the directory you want to scan first. This scans subfolders as well.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-5) -and $_.PSIsContainer -eq $false}


Keywords: Recent Files, modified, updated, changed, today, recently


Category: Scripts 🠪 Powershell
Sigcheck
November 26, 2023

This doesn't actually use Powershell YET...
C:\Tools\SysinternalsSuite\sigcheck.exe -accepteula -e -s -vt -vs -u C:\ > C:\Tools\check.txt


keywords: Sysinternals, Signature, Check, sigcheck.exe, digital signatures


Category: Scripts 🠪 Powershell
Signing Powershell scripts
December 1, 2023

https://www.darkoperator.com/blog/2013/3/5/powershell-basics-execution-policy-part-1.html

https://www.hanselman.com/blog/signing-powershell-scripts


Category: Scripts 🠪 Powershell
Simple script to select the right backup drive where the drive letter may change
November 27, 2023

# This lets you create a file in the root of a backup drive, then this script will search all drive letters for it
# It will then start a batch file passing the drive letter to the batch file
# The batch file will only be called if the backup drive is found


$Drives = Get-PSDrive
$DriveLetter = ""
$MatchFilePath = "BackupA.txt"
$BackupScript = "D:\Temp\test.bat"
# $BackupScript will be called with a plain drive letter like this: cmd.exe /c c:\BackupScript.bat E

foreach ( $Drive in $Drives ){
...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Swap default printers using Powershell Script
November 30, 2023

$Printers = Get-CimInstance -Class Win32_Printer
$DefaultPrinter = ""
$Printer1 = "RICOH MP C6004"
$Printer2 = "HP LaserJet 600"

foreach ( $Printer in $Printers ){
if ( $Printer.Default ){ $DefaultPrinter = $Printer.Name }
}
write-Host "Old Default printer: $($DefaultPrinter)"

if ( $DefaultPrinter -match $Printer1 ){
$NewPrinter = $Printer2
}else{
$NewPrinter = $Printer1
}
foreach ( $Printer in $Printers ){
if ( $Printer.Name -match $NewPrinter ){
Invoke-CimMethod -InputObject $Printer -M...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Sysmon
December 1, 2023

https://gist.github.com/psrdrgz/f87e73c4a89c4968f4ac67bf99267cc4


Sysmon is a SysInternals tool from Microsoft which allows logging of things
the computer does to the Event Log. It includes things like file
writes/creates/reads, network access, process start/stop, etc.
You can find it in the Event Viewer under:
Applications and Services\Microsoft\Windows\Sysmon\Operational

Here are some powershell commands to parse out useful information:

Get all Sysmon events, this will take a few minutes, do...<Too long, click to read the rest>


Category: Scripts 🠪 Powershell
Tray Icon Sample
December 1, 2023

https://github.com/mossrich/PowershellRecipes/blob/master/TraySnippets.ps1


Category: Scripts 🠪 Powershell
Uninstall Software matching name
November 26, 2023

#Display apps matching this name
$app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "Epson" }; foreach ( $thisapp in $app) { write-host $thisapp.name }

# Uninstall apps matching this name
$app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "Epson" }; foreach ( $thisapp in $app) { write-host $thisapp.name; $app.Uninstall() }


Keywords: Uninstall multiple programs at once, batch file, powershell, remove, uninstall, delete, program, application, wildcard





This site is meant to be used as a reference for myself, although others may find it useful. I use it to keep track of certain fixes, software, and other solutions which I may need while assisting customers. The page layout is pure HTML/CSS and is kept simple to optimize loading time and fast results.

Return to Airin's Computers