Skip to content

Instantly share code, notes, and snippets.

@joaf123
Last active October 16, 2024 18:30
Show Gist options
  • Save joaf123/a83b6b23eeab2c274897d497a8245d30 to your computer and use it in GitHub Desktop.
Save joaf123/a83b6b23eeab2c274897d497a8245d30 to your computer and use it in GitHub Desktop.
[PowerShell] Personal Profile #PowerShell
#region ===== Oh-My-Posh Theme ===================================================================================================================================================
oh-my-posh --init --shell pwsh --config "$env:POSH_THEMES_PATH\no-internet.easy-term.omp.json" | Invoke-Expression
#endregion =======================================================================================================================================================================
#region ===== Install/Import Modules =============================================================================================================================================
# PSReadline Install if needed:
if (-not (Get-Module -Name "PSReadLine")) {
Write-Host "Installing PSReadLine"
Install-Module PSReadLine -Scope CurrentUser
}
#endregion =======================================================================================================================================================================
#region ===== Alias Configs ======================================================================================================================================================
# Fjerner overskriving av curl.exe som er et mye bedre alternativ til Invoke-WebRequest.
# Curl ligger i windows by default men er overskrevet av et powershell alias for Invoke-WebRequest.
# Husk å sjekke at du har konfigurert path riktig. Det hender at mappen hvor curl.exe ligger ikke er inkludert i miljøvariabelen "path"
$pwshVersion = Get-Host | Select-Object Version
# Remove the curl alias for Invoke-WebRequest so that curl binaries added to path are used instead:
if (-not ($pwshVersion -match '7.')) {
Remove-Item alias:\curl
}
#grep alias for Select-String:
set-alias grep Select-String
# Nano from Mingw or git binaries:
set-alias nano "C:\Program Files\Git\usr\bin\nano.exe"
#endregion =======================================================================================================================================================================
#region ===== Run WinFetch =======================================================================================================================================================
winfetch;
#endregion =======================================================================================================================================================================
#region ===== Configure PSReadLine AutoComplete ==================================================================================================================================
# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
# Autocompletion for arrow keys
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
#endregion =======================================================================================================================================================================
#region ===== .NET-Style RegEx Tester ============================================================================================================================================
function RegExer() {
# Load the Windows Forms assembly
Add-Type -AssemblyName System.Windows.Forms
# Create the main form
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "RegExer - PowerShell RegEx Tester"
$Form.Width = 425
$Form.Height = 400
# Prevent resizing by setting the FormBorderStyle to FixedSingle
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
# Create a label for regex input
$RegexLabel = New-Object System.Windows.Forms.Label
$RegexLabel.Text = "Enter a powershell style regex pattern:"
$RegexLabel.Location = New-Object System.Drawing.Point(10, 10)
$RegexLabel.Height = 20
$RegexLabel.Width = 420
$Form.Controls.Add($RegexLabel)
# Create a text box for regex input
$RegexTextBox = New-Object System.Windows.Forms.TextBox
$RegexTextBox.Location = New-Object System.Drawing.Point(10, 30)
$RegexTextBox.Width = 300
$Form.Controls.Add($RegexTextBox)
# Create a label for text input
$TextLabel = New-Object System.Windows.Forms.Label
$TextLabel.Text = "Enter text to test:"
$TextLabel.Location = New-Object System.Drawing.Point(10, 60)
$TextLabel.Height = 20
$Form.Controls.Add($TextLabel)
# Create a text box for text input
$TextInput = New-Object System.Windows.Forms.TextBox
$TextInput.Location = New-Object System.Drawing.Point(10, 80)
$TextInput.Width = 390
$TextInput.Height = 100
$TextInput.Multiline = $true
$Form.Controls.Add($TextInput)
# Create a label for the results
$ResultsLabel = New-Object System.Windows.Forms.Label
$ResultsLabel.Text = "Results:"
$ResultsLabel.Location = New-Object System.Drawing.Point(10, 190)
$ResultsLabel.Height = 20
$Form.Controls.Add($ResultsLabel)
# Create a text box for displaying results
$ResultsTextBox = New-Object System.Windows.Forms.TextBox
$ResultsTextBox.Location = New-Object System.Drawing.Point(10, 210)
$ResultsTextBox.Width = 390
$ResultsTextBox.Height = 100
$ResultsTextBox.Multiline = $true
$ResultsTextBox.ReadOnly = $true
$Form.Controls.Add($ResultsTextBox)
# Create a button to perform regex matching
$TestButton = New-Object System.Windows.Forms.Button
$TestButton.Text = "Test Regex"
$TestButton.Location = New-Object System.Drawing.Point(330, 30)
$TestButton.Add_Click({
$pattern = $RegexTextBox.Text
$text = $TextInput.Text
if ($text -match $pattern) {
$ResultsTextBox.Text = "Match found: $($matches[0])"
}
else {
$ResultsTextBox.Text = "No match found"
}
})
$Form.Controls.Add($TestButton)
# Show the form
$Form.ShowDialog()
# Clean up resources
$Form.Dispose()
}
#endregion =======================================================================================================================================================================
#region ===== Convert To Unix/Dos Line Endings ===================================================================================================================================
function dos2unix ($infile, $outfile) {
(Get-Content -raw $infile) -replace "`r`n","`n" |
Set-Content -nonewline $outfile
}
function unix2dos ($infile, $outfile) {
(Get-Content -raw $infile) -replace "(?<!`r)`n","`r`n" |
Set-Content -nonewline $outfile
}
#endregion =======================================================================================================================================================================
#region ===== Copy A File and all folders leading up to it as a Clipboard Drop ===================================================================================================
function DeepCopy {
#Creates a clipboard copy of the file if found, and the folder structure leading up to it
param(
[string]$Path = (Get-Location),
[string]$FileName
)
$destinationPath = "C:\temp\DeepCopy"
$innerDestinationPath = "C:\temp\DeepCopy\*"
function Copy-Folders-And-File($currentPath, $fileToCopy) {
if ($currentPath -like "$invocationPath*") {
$relativePath = $currentPath -replace [regex]::Escape($invocationPath), ""
$destinationFolder = Join-Path -Path $destinationPath -ChildPath $relativePath
New-Item -Path $destinationFolder -ItemType Directory -Force
$destinationFile = Join-Path -Path $destinationFolder -ChildPath $fileToCopy.Name
Copy-Item -Path $fileToCopy.FullName -Destination $destinationFile -Force
}
}
$invocationPath = (Get-Location).Path
$files = Get-ChildItem -Path $Path -Recurse -File -Filter $FileName
foreach ($file in $files) {
$fileDirectory = $file.DirectoryName
Copy-Folders-And-File -currentPath $fileDirectory -fileToCopy $file
}
# Create a clipboard file drop for the C:\DeepCopy folder and its contents
Add-Type -AssemblyName System.Windows.Forms
$dataObject = New-Object System.Windows.Forms.DataObject
$dataObject.SetFileDropList(@($innerDestinationPath))
[System.Windows.Forms.Clipboard]::SetDataObject($dataObject)
}
function Clear-DeepCopyCache {
#Cache Cleaning (Paste operation breaks if source is deleted):
Remove-Item C:\temp\DeepCopy\* -Recurse -Force
Timeout /NoBreak 2
}
#endregion =======================================================================================================================================================================
#region ===== HashString =========================================================================================================================================================
Function HashString {
<#
.SYNOPSIS
Generates a hash with the MD5 HashAlgorithm or with another supported HashAlgorithm.
See System.Security.Cryptography.HashAlgorithm for more information.
.DESCRIPTION
This function takes the supplied string and generates a HashAlgorithm with it. Function defaults to MD5 hashing if no -a paramter
is supplied with a supported System.Security.Cryptography.HashAlgorithm.
.PARAMETER <inputString>
Specifies the string you want to hash.
.PARAMETER <a>
Specifies the System.Security.Cryptography.HashAlgorithm you want to hash your string with.
.EXAMPLE
HashString "Hello, World!"
PS C:\>65A8E27D8879283831B664BD8B7F0AD4
Description
-----------
Hashes "Hello, World!" with the MD5 HashAlgorithm
.EXAMPLE
HashString -inputString "Hello, World!" -a "SHA256"
PS C:\>DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F
Description
-----------
Hashes "Hello, World!" with the SHA256 HashAlgorithm
.EXAMPLE
"Hello, World!" | HashString -a "SHA256"
PS C:\>DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F
Description
-----------
Hashes "Hello, World!" with the SHA256 HashAlgorithm using a pipeline supplied string.
.NOTES
FunctionName : HashString
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
.LINK
My personal GitHub profile:
https://github.com/joaf123
My personal Gist profile:
https://gist.github.com/joaf123
#>
param(
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[String] $inputString,
[String] $a = "MD5"
)
$bytes = [System.Text.Encoding]::UTF8.GetBytes($inputString)
$algorithm = [System.Security.Cryptography.HashAlgorithm]::Create($a)
$StringBuilder = New-Object System.Text.StringBuilder
$algorithm.ComputeHash($bytes) |
ForEach-Object {
$null = $StringBuilder.Append($_.ToString("x2"))
}
$StringBuilder.ToString().ToUpper()
}
#endregion =======================================================================================================================================================================
#region ===== HashString: md5sum Alias ===========================================================================================================================================
Function md5sum([parameter(Mandatory = $true, ValueFromPipeline = $true)][String] $inputString) {
<#
.SYNOPSIS
Unix style md5sum alias for HashString function.
.DESCRIPTION
Takes the supplied string and generates an MD5 hash of it.
.NOTES
FunctionName : md5sum
Created by : Joachim Fosse
Date Coded : 30.09.2021
.EXAMPLE
md5sum "Hello, World!"
PS C:\>65A8E27D8879283831B664BD8B7F0AD4
Description
-----------
Hashes "Hello, World!" with the MD5 HashAlgorithm
.EXAMPLE
"Hello, World!" | md5sum
PS C:\>65A8E27D8879283831B664BD8B7F0AD4
Description
-----------
Hashes "Hello, World!" with the MD5 HashAlgorithm using a pipeline supplied string.
.LINK
My personal GitHub profile:
https://github.com/joaf123
My personal Gist profile:
https://gist.github.com/joaf123
#>
HashString -a "MD5" $inputString
}
#endregion =======================================================================================================================================================================
#region ===== Get Query Content ==================================================================================================================================================
function GetXSDQuery {
<#
.SYNOPSIS
Get the content of a query in an XSD file.
.DESCRIPTION
This function takes a path to an XSD file and a string to search for in the file. It then returns the content of the query in the XSD file.
.NOTES
FunctionName : GetXSDQuery
Created by : Joachim Fosse
More info : https://github.com/joaf123
.PARAMETER Path
The path to the XSD file.
.PARAMETER queryName
The name of the query to search for in the XSD file.
.EXAMPLE
GetXSDQuery -Path "C:\Users\joach\Documents\query.xsd" -queryName "QueryName"
Example XSD Markup
-----------------------------------------------------------------------------
<DbSource Name="QueryName">SELECT * FROM SOMETHING</DbSource>
Description
-----------------------------------------------------------------------------
Searches for the query with the name "QueryName" in the XSD file located at "C:\Users\joach\Documents\query.xsd".
Returns
-----------------------------------------------------------------------------
SELECT * FROM SOMETHING
#>
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
Position = 0
)]
[string]$Path,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
Position = 1
)]
[string]$queryName
)
$content = Get-Content -Raw -Path "$Path.xsd"
$regex = "(" + [regex]::Escape('"') + "$queryName" + [regex]::Escape('"') + ")(?s)(?!.*\" + [regex]::Escape('"') + "$queryName" + [regex]::Escape('"') + ")(.+?)(<\/DbSource)"
$_matches = Select-String -InputObject $content -Pattern $regex -AllMatches | Foreach-Object { $_.Matches } | Foreach-Object { $_.Value }
return $_matches
}
#endregion =======================================================================================================================================================================
#region ===== Extract Docx Archives ==============================================================================================================================================
function Unpack-Docx-Archives {
<#
.SYNOPSIS
Unpack each Docx. archive in the current folder.
.DESCRIPTION
Extracts the contents of every docx archive inside the current folder, to a folder with the same name as the archive.
.NOTES
FunctionName : ExtractAllDocxArchives
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
#>
7z x *.docx -o*
}
function Unpack-Docx-Archives-Recursive{
<#
.SYNOPSIS
Unpack every Docx. archive in each subfolder of the current folder.
.DESCRIPTION
Extracts the contents of every docx archive inside the current folder, to a folder with the same name as the archive.
.NOTES
FunctionName : ExtractAllDocxArchivesFromSubfolder
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
#>
$initpath = Get-Location
foreach ($folder in Get-ChildItem) {
if ($folder.Attributes -eq "Directory") {
Set-Location $folder.FullName
7z x *.docx -o*
}
}
Set-Location $initpath
7z x *.docx -o*
}
function Unpack-Docx {
param (
[Parameter(Mandatory=$false, ValueFromPipeline = $true)]
[switch]$r
)
if ($r) {
Unpack-Docx-Archives-Recursive
} else {
Unpack-Docx-Archives
}
}
#===========================================================================================================================================================================
#====== Repack Docx Archives ===============================================================================================================================================
function Repack-Docx-Archives {
<#
.SYNOPSIS
Repacks every .docx archive in the current folder.
Example folder structure that calls for use of this function instead of "RepackAllDocxArchivesInSubfolders":
Root / Active Folder
|____Folder representing .docx file
|____.Docx XML Files
.DESCRIPTION
Repacks the contents of every subfolder representing a docx archive in the current folder back to a .docx archive
.NOTES
FunctionName : RepackAllDocxArchives
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
#>
$initpath = Get-Location
foreach ($folder in Get-ChildItem -Directory) {
$archivePath = Join-Path -Path $initpath -ChildPath ($folder.Name + '.docx')
Set-Location $folder.FullName
if (Test-Path $archivePath) {
Remove-Item -Path $archivePath
7z a -tzip $archivePath *
}
if (Test-Path $archivePath) {
Set-Location $initpath
[IO.Directory]::Delete($folder.FullName, $true)
}
}
Set-Location $initpath
}
function Repack-Docx-Archives-Recursive {
<#
.SYNOPSIS
Repacks every nested .docx archive subfolder in the current location.
Example folder structure that calls for use of this function instead of "RepackAllDocxArchives":
Root / Active Folder
|____SubFolder
|____Folder representing .docx file
|____.Docx XML Files
.DESCRIPTION
Repacks the contents of every subfolder representing a docx archive in the current folder back to a .docx archive
.NOTES
FunctionName : RepackAllDocxArchivesInSubfolders
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
#>
RepackAllDocxArchives
$initpath = Get-Location
foreach ($folder in Get-ChildItem) {
if ($folder.Attributes -eq "Directory") {
Set-Location $folder.FullName
foreach ($subFolder in Get-ChildItem) {
if ($subFolder.Attributes -eq "Directory") {
Set-Location $subFolder.FullName
$archivePath = $subFolder.Name + '.docx'
if (Test-Path $archivePath) {
Remove-Item -Path $archivePath
}
7z a -tzip $archivePath *
Get-ChildItem *.docx -Recurse | Move-Item -force -Destination $folder.FullName
$folderToDelte = $folder.FullName + '\' + $subFolder.Name
Set-Location $folder.FullName
[IO.Directory]::Delete($folderToDelte, $true)
}
}
}
}
Set-Location $initpath
}
function Repack-Docx {
param (
[Parameter(Mandatory=$false, ValueFromPipeline = $true)]
[switch]$r
)
if ($r) {
Repack-Docx-Archives-Recursive
} else {
Repack-Docx-Archives
}
}
#endregion =======================================================================================================================================================================
#region ===== Image Tools =============================================================================================================================================
function Find-And-Replace-Image{
<#
.SYNOPSIS
Finds images with the same name and hash as a specified old image and replaces them with a new image.
.DESCRIPTION
This function searches for images in a specified directory and its subdirectories that have the same name as the old image.
It then compares the hash of these images with the hash of the old image. If the hashes match, the old image is replaced
with a new image specified by the user.
.PARAMETER oldImagePath
The full path to the old image file that will be used to find matching files. This file's hash will be compared to the hashes
of files in the target directory.
.PARAMETER newImagePath
The full path to the new image file that will replace the old image files if their hashes match.
.PARAMETER targetDir
The directory where the function will search for images with the same name as the old image. If not specified, it defaults
to the current directory from which the function is invoked.
.EXAMPLE
Find-And-Replace-Image -oldImagePath "C:\path\to\old\image.jpg" -newImagePath "C:\path\to\new\image.jpg" -targetDir "C:\path\to\search\directory"
Searches for all images named "image.jpg" in "C:\path\to\search\directory" and replaces them with "C:\path\to\new\image.jpg"
if their content matches the old image.
.EXAMPLE
Find-And-Replace-Image -oldImagePath "C:\path\to\old\image.jpg" -newImagePath "C:\path\to\new\image.jpg"
Searches for all images named "image.jpg" in the current directory and its subdirectories, replacing them with
"C:\path\to\new\image.jpg" if their content matches the old image.
.NOTES
File hashes are compared using the SHA256 algorithm for accurate content comparison.
This function assumes that the new image will be the exact file used to replace the old images.
#>
param (
[string]$oldImagePath,
[string]$newImagePath,
[string]$targetDir = $(Get-Location) # Default to current directory if no target directory is provided
)
# Get the name of the old image file (without the path)
$oldImageName = [System.IO.Path]::GetFileName($oldImagePath)
# Calculate the hash of the old image
$oldImageHash = Get-FileHash $oldImagePath -Algorithm SHA256
# Search for files with the same name as the old image in the target directory
Get-ChildItem -Path $targetDir -Recurse -Filter $oldImageName | ForEach-Object {
# Calculate the hash of the current file
$currentFileHash = Get-FileHash $_.FullName -Algorithm SHA256
# Compare the hash of the current file with the hash of the old image
if ($currentFileHash.Hash -eq $oldImageHash.Hash) {
Write-Host "Replacing $($_.FullName) with $newImagePath"
# Replace the matching file with the new image
Copy-Item -Path $newImagePath -Destination $_.FullName -Force
}
}
}
function Base64ToJpeg() {
param(
[Parameter(Mandatory = $true, Position = 0)]
$inputFile,
[Parameter(Mandatory = $true, Position = 1)]
$outputFile
)
$currentFolder = Get-Location;
$outputPath = [IO.Path]::Combine($currentFolder, $outputFile)
$b64 = Get-Content($inputFile);
$bytes = [System.Convert]::FromBase64String($b64);
[System.IO.File]::WriteAllBytes($outputPath, $bytes);
Write-Output "Done"
}
function Convert-Image-To-Webp {
<#
.SYNOPSIS
Converts an image to .Webp format.
.DESCRIPTION
Converts Images to .Webp format. It looks for png's by default but this can be changed by piping from get-childitem
.NOTES
FunctionName : HashString
Created by : Joachim Fosse
Date Coded : 30.09.2021
More info : https://github.com/joaf123
#>
# Param
param([Parameter(Mandatory = $false, ValueFromPipeline = $true)] $Path)
process {
if (!($Path)) {
$Path = get-childitem -Filter "*.png"
}
$Path | ForEach-Object {
$FilePath = [IO.Path]::ChangeExtension($_.FullName, '.webp');
cwebp $_.FullName -o $FilePath
}
}
}
#endregion =======================================================================================================================================================================
#region ===== Google Search Function and Alias ===================================================================================================================================
function googleSearch { Start-Process www.google.com/search?q=$args }
set-alias gQ googleSearch
#endregion =======================================================================================================================================================================
#region ===== Chocolatey profile =================================================================================================================================================
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
#endregion =======================================================================================================================================================================
#region ===== Microsoft PowerToys CommandNotFound Module =========================================================================================================================
#f45873b3-b655-43a6-b217-97c00aa0db58 PowerToys CommandNotFound module
Import-Module -Name Microsoft.WinGet.CommandNotFound
#f45873b3-b655-43a6-b217-97c00aa0db58
#endregion =======================================================================================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment