Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Last active July 6, 2024 03:59
Show Gist options
  • Save Abhinav1217/bf42ed4c06ac374d2168c8ceb247433b to your computer and use it in GitHub Desktop.
Save Abhinav1217/bf42ed4c06ac374d2168c8ceb247433b to your computer and use it in GitHub Desktop.
a basic $PROFILE for powershell
#
# @author Abhinav Kulshreshtha
# @license The Unlicensed
#
# If you get the error: "Running scripts is disabled on this system" when loading the Profile:
# From a PowerShell window opened As Administrator:
# > Set-ExecutionPolicy RemoteSigned
# Select "Y"1
# https://tecadmin.net/powershell-running-scripts-is-disabled-system/
# Define an alias
#
# Set-Alias -Name backup-svn -Value {
# Param(
# [Alias('S')]
# [Parameter(Mandatory = $true)]
# [string] $SourcePath,
# [Alias('D')]
# [Parameter(Mandatory = $true)]
# [string] $DestinationPath
# )
#
# $ExcludePatterns = @("*.svn*", "obj", "bin")
# Get-ChildItem -Path $SourcePath -File -Recurse -Exclude $ExcludePatterns |
# Compress-Archive -DestinationPath $DestinationPath
# }
#region Setup and Import
# Check if PSReadLine module is available
if (-not (Get-Module -Name PSReadLine -ListAvailable)) {
# Install the PSReadLine module
Install-Module -Name PSReadLine -Scope CurrentUser -Force -AllowClobber
# Import the PSReadLine module
Import-Module PSReadLine
}
# PSUtil - https://github.com/PowershellFrameworkCollective/PSUtil
# Check if PSUtil module is available
if (-not (Get-Module -Name PSUtil -ListAvailable)) {
# Install the PSUtil module
Install-Module -Name PSUtil -Scope CurrentUser -Force -AllowClobber
# Import the PSUtil module
Import-Module PSUtil
}
# BurntToast - https://github.com/Windos/BurntToast
# Check if BurntToast module is available
if (-not (Get-Module -Name BurntToast -ListAvailable)) {
# Install the BurntToast module
Install-Module -Name BurntToast -Scope CurrentUser -Force -AllowClobber
# Import the BurntToast module
Import-Module BurntToast
}
# SimplySql - https://github.com/mithrandyr/SimplySql
# Check if SimplySql module is available
if (-not (Get-Module -Name SimplySql -ListAvailable)) {
# Install the SimplySql module
Install-Module -Name SimplySql -Scope CurrentUser -Force -AllowClobber
# Import the SimplySql module
Import-Module SimplySql
}
# Don't add sensitive stuff to history
Set-PSReadLineOption -AddToHistoryHandler {
param([string]$line)
$sensitive = "password|asplaintext|token|key|secret|hook|webhook"
return ($line -notmatch $sensitive)
}
# Some VSCode stuff
#if ($psEditor) { Import-Module EditorServicesCommandSuite }
# turn off that annoying beep
Set-PSReadlineOption -BellStyle None
Import-Module 'gsudoModule.psd1'
Set-Alias 'sudo' 'Invoke-gsudo'
#endregion
# Search command history for a perticular command text snippet.
Function Grep-History {
# Default value if
param ( [string]$Text = "*" )
Get-History | Where-Object CommandLine -like "*$Text*"
}
# a dirt poor grep implementation.
function grep {
Write-Output "You're looking for this command: Select-String -Pattern ""error"" -Path ""C:\temp\log\*.log\"""
if ($args[0]) {
Write-Output "... but let me 'grep' that for you anyway"
$search = $args[0]
$path = "*.*"
if ($args[1]) { $path = $args[1]}
Select-String -Pattern ($search) -Path ($path)
}
}
#region Persistant command history in Powershell (Because this poor guy doesn't have any)
# $historyFile = "$HOME/.local/share/powershell/PSReadLine/consolehost_history.txt"
#$historyFile = "C:/history-file.csv"
# Function to export command history to file
#Function Export-CommandHistory {
# Get-History | Select-Object -Property CommandLine | Sort-Object -Unique |
# Export-Csv -Path $historyFile -NoTypeInformation
#}
# Function to import command history from file
#Function Import-CommandHistory {
# if (Test-Path $historyFile) {
# $history = Import-Csv -Path $historyFile -Delimiter "`t" | Select-Object -ExpandProperty CommandLine
# $uniqueHistory = $history | Select-Object -Unique
# $uniqueHistory | ForEach-Object { Add-History -InputObject $_ }
# }
#}
#Trim History file.
#Function Trim-History {
# if (Test-Path $historyFile) {
# $uniqueHistory = Get-Content $historyFile | Select-Object -Unique
# $uniqueHistory | Set-Content $historyFile
# Write-Output "Command history file trimmed."
# } else {
# Write-Output "Command history file not found."
# }
#}
# Export command history when exiting PowerShell
# $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
# Export-CommandHistory
# }
# Import command history when launching PowerShell
#Import-CommandHistory
#endregion
#region Another attempt to try to give this poor guy some persistant history capabilities
# Persistent History
# Save last 200 history items on exit
$MaximumHistoryCount = 20000
$historyPath = Join-Path (split-path $profile) history.clixml
# Hook PowerShell's exiting event & hide the registration with -supportEvent
Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action {
Get-History -Count $MaximumHistoryCount | Export-Clixml $historyPath
}
# Load previous history, if it exists
if ((Test-Path $historyPath)) {
Import-Clixml $historyPath | Add-History
}
#endregion
#region Some common posix compliant shims
# Emulate the posix's which command
function which($cmd) { (Get-Command $cmd).Definition }
# Emulate whoami command
#function whoami { (get-content env:\userdomain) + "\" + (get-content env:\username) }
# Check if the wget2 command is available, Then set an alias to wget.
if (Get-Command -Name wget2 -ErrorAction SilentlyContinue) {
# If wget2 command is available, set the alias
Set-Alias -Name wget -Value wget2
}
# techie007 post, last comment https://superuser.com/questions/502374/equivalent-of-linux-touch-to-create-an-empty-file-with-powershell
function touch {
if(!$args[0])
{
Write-Output "You forgot to provide a file name, so I can't create anything."
continue
}
if((Test-Path -Path ($args[0])) -eq $false) {
Set-Content -Path ($args[0]) -Value ($null)
}
else {
(Get-Item ($args[0])).LastWriteTime = Get-Date
}
}
# Check if zoxide is available
if (Get-Command zoxide -ErrorAction SilentlyContinue) {
# Set alias 'cd' to 'z'
Set-Alias -Name cd -Value z -Option AllScope
}
# to reload your PowerShell profile
function reload {
. $PROFILE
Write-Host "$profile reloaded"
}
function Pl-Open {
param (
[Parameter(Mandatory=$false)]
[string]$Path = "."
)
Invoke-Item $Path
}
Set-Alias open Pl-Open
#endregion
#region Setting up softwares
# Common installation paths for Notepad++
$notepadPlusPlusPaths = @("C:\Program Files (x86)\Notepad++\notepad++.exe", "C:\Program Files\Notepad++\notepad++.exe")
# Check each path to see if Notepad++ is installed
foreach ($path in $notepadPlusPlusPaths) {
if (Test-Path $path) {
function Open-WithNPP ($filePath) {
& $path $filePath
}
#set a simpler alias for above function because windows is crap.
Set-Alias -Name npp -Value Open-WithNPP
# replace notepad with notepad++
function notepad {
Start-Process -FilePath $path $args[0]
}
break
}
}
# setup zoxide if it exists
if ((Get-Command zoxide -ErrorAction SilentlyContinue)) {
Invoke-Expression (& { (zoxide init powershell | Out-String) })
}
#endregion
#region PID management
function whoisPID($port) {
Write-Host "Process using this port is..." -ForegroundColor DarkGreen
$Private:localPid = (netstat -ano | grep $port | awk '{print $NF}'|awk 'FNR == 1 {print}')
Write-Host "$localPid" -ForegroundColor DarkGreen
tasklist | grep "$localPid"
}
Set-Alias whois whoisPID
function killPID($port) {
Write-Host "killing process using this port..." -ForegroundColor DarkGreen
$Private:localPid = (netstat -ano | grep $port | awk '{print $NF}'|awk 'FNR == 1 {print}')
tasklist | grep "$localPid"
TASKKILL /PID $localPid /F
Write-Host "Killing $localPid done" -ForegroundColor DarkGreen
}
Set-Alias killP killPID
#endregion
#region Utility commands
# Put this into your PS profile, execute from cmd.exe:
# notepad.exe %USERPROFILE%\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
# notepad.exe %USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# Because there is never enough Telemetry ...
function Telefucktry-Optout() {
# powershell telemetry
[System.Environment]::SetEnvironmentVariable("POWERSHELL_CLI_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_CLI_TELEMETRY_OPTOUT","1","User")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT","1","User")
# powershell updatechecks
[System.Environment]::SetEnvironmentVariable("POWERSHELL_UPDATECHECK","Off","Machine")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_UPDATECHECK","Off","User")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_UPDATECHECK_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("POWERSHELL_UPDATECHECK_OPTOUT","1","User")
# pwsh telemetry
[System.Environment]::SetEnvironmentVariable("PWSH_CLI_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("PWSH_CLI_TELEMETRY_OPTOUT","1","User")
[System.Environment]::SetEnvironmentVariable("PWSH_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("PWSH_TELEMETRY_OPTOUT","1","User")
# pwsh updatechecks
[System.Environment]::SetEnvironmentVariable("PWSH_UPDATECHECK","Off","Machine")
[System.Environment]::SetEnvironmentVariable("PWSH_UPDATECHECK","Off","User")
[System.Environment]::SetEnvironmentVariable("PWSH_UPDATECHECK_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("PWSH_UPDATECHECK_OPTOUT","1","User")
# dotnet telemetry
[System.Environment]::SetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT","1","User")
[System.Environment]::SetEnvironmentVariable("DOTNET_TELEMETRY_OPTOUT","1","Machine")
[System.Environment]::SetEnvironmentVariable("DOTNET_TELEMETRY_OPTOUT","1","User")
# complus telemetry
[System.Environment]::SetEnvironmentVariable("COMPlus_EnableDiagnostics","0","Machine")
[System.Environment]::SetEnvironmentVariable("COMPlus_EnableDiagnostics","0","User")
# are you fucking kdding me ...
[String]$GlobalTeleDotnet = [System.Environment]::GetEnvironmentVariable("DOTNET_TELEMETRY_OPTOUT","Machine")
[String]$UserTeleDotnet = [System.Environment]::GetEnvironmentVariable("DOTNET_TELEMETRY_OPTOUT","User")
[String]$GlobalTelePowershell = [System.Environment]::GetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT","Machine")
[String]$UserTelePowershell = [System.Environment]::GetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT","User")
[String]$GlobalTelePowershellCli = [System.Environment]::GetEnvironmentVariable("POWERSHELL_CLI_TELEMETRY_OPTOUT","Machine")
[String]$UserTelePowershellCli = [System.Environment]::GetEnvironmentVariable("POWERSHELL_CLI_TELEMETRY_OPTOUT","User")
[String]$GlobalTelePwsh = [System.Environment]::GetEnvironmentVariable("PWSH_TELEMETRY_OPTOUT","Machine")
[String]$UserTelePwsh = [System.Environment]::GetEnvironmentVariable("PWSH_TELEMETRY_OPTOUT","User")
[String]$GlobalTelePwshCli = [System.Environment]::GetEnvironmentVariable("PWSH_CLI_TELEMETRY_OPTOUT","Machine")
[String]$UserTelePwshCli = [System.Environment]::GetEnvironmentVariable("PWSH_CLI_TELEMETRY_OPTOUT","User")
[String]$GlobalTeleDotnetCli = [System.Environment]::GetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT","Machine")
[String]$UserTeleDotnetCli = [System.Environment]::GetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT","User")
[String]$GlobalUpcheckPowershell = [System.Environment]::GetEnvironmentVariable("POWERSHELL_UPDATECHECK","Machine")
[String]$UserUpcheckPowershell = [System.Environment]::GetEnvironmentVariable("POWERSHELL_UPDATECHECK","User")
[String]$GlobalUpcheckPwsh = [System.Environment]::GetEnvironmentVariable("PWSH_UPDATECHECK_OPTOUT","Machine")
[String]$UserUpcheckPwsh = [System.Environment]::GetEnvironmentVariable("PWSH_UPDATECHECK_OPTOUT","User")
[String]$GlobalComPlusDiag = [System.Environment]::GetEnvironmentVariable("COMPlus_EnableDiagnostics","Machine")
[String]$UserComPlusDiag = [System.Environment]::GetEnvironmentVariable("COMPlus_EnableDiagnostics","User")
Write-Host "`n
DOTNET_TELEMETRY_OPTOUT `tMachine $GlobalTeleDotnet`tUser $UserTeleDotnet
POWERSHELL_TELEMETRY_OPTOUT `tMachine $GlobalTelePowershell`tUser $UserTelePowershell
POWERSHELL_CLI_TELEMETRY_OPTOUT `tMachine $GlobalTelePowershellCli`tUser $UserTelePowershellCli
PWSH_TELEMETRY_OPTOUT `tMachine $GlobalTelePwsh`tUser $UserTelePwsh
PWSH_CLI_TELEMETRY_OPTOUT `tMachine $GlobalTelePwshCli`tUser $UserTelePwshCli
DOTNET_CLI_TELEMETRY_OPTOUT `tMachine $GlobalTeleDotnetCli`tUser $UserTeleDotnetCli
POWERSHELL_UPDATECHECK `tMachine $GlobalUpcheckPowershell`tUser $UserUpcheckPowershell
PWSH_UPDATECHECK_OPTOUT `tMachine $GlobalUpcheckPwsh`tUser $UserUpcheckPwsh
COMPlus_EnableDiagnostics `tMachine $GlobalComPlusDiag`tUser $UserComPlusDiag";
}
#endregion
# Clear up screen
#clear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment