Skip to content

Instantly share code, notes, and snippets.

@perXautomatik
Forked from LittleNewton/Microsoft.PowerShell_profile.ps1
Last active February 14, 2024 10:33
Show Gist options
  • Save perXautomatik/a030dae32c0a6b86a8099ce04eb58586 to your computer and use it in GitHub Desktop.
Save perXautomatik/a030dae32c0a6b86a8099ce04eb58586 to your computer and use it in GitHub Desktop.
PowerShell 7.1 启动命令
# Auto detect text files and perform LF normalization
* text=auto
*/
Modules/*
Microsoft.PowerShell_profile.ps1
[submodule "Modules"]
path = Modules
url = https://github.com/perXautomatik/PowerShell-Scripts.git
branch = Modules
[submodule "Snipps/EnvPath"]
path = Snipps/EnvPath
url = https://gist.github.com/2281de51f26338d8e273b0161785ed72
[submodule "Snipps"]
path = Snipps
url = https://github.com/perXautomatik/Ps1-PowerShellModule.git

The Goods

PowerShell Profile

My PS Scripts

  • Add helper functions (uptime, reload-profile, find-file, unzip, and print-path)
  • Add equivalents for my favorite Unix commands (df, sed, sed-recursive, grep, grepv, which, export, pkill, pgrep, touch, sudo, pstree)
  • Add Git aliases (gc for git checkout, gp for git pull)
  • Set the default output to utf8
  • Increase the linme history to 10000 Get-FolderAccess screenshot: http://i.imgur.com/21LhwVy.jpg

Copy-File screenshot: http://imgur.com/hT8yoUm.jpg

if ($GLOBAL:PWD -isnot [System.Management.Automation.PathInfo])
{
$GLOBAL:PWD = get-location
}
if ($GLOBAL:CDHIST -isnot [System.Collections.ArrayList])
{
$GLOBAL:CDHIST = [System.Collections.Arraylist]::Repeat($PWD, 1)
}
$cwd = get-location
$count = $GLOBAL:CDHIST.count
if ($args.length -eq 0)
{
set-location $HOME
$GLOBAL:PWD = get-location
$GLOBAL:CDHIST.Remove($GLOBAL:PWD)
if ($GLOBAL:CDHIST[0] -ne $GLOBAL:PWD)
{
$GLOBAL:CDHIST.Insert(0,$GLOBAL:PWD)
}
}
elseif ($args[0] -like "-[0-9]*")
{
$num = $args[0].Replace("-","")
$GLOBAL:PWD = $GLOBAL:CDHIST[$num]
set-location $GLOBAL:PWD
$GLOBAL:CDHIST.RemoveAt($num)
$GLOBAL:CDHIST.Insert(0,$GLOBAL:PWD)
}
elseif ($args[0] -eq "-l")
{
$start = [System.Math]::Max(0, $count - 50)
for ($i = 0; $i -lt $count; $i++)
{
"{0,6} {1}" -f $i, $GLOBAL:CDHIST[$i].ToString().Replace("Microsoft.PowerShell.Core\FileSystem::","")
}
}
elseif ($args[0] -eq "-")
{
if ($GLOBAL:CDHIST.count -gt 1)
{
$t = $CDHIST[0]
$CDHIST[0] = $CDHIST[1]
$CDHIST[1] = $t
set-location $GLOBAL:CDHIST[0]
$GLOBAL:PWD = get-location
}
}
else
{
set-location "$args"
$GLOBAL:PWD = get-location
for ($i = $count - 1; $i -ge 0; $i--)
{
if ($GLOBAL:PWD.Path -eq $GLOBAL:CDHIST[$i])
{
$GLOBAL:CDHIST.RemoveAt($i)
}
}
$GLOBAL:CDHIST.Insert($GLOBAL:CDHIST.count, $GLOBAL:PWD)
}
$GLOBAL:PWD = get-location
#------------------------------- Styling begin --------------------------------------
if ( (($error.length | group).name -eq $null ) -and (Test-IsInteractive) ) {
Clear-Host # remove advertisements (preferably use -noLogo)
}
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
# Style default PowerShell Console
$shell = $Host.UI.RawUI
$shell.WindowTitle= "PS"
$shell.BackgroundColor = "Black"
$shell.ForegroundColor = "White"
# Load custom theme for Windows Terminal
#Set-Theme LazyAdmin
Write-Host "PSVersion: $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)"
Write-Host "PSEdition: $($PSVersionTable.PSEdition)"
Write-Host "Profile: $PSCommandPath"
Write-Host "admin: $isAdmin"
 if (Test-CommandExists 'search-Everything')
{
function invoke-Everything([string]$filter) { @(Search-Everything -filter $filter -global) }
function invoke-FuzzyWithEverything($searchstring) { menu @(invoke-Everything "ext:exe $searchString") | %{& $_ } } #use whatpulse db first, then everything #todo: sort by rescent use #use everything to find executable for fast execution
function Every-execute ($inputx) { $filter = "ext:exe $inputx" ; $filter } #& (Every-Menu $filter)
function Every-AsHashMap { param( $filter = 'ext:psd1 \module') $q = @{} ; everything $filter | %{@{ name = (get -item $_).name ; time=(get -item $_).LastWriteTime ; path=(get -item $_) } } | sort -object -property time | %{ $q[$_.name] = $_.path } ; $q | select -property values}
function Every-execute { param( $filter = 'regex:".*\\data\\[^\\]*.ahk"',$navigate=$true) Every-Menu | % { if($navigate) {cd ($_ | split -path -parent)} ; . $_ } }
# function Every-Load { param( $psFileFilter = 'convert-xlsx-to-csv.ps1') . ( everythnig $psFileFilter | select -first 1) } ; invoke-expression "ExcelToCsv -File 'D:\unsorted\fannyUtskick.xlsx'"
function Every-Explore { param( $filter = 'ext:exe lasso') ; Every-Menu $filter | % { $path = if(!( Test-Path $_ -PathType Container)) { $_ | split-path -leaf } else {$_} ; explorer $path } }
function Every-Menu { param( $filter) $a= @(invoke-Everything $filter) ; if($a.count -eq 1) {$a} else {menu $a} }
Set-Alias -Name everything -Value invoke-everything
}

# Helper Functions
#######################################################
# src: https://gist.github.com/apfelchips/62a71500a0f044477698da71634ab87b
# New-Item $(Split-Path "$($PROFILE.CurrentUserCurrentHost)") -ItemType Directory -ea 0; Invoke-WebRequest -Uri "https://git.io/JYZTu" -OutFile "$($PROFILE.CurrentUserCurrentHost)"
# ref: https://devblogs.microsoft.com/powershell/optimizing-your-profile/#measure-script
# ref: Powershell $? https://stackoverflow.com/a/55362991
# ref: Write-* https://stackoverflow.com/a/38527767
# Write-Host wrapper for Write-Information -InformationAction Continue
# define these environment variables if not set already and also provide them as PSVariables
if ($isWindows)
{
function Test-IsAdmin { if ( (id -u) -eq 0 ) { return $true } return $false }
}
#src: https://stackoverflow.com/a/34098997/7595318
function Test-IsInteractive {
# Test each Arg for match of abbreviated '-NonInteractive' command.
$NonInteractiveFlag = [Environment]::GetCommandLineArgs() | Where-Object{ $_ -like '-NonInteractive' }
if ( (-not [Environment]::UserInteractive) -or ( $NonInteractiveFlag -ne $null ) ) {
return $false
}
return $true
}
#if ( Test-IsInteractive ) { (preferably use -noLogo) } # Clear-Host # remove advertisements
function Download-Latest-Profile {
New-Item $( Split-Path $($PROFILE.CurrentUserCurrentHost) ) -ItemType Directory -ea 0
if ( $(Get-Content "$($PROFILE.CurrentUserCurrentHost)" | Select-String "62a71500a0f044477698da71634ab87b" | Out-String) -eq "" ) {
Move-Item -Path "$($PROFILE.CurrentUserCurrentHost)" -Destination "$($PROFILE.CurrentUserCurrentHost).bak"
}
Invoke-WebRequest -Uri "https://gist.githubusercontent.com/apfelchips/62a71500a0f044477698da71634ab87b/raw/Profile.ps1" -OutFile "$($PROFILE.CurrentUserCurrentHost)"
Reload-Profile
}
#src: https://devblogs.microsoft.com/scripting/use-a-powershell-function-to-see-if-a-command-exists/
function Test-CommandExists {
Param ($command)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
try { Get-Command $command; return $true }
catch {return $false}
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Clean-Object {
process {
$_.PSObject.Properties.Remove('PSComputerName')
$_.PSObject.Properties.Remove('RunspaceId')
$_.PSObject.Properties.Remove('PSShowComputerName')
}
#Where-Object { $_.PSObject.Properties.Value -ne $null}
}
function Get-Environment { # Get-Variable to show all Powershell Variables accessible via $
if ( $args.Count -eq 0 ) {
Get-Childitem env:
} elseif( $args.Count -eq 1 ) {
Start-Process (Get-Command $args[0]).Source
} else {
Start-Process (Get-Command $args[0]).Source -ArgumentList $args[1..($args.Count-1)]
}
}
function cf {
if ( $null -ne $(Get-Module PSFzf) ) {
Get-ChildItem . -Recurse -Attributes Directory | Invoke-Fzf | Set-Location
} else {
Write-Error "please install PSFzf"
}
}
if ( $(Test-CommandExists 'git') ) {
Set-Alias g git -Option AllScope
function git-root { $gitrootdir = (git rev-parse --show-toplevel) ; if ( $gitrootdir ) { Set-Location $gitrootdir } }
if ( $IsWindows ) {
function git-sh {
if ( $args.Count -eq 0 ) { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") -l
} else { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") $args }
}
function git-bash {
if ( $args.Count -eq 0 ) {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l
} else {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") $args
}
}
function git-vim { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l -c `'vim $args`' }
if ( -Not (Test-CommandExists 'sh') ){ Set-Alias sh git-sh -Option AllScope }
if ( -Not (Test-CommandExists 'bash') ){ Set-Alias bash git-bash -Option AllScope }
if ( -Not (Test-CommandExists 'vi') ){ Set-Alias vi git-vim -Option AllScope }
if ( -Not (Test-CommandExists 'vim') ){ Set-Alias vim git-vim -Option AllScope }
}
}
function Select-Value { # src: https://geekeefy.wordpress.com/2017/06/26/selecting-objects-by-value-in-powershell/
[Cmdletbinding()]
param(
[parameter(Mandatory=$true)] [String] $Value,
[parameter(ValueFromPipeline=$true)] $InputObject
)
process {
# Identify the PropertyName for respective matching Value, in order to populate it Default Properties
$Property = ($PSItem.properties.Where({$_.Value -Like "$Value"})).Name
If ( $Property ) {
# Create Property a set which includes the 'DefaultPropertySet' and Property for the respective 'Value' matched
$DefaultPropertySet = $PSItem.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames
$TypeName = ($PSItem.PSTypenames)[0]
Get-TypeData $TypeName | Remove-TypeData
Update-TypeData -TypeName $TypeName -DefaultDisplayPropertySet ($DefaultPropertySet+$Property |Select-Object -Unique)
$PSItem | Where-Object {$_.properties.Value -like "$Value"}
}
}
}
function pause($message="Press any key to continue . . . ") {
Write-Host -NoNewline $message
$i=16,17,18,20,91,92,93,144,145,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183
while ($null -eq $k.VirtualKeyCode -or $i -Contains $k.VirtualKeyCode){
$k = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
Write-Host ""
}
# native touch implementation
# src: https://ss64.com/ps/syntax-touch.html
function Set-FileTime {
param(
[string[]]$paths,
[bool]$only_modification = $false,
[bool]$only_access = $false
)
begin {
function updateFileSystemInfo([System.IO.FileSystemInfo]$fsInfo) {
$datetime = Get-Date
if ( $only_access ) {
$fsInfo.LastAccessTime = $datetime
} elseif ( $only_modification ) {
$fsInfo.LastWriteTime = $datetime
} else {
$fsInfo.CreationTime = $datetime
$fsInfo.LastWriteTime = $datetime
$fsInfo.LastAccessTime = $datetime
}
}
function touchExistingFile($arg) {
if ( $arg -is [System.IO.FileSystemInfo] ) {
updateFileSystemInfo($arg)
} else {
$resolvedPaths = Resolve-Path $arg
foreach ($rpath in $resolvedPaths) {
if ( Test-Path -type Container $rpath ) {
$fsInfo = New-Object System.IO.DirectoryInfo($rpath)
} else {
$fsInfo = New-Object System.IO.FileInfo($rpath)
}
updateFileSystemInfo($fsInfo)
}
}
}
function touchNewFile([string]$path) {
#$null > $path
Set-Content -Path $path -value $null;
}
}
process {
if ( $_ ) {
if ( Test-Path $_ ) {
touchExistingFile($_)
} else {
touchNewFile($_)
}
}
}
end {
if ( $paths ) {
foreach ( $path in $paths ) {
if ( Test-Path $path ) {
touchExistingFile($path)
} else {
touchNewFile($path)
}
}
}
}
}
if ( $IsWindows ) {
function stree($directory = $pwd) {
$gitrootdir = (Invoke-Command{Set-Location $args[0]; git rev-parse --show-toplevel 2>&1;} -ArgumentList $directory)
if ( Test-Path -Path "$gitrootdir\.git" -PathType Container) {
$newestExe = Get-Item "${env:ProgramFiles(x86)}\Atlassian\SourceTree\SourceTree.exe" | select -Last 1
Write-Debug "Opening $gitrootdir with $newestExe"
Start-Process -filepath $newestExe -ArgumentList "-f `"$gitrootdir`" log"
} else {
Write-Error "git directory not found"
}
}
if ( "${env:ChocolateyInstall}" -eq "" ) {
function Install-Chocolatey {
if (Get-Command choco -ErrorAction SilentlyContinue) {
Write-Error "chocolatey already installed!"
} else {
Start-Process (Get-HostExecutable) -ArgumentList "-Command Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1') -verb RunAs"
}
}
else {
function choco { Start-Process (Get-HostExecutable) -ArgumentList "-noProfile -noLogo -Command choco.exe ${args}; pause" -verb runAs }
}
}
}
function Get-HostExecutable {
if ( $PSVersionTable.PSEdition -eq "Core" ) {
$ConsoleHostExecutable = (get-command pwsh).Source
} else {
$ConsoleHostExecutable = (get-command powershell).Source
}
return $ConsoleHostExecutable
}
# don't override chocolatey sudo or unix sudo
if ( -not $(Test-CommandExists 'sudo') ) {
function sudo() {
if ( $args.Length -eq 0 ) {
Start-Process $(Get-HostExecutable) -verb "runAs"
} elseif ( $args.Length -eq 1 ) {
Start-Process $args[0] -verb "runAs"
} else {
Start-Process $args[0] -ArgumentList $args[1..$args.Length] -verb "runAs"
}
}
}
function uptimef {
Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime';
EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
}
function find-file($name) {
ls -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | foreach {
$place_path = $_.directory
echo "${place_path}\${_}"
}
}
function unzipf ($path) {
$dirname = (Get-Item $path).Basename
echo("Extracting", $path, "to", $dirname)
New-Item -Force -ItemType directory -Path $dirname
expand-archive $path -OutputPath $dirname -ShowProgress
}
# already expanded to save time https://github.com/nvbn/thefuck/wiki/Shell-aliases#powershell
if ( $(Test-CommandExists 'thefuck') ) {
function fuck {
$PYTHONIOENCODING_BKP=$env:PYTHONIOENCODING
$env:PYTHONIOENCODING="utf-8"
$history = (Get-History -Count 1).CommandLine
if (-not [string]::IsNullOrWhiteSpace($history)) {
$fuck = $(thefuck $args $history)
if ( -not [string]::IsNullOrWhiteSpace($fuck) ) {
if ( $fuck.StartsWith("echo") ) { $fuck = $fuck.Substring(5) } else { iex "$fuck" }
}
}
[Console]::ResetColor()
$env:PYTHONIOENCODING=$PYTHONIOENCODING_BKP
}
Set-Alias f fuck -Option AllScope
}
# hacks for old powerhsell versions
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
function Get-ExitBoolean($command) { & $command | Out-Null; $?} ; Set-Alias geb Get-ExitBoolean # fixed: https://github.com/PowerShell/PowerShell/pull/9849
function Use-Default # $var = d $Value : "DefaultValue" eg. ternary # fixed: https://toastit.dev/2019/09/25/ternary-operator-powershell-7/
{
for ($i = 1; $i -lt $args.Count; $i++){
if ($args[$i] -eq ":"){
$coord = $i; break
}
}
if ($coord -eq 0) {
throw new System.Exception "No operator!"
}
if ($args[$coord - 1] -eq ""){
$toReturn = $args[$coord + 1]
} else {
$toReturn = $args[$coord -1]
}
return $toReturn
}
Set-Alias d Use-Default
}
if ( $IsWindows ) {
# src: http://serverfault.com/questions/95431
function Test-IsAdmin { $user = [Security.Principal.WindowsIdentity]::GetCurrent(); return $(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator); }
function Reopen-here { Get-Process explorer | Stop-Process Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command 'Get-Process explorer | Stop-Process'" -verb "runAs"}
function Reset-Spooler { Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command 'Stop-Service -Name Spooler -Force; Get-Item ${env:SystemRoot}\System32\spool\PRINTERS\* | Remove-Item -Force -Recurse; Start-Service -Name Spooler'" -verb "runAs" }
function subl { Start-Process "${Env:ProgramFiles}\Sublime Text\subl.exe" -ArgumentList $args -WindowStyle Hidden } # hide subl shim script
function get-tempfilesNfolders { foreach ($folder in @('C:\Windows\Temp\*', 'C:\Documents and Settings\*\Local Settings\temp\*', 'C:\Users\*\Appdata\Local\Temp\*', 'C:\Users\*\Appdata\Local\Microsoft\Windows\Temporary Internet Files\*', 'C:\Windows\SoftwareDistribution\Download', 'C:\Windows\System32\FNTCACHE.DAT')) {$_} }
function Export-Regestrykey { param ( $reg = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\' ,$outFile = 'H:\hkcu-regbackup.txt' ) get-childitem -path $reg | out-file $outFile }
function start-bc ($REMOTE,$LOCAL,$BASE,$MERGED) { cmd /c "${Env:ProgramFiles}\BeondCompare4\BComp.exe" "$REMOTE" "$LOCAL" "$BASE" "$MERGED" } #todo: replace hardcode with global variable pointing to path
function start-cygwin { param ( $cygwinpath = "${Env:ProgramFiles}\cygwin64\" ) ."$cygwinpath\Cygwin.bat" }
function Compare-ImagesMetadata { param ( $exifToolPath = "${Env:ProgramFiles}\geosetter\tools\" ,$inputA = "E:\Pictures\Badges & Signs & Shablon Art\00 - soulcripple front (2).jpg" ,$inputB = "E:\Pictures\Badges & Signs & Shablon Art\00 - soulcripple front.jpg" ) ; $set1 = .\exiftool.exe -a -u -g1 $inputA ; $set2 = .\exiftool.exe -a -u -g1 $inputB ; Compare-Object $set1 $set2 | select -ExpandProperty inputobject }
function new-SymbolicLink { param ( $where = 'H:\mina grejer\Till Github' ,$from = 'H:\mina grejer\Project shelf\Till Github' ) New-Item -Path $where -ItemType SymbolicLink -Value $from }
}
if (Test-CommandExists 'search-Everything')
{
function invoke-Everything([string]$filter) { @(Search-Everything -filter $filter -global) }
function invoke-FuzzyWithEverything($searchstring) { menu @(everything "ext:exe $searchString") | %{& $_ } } #use whatpulse db first, then everything #todo: sort by rescent use #use everything to find executable for fast execution
function Every-execute ($inputx) { $filter = "ext:exe $inputx" ; $filter } #& (Every-Menu $filter)
function Every-AsHashMap { param( $filter = 'ext:psd1 \module') $q = @{} ; everything $filter | %{@{ name = (get -item $_).name ; time=(get -item $_).LastWriteTime ; path=(get -item $_) } } | sort -object -property time | %{ $q[$_.name] = $_.path } ; $q | select -property values}
function Every-execute { param( $filter = 'regex:".*\\data\\[^\\]*.ahk"',$navigate=$true) Every-Menu | % { if($navigate) {cd ($_ | split -path -parent)} ; . $_ } }
# function Every-Load { param( $psFileFilter = 'convert-xlsx-to-csv.ps1') . ( everythnig $psFileFilter | select -first 1) } ; invoke-expression "ExcelToCsv -File 'D:\unsorted\fannyUtskick.xlsx'"
function Every-Explore { param( $filter = 'ext:exe lasso') ; Every-Menu $filter | % { $path = if(!( Test-Path $_ -PathType Container)) { $_ | split-path -leaf } else {$_} ; explorer $path } }
function Every-Menu { param( $filter) $a= @(everything $filter) ; if($a.count -eq 1) {$a} else {menu $a} }
}
if (Test-CommandExists 'git')
{ #todo: move to git aliases
function invoke-gitCheckout () { & git checkout $args }
function invoke-gitFetchOrig { git fetch origin }
Function invoke-GitLazy($path,$message) { cd $path ; git lazy $message } ;
Function invoke-GitLazySilently {Out-File -FilePath .\lazy.log -inputObject (invoke-GitLazy 'AutoCommit' 2>&1 )} ; #todo: parameterize #todo: rename to more descriptive #todo: breakout
function invoke-gitRemote { param ($subCommand = 'get-url',$name = "origin" ) git remote $subCommand $name }
Function invoke-GitSubmoduleAdd([string]$leaf,[string]$remote,[string]$branch) { git submodule add -f --name $leaf -- $remote $branch ; git commit -am $leaf+$remote+$branch } ; #todo: move to git aliases #Git Ad $leaf as submodule from $remote and branch $branch
}
if ( $null -ne $(Get-Module PSReadline -ea SilentlyContinue)) {
function find-historyAppendClipboard($searchstring) { $path = get-historyPath; menu @( get-content $path | where{ $_ -match $searchstring }) | %{ Set-Clipboard -Value $_ }} #search history of past expressions and adds to clipboard
function find-historyInvoke($searchstring) { $path = get-historyPath; menu @( get-content $path | where{ $_ -match $searchstring }) | %{Invoke-Expression $_ } } #search history of past expressions and invokes it, doesn't register the expression itself in history, but the pastDo expression.
}
function split-fileByLineNr { param( $pathName = '.\gron.csv',$OutputFilenamePattern = 'output_done_' , $LineLimit = 60) ;
$ext = $pathName | split-path -Extension
$inputx = Get-Content ;
$line = 0 ;
$i = 0 ;
$path = 0 ;
$start = 0 ;
while ($line -le $inputx.Length) {
if ($i -eq $LineLimit -Or $line -eq $inputx.Length) {
$path++ ;
$pathname = "$OutputFilenamePattern$path$ext" ;
$inputx[$start..($line - 1)] | Out -File $pathname -Force ;
$start = $line ;
$i = 0 ;
Write-Host "$pathname" ;
} ;
$i++ ;
$line++
}
}
function split-fileByMatch($pathName , $regex) { #param( $pathName = 'C:\Users\crbk01\Documents\WindowsPowerShell\snipps\Modules\Todo SplitUp.psm1' , $regex = '(?<=function\s)[^\s\(]*') ;
$ext = ($pathName | split-path -Extension)
$parent = ($pathName | split-path -Parent)
$OriginalName = ($pathName | split-path -LeafBase)
$inputx = Get-Content $pathName; $line = 0 ; $i = 0 ; $start = @(select-string -path $pathName -pattern $regex ) | select linenumber ; $LineLimit = $start | select -Skip 1 ; $names = @() ; [regex]::matches($inputx,$regex).groups.value | %{$names+= $_ }
$occurence = 0 ;
while ($line -le $inputx.Length) {
if ($i -eq ([int]$LineLimit[$occurence].linenumber -1) -Or $line -eq $inputx.Length)
{
$currentName = $names[$occurence];
$pathname = Join-Path -path $parent -childPath "$OriginalName-$currentName$ext" ;
$u = ([int]$start[$occurence].linenumber -1)
$inputx[$u..($line - 1)] > $pathname
$occurence++ ;
Write-Host "$u..($line - 1)$pathname" ;
};
$i++ ;
$line++
}
}
#function aliasCode { & $env:code }
function .. { Set-Location ".." }
function .... { Set-Location (Join-Path -Path ".." -ChildPath "..") }
function all { process { $_ | Select-Object * } } # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7#piping-objects-to-functions
function cdc { Set-Location "$XDG_CONFIG_HOME" }
function cdcheat { Set-Location "$CHEATS_DIR" }
function cdd { Set-Location "$DESKTOP_DIR" }
function cddd { Set-Location "$DEVEL_DIR" }
function cddev { Set-Location "$DEVEL_DIR" }
function cdn { Set-Location "$NOTES_DIR" }
function cdports { Set-Location "$PORTS_DIR" }
function cdt { Set-Location "$TODO_DIR" }
function clear-Days_Back { param( $path = "C:\Support\SQLBac\" ,$Daysback = "0" ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $CurrentDate = Get-Date $DatetoDelete = $CurrentDate.AddDays($Daysback) Get-ChildItem $path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item }
function ConvertFrom-Bytes { param( [string]$bytes, [string]$savepath ) $dir = Split-Path $savepath if (!(Test-Path $dir)) { md $dir | Out-Null } [convert]::FromBase64String($bytes) | Set-Content $savepath -Encoding Byte }
function ConvertTo-Bytes ( [string]$path ) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } [convert]::ToBase64String((Get-Content $path -Encoding Byte)) }
function df { get-volume }
function enter-dir { param( $path = '%USERPROFILE%\Desktop\' ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } Set-Location $Path }; #if no param, navigate to desktop # 5. 更改工作目录 # 输入要切换到的路径 # 用法示例:cd C:/ # 默认路径:D 盘的桌面
function exit-Nrenter { shutdown /r } #reboot
function export($name, $value) { set-item -force -path "env:$name" -value $value; }
function foldercontain($folder,$name) { $q = get-childitem $folder; return $q -contains $name }
function Get-AllNic { Get-NetAdapter | Sort-Object -Property MacAddress } # 1. 获取所有 Network Interface
function get-Childnames { param( $path = $pwd) (Get-ChildItem -path $path).Name ; Write-Host("") }; # 3. 查看目录 ls & ll
function Get-DefaultAliases { Get-Alias | Where-Object { $_.Options -match "ReadOnly" }}
function get-envVar { Get-Childitem -Path Env:*}
function get-EspHeader { param( $path = '.\FormiD.esp', $max = 13,$headerSize = 3 ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $q = ((( -join (gc $path | select -first $headerSize)) -replace "[^\w. ] {1,}","å").split("å") -match "^.*[.](esp |esm)$") ; $q | ? {($q | select -first $max) -NotContains $_}}
function get-historyPath { (Get-PSReadlineOption).HistorySavePath }
function Get-IPv4Routes { Get-NetRoute -AddressFamily IPv4 | Where-Object -FilterScript {$_.NextHop -ne '0.0.0.0'} } # 2. 获取 IPv4 关键路由
function Get-IPv6Routes { Get-NetRoute -AddressFamily IPv6 | Where-Object -FilterScript {$_.NextHop -ne '::'} } # 3. 获取 IPv6 关键路由
function get-isFolder {$PSBoundParameters -is [system.in.folder]}
function get-parameters { Get-Member -Parameter *}
function get-RegInstallpaths { Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | % { Get -ItemProperty $_.PsPath } | Select DisplayName,InstallLocation }
function get-whatpulse { param( $program,$path) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $query = "select rightstr(path,instr(reverse(path),'/') -1) exe,path from (select max(path) path,max(cast(replace(version,'.','') as integer)) version from applications group by case when online_app_id = 0 then name else online_app_id end)" ; $adapter = newSqliteConnection -source (Everything 'whatpulse.db')[0] -query $query ; $b=@($data.item('exe')) ; $a = @($data.item('path')) ; $i=0 ; while($i -lt $a.Length) {$res[$b[$i]]=$a[$i] ; $i++ } ; $res | where { $_.name -match $program -and $_.path -match $path}}
function grep { process { $_ | Select-String -Pattern $args } } # function grep($regex, $dir) { if ( $dir ) { ls $dir | select-string $regex return } $input | select-string $regex }
function grepv($regex) { $input | ? { !$_.Contains($regex) } }
function Initialize-Profile { . $PROFILE.CurrentUserCurrentHost} #function initialize-profile { & $profile } #reload-profile is an unapproved verb.
function invoke-Nmake { nmake.exe $args -nologo }; # 1. 编译函数 make
function invoke-powershellAsAdmin { Start-Process powershell -Verb runAs } #new ps OpenAsADmin
function join-ByRuncunfig { param( $prefix='[$]APPLICATION_CONFIG_DIR[$][/]'
,$refixReplace='C:\Users\crbk01\AppData\Roaming\JetBrains\DataGrip2021.1\',
$runconfig="TillMinaMedelanden.run.xml",$output='runConfig/Combined.sql') [xml]$xml=get -content $runConfig -Encoding UTF8 ; $xml.component.configuration.'script -file' | %
{$_.value -replace $prefix, ($prefixReplace -replace '\\','/')} | % {" - -:$_"
; get -content -path $_ -Encoding UTF8 ; "go" } >> $output }
function list { process { $_ | Format-List * } } # fl is there by default
function man { Get-Help $args[0] | out-host -paging }
function md { New-Item -type directory -path (Join-Path "$args" -ChildPath "") }
function measure-ExtOccurenseRecursivly { param( $path = "D:\Project Shelf\MapBasic" ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } Get-ChildItem -Path $path -Recurse -File | group Extension -NoElement | sort Count -Descending | select -Property name }
function measure-words { param( $inputStream = (Get -ChildItem | % { Get -Content $_.name }), $regex="[^a-z0-9_-]") $hash = @{} ; $a="" ; $inputStream | % {$a+=$_} ; $a -split $regex | % { $_.tolower()} | % {$hash[$_]++} ; $sorted= % {$hash.GetEnumerator() | sort -object {[int]$_.value}} ; return $sorted} ; $sorted | where{$_.name -notmatch "^\d+$"} | where{$_.name.length -gt 4 }
function mkdir { New-Item -type directory -path (Join-Path "$args" -ChildPath "") }
function My-Scripts { Get-Command -CommandType externalscript }
function open-here { param( $Path = $pwd ) Invoke-Item $Path }; # 4. 打开当前工作目录 # 输入要打开的路径 # 用法示例:open C:\ # 默认路径:当前工作文件夹
function open-ProfileFolder { explorer (split-path -path $profile -parent)}
function pgrep($name) { Get-Process $name }
function pkill($name) { Get-Process $name -ErrorAction SilentlyContinue | kill }
function pull () { & get pull $args }
function read-aliases { Get-Alias | Where-Object { $_.Options -notmatch "ReadOnly" }}
function read-EnvPaths { ($Env:Path).Split(";") }
function read-headOfFile { param( $linr = 10, $path ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } gc -Path $path -TotalCount $linr }
function read-json { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PSCustomObject] $input ) $json = [ordered]@{}; ($input).PSObject.Properties | % { $json[$_.Name] = $_.Value } $json.SyncRoot }
function read-paramNaliases ($command) { (Get-Command $command).parameters.values | select name, @{n='aliases';e={$_.aliases}} }
function read-pathsAsStream { get-childitem | out-string -stream } # filesInFolAsStream ;
function read-uptime { Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime'; EXPRESSION= {$_.ConverttoDateTime($_.lastbootuptime)}} } #doesn't psreadline module implement this already?
function Remove-CustomAliases { Get-Alias | Where-Object { ! $_.Options -match "ReadOnly" } | % { Remove-Item alias:$_ }} # https://stackoverflow.com/a/2816523
function remove-TempfilesNfolders { foreach ($folder in get-tempfilesNfolders) {Remove-Item $folder -force -recurse} }
function Sanatize-path { param( $path='G:\mhk',$replaceChar='_') if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $regex= "[^\)\w \\\ -:.åäöÅÄÖ %\ {,~$\(!@¤£é&=#§]" ; Get -ChildItem $path -Recurse | Where -Object {$_.name -match $regex} | rename -item -newName {$_.name -replace $regex,$replaceChar}}
function sed($path, $find, $replace) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } (Get-Content $path).replace("$find", $replace) | Set-Content $path }
function set-FileEncodingUtf8 ( [string]$path ) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } sc $path -encoding utf8 -value(gc $path) }
function set-x { Set-PSDebug -trace 2}
function set+x { Set-PSDebug -trace 0}
function sort-PathByLvl { param( $inputList) $inputList | Sort {($_ -split '\\').Count}, {$_} -Descending | select -object -first 2 | % { $error.clear() ; try { out -null -input (test -ModuleManifest $_ > '&2>&1' ) } catch { "Error" } ; if (!$error) { $_ } }}
function start-BrowserFlags { vivaldi "vivaldi://flags" } #todo: use standard browser instead of hardcoded
function start-notepad-profile { notepad $profile}
function string { process { $_ | Out-String -Stream } }
function touch($path) { "" | Out-File $path -Encoding ASCII }
function which($name) { Get-Command $name | Select-Object -ExpandProperty Definition } #should use more
Remove-Item alias:ls -ea SilentlyContinue ; function ls { Get-Childitem} # ls -al is musclememory by now so ignore all args for this "alias"
#------------------------------- Functions END -------------------------------
if ( $(Test-CommandExists 'git') ) {
Set-Alias g git -Option AllScope
function git-root { $gitrootdir = (git rev-parse --show-toplevel) ; if ( $gitrootdir ) { Set-Location $gitrootdir } }
if ( $IsWindows ) {
function git-sh {
if ( $args.Count -eq 0 ) { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") -l
} else { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") $args }
}
function git-bash {
if ( $args.Count -eq 0 ) {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l
} else {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") $args
}
}
function git-vim { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l -c `'vim $args`' }
if ( -Not (Test-CommandExists 'sh') ){ Set-Alias sh git-sh -Option AllScope }
if ( -Not (Test-CommandExists 'bash') ){ Set-Alias bash git-bash -Option AllScope }
if ( -Not (Test-CommandExists 'vi') ){ Set-Alias vi git-vim -Option AllScope }
if ( -Not (Test-CommandExists 'vim') ){ Set-Alias vim git-vim -Option AllScope }
}
set-alias GitAdEPathAsSNB invoke-GitSubmoduleAdd -Option AllScope
set-alias -Name:"gitSilently" -Value:"invoke-GitLazySilently" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSingleRemote" -Value:"invoke-gitFetchOrig" -Description:"" -Option:"AllScope"
set-alias -Name:"gitsplit" -Value:"subtree-split-rm-commit" -Description:"" -Option:"AllScope"
set-alias GitUp invoke-GitLazy -Option AllScope
set-alias -Name:"remote" -Value:"invoke-gitRemote" -Description:"" -Option:"AllScope"
}
#------------------------------- Credit to : apfelchips -------------------------------
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
function Install-PowerShellGet { Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command Install-PackageProvider -Name NuGet -Force; Install-Module -Name PowerShellGet -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck; pause" -verb "RunAs"}
}
function Test-ModuleExists {
#retuns module version if exsists else false
Param ($name)
$x = Get-Module -ListAvailable -Name $name
return $x ?? $false
}
#src: https://devblogs.microsoft.com/scripting/use-a-powershell-function-to-see-if-a-command-exists/
function Test-CommandExists {
Param ($command)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
try { Get-Command $command; return $true }
catch {return $false}
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Get-ModulesAvailable {
if ( $args.Count -eq 0 ) {
Get-Module -ListAvailable
} else {
Get-Module -ListAvailable $args
}
}
function Get-ModulesLoaded {
if ( $args.Count -eq 0 ) {
Get-Module -All
} else {
Get-Module -All $args
}
}
function TryImport-Module {
param($name)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
$errorPath = join-path -Path (split-path $profile -Parent) -ChildPath "$name.error.load.log"
try { Import-Module $name && echo "i $name"}
catch { "er.loading $name" ; $error > $errorPath }
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Tryinstall-Module {
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
$errorPath = join-path -Path (split-path $profile -Parent) -ChildPath "$name.error.install.log"
try {
if ( $args.Count -eq 1 ) {
Invoke-Expression "PowerShellGet\Install-Module -Name $args[1] -Scope CurrentUser -Force -AllowClobber"
}
elseif ( $args.Count -eq 2 ) {
Invoke-Expression "PowerShellGet\Install-Module -Name $args[1] -Scope CurrentUser -Force -AllowClobber $args[2]"
}
elseif ($args.count -ne 0)
{
Invoke-Expression "PowerShellGet\Install-Module $args"
}
echo "i $name"
}
catch { "er.installing $name" ; $error > $errorPath }
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Install-MyModules {
Tryinstall-Module 'PSReadLine' -AllowPrerelease
Tryinstall-Module 'posh-git'
Tryinstall-Module 'PSFzf'
Tryinstall-Module 'PSEverything'
Tryinstall-Module 'PSProfiler' # --> Measure-Script
# serialization tools: eg. ConvertTo-HashString / ConvertTo-HashTable https://github.com/torgro/HashData
Tryinstall-Module 'hashdata'
# useful Tools eg. ConvertTo-FlatObject, Join-Object... https://github.com/RamblingCookieMonster/PowerShell
Tryinstall-Module 'WFTools'
# https://old.reddit.com/r/AZURE/comments/fh0ycv/azuread_vs_azurerm_vs_az/
# https://docs.microsoft.com/en-us/microsoft-365/enterprise/connect-to-microsoft-365-powershell
Tryinstall-Module 'AzureAD'
Tryinstall-Module 'Pscx'
Tryinstall-Module 'SqlServer'
if ( $IsWindows ){
# Windows Update CLI tool http://woshub.com/pswindowsupdate-module/#h2_2
# Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
# native alternative: WindowsUpdateProvider\Install-WUUpdates >= Windows Server 2019
Tryinstall-Module 'PSWindowsUpdate'
}
}
Import-Module -Name (join-path -Path (split-path $profile -Parent) -ChildPath "sqlite.ps1")
function Import-MyModules {
if (!( ""-eq "${env:ChocolateyInstall}" )) {
TryImport-Module "${env:ChocolateyInstall}\helpers\chocolateyProfile.psm1"
}
# does not load but test if avialable to speed up load time
# ForEach-Object { TryImport-Module -name $_ } #-parralel for ps 7 does not work currently
$modules = @( 'PowerShellGet', 'PSProfiler', 'hashdata','WFTools','AzureAD','SqlServer','PSWindowsUpdate','echoargs','pscx' )
$modules | ForEach-Object { $null = Test-ModuleExists $_ || "error $_" }
# 引入 posh-git
if ( ($host.Name -eq 'ConsoleHost') -and ($null -ne (Get-Module -ListAvailable -Name posh-git)) )
{ TryImport-Module posh-git }
# 引入 oh-my-posh
TryImport-Module oh-my-posh
if ( (Test-ModuleExists 'oh-my-posh' )) {
Set-PoshPrompt ys
Set-PoshPrompt paradox
}
# 设置 PowerShell 主题
# 引入 ps-read-line # useful history related actions
# example: https://github.com/PowerShell/PSReadLine/blob/master/PSReadLine/SamplePSReadLineProfile.ps1
if ( ($host.Name -eq 'ConsoleHost') -and (Test-ModuleExists 'PSReadLine' )) {
#TryImport-Module PSReadLine
#------------------------------- Set Hot-keys BEGIN -------------------------------
$PSReadLineOptions = @{
PredictionSource = "HistoryAndPlugin"
HistorySearchCursorMovesToEnd = $true
}
Set-PSReadLineOption @PSReadLineOptions
# Set-PSReadLineOption -EditMode Emac
# 每次回溯输入历史,光标定位于输入内容末尾
# 设置 Tab 为菜单补全和 Intellisense
# 设置 Ctrl+d 为退出 PowerShell
# 设置 Ctrl+z 为撤销
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadlineKeyHandler -Chord 'Shift+Tab' -Function Complete
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
#------------------------------- Set Hot-keys END -------------------------------
if ( $(Get-Module PSReadline).Version -ge 2.2 ) {
# 设置预测文本来源为历史记录
Set-PSReadLineOption -predictionsource history -ea SilentlyContinue
}
if ( $null -ne $(Get-Module PSFzf) ) {
#Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
#$FZF_COMPLETION_TRIGGER='...'
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
}
}
}
Import-MyModules; echo "modules imported"
$profileFolder = $home+'\Documents\Powershell\'
#------------------------------- Credit to : apfelchips -------------------------------
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
function Install-PowerShellGet { Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command Install-PackageProvider -Name NuGet -Force; Install-Module -Name PowerShellGet -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck; pause" -verb "RunAs"}
}
function Test-ModuleExists {
#retuns module version if exsists else false
Param ($name)
$x = Get-Module -ListAvailable -Name $name
return $x ?? $false
}
#src: https://devblogs.microsoft.com/scripting/use-a-powershell-function-to-see-if-a-command-exists/
function Test-CommandExists {
Param ($command)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
try { Get-Command $command; return $true }
catch {return $false}
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Get-ModulesAvailable {
if ( $args.Count -eq 0 ) {
Get-Module -ListAvailable
} else {
Get-Module -ListAvailable $args
}
}
function Get-ModulesLoaded {
if ( $args.Count -eq 0 ) {
Get-Module -All
} else {
Get-Module -All $args
}
}
function TryImport-Module {
param($name)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
$errorPath = join-path -Path $profileFolder -ChildPath "$name.error.load.log"
try { Import-Module $name && echo "i $name"}
catch { "er.loading $name" ; $error > $errorPath }
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Tryinstall-Module {
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
$errorPath = join-path -Path $profileFolder -ChildPath "$name.error.install.log"
try {
if ( $args.Count -eq 1 ) {
Invoke-Expression "PowerShellGet\Install-Module -Name $args[1] -Scope CurrentUser -Force -AllowClobber"
}
elseif ( $args.Count -eq 2 ) {
Invoke-Expression "PowerShellGet\Install-Module -Name $args[1] -Scope CurrentUser -Force -AllowClobber $args[2]"
}
elseif ($args.count -ne 0)
{
Invoke-Expression "PowerShellGet\Install-Module $args"
}
echo "i $name"
}
catch { "er.installing $name" ; $error > $errorPath }
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Install-MyModules {
Tryinstall-Module 'PSReadLine' -AllowPrerelease
Tryinstall-Module 'posh-git'
Tryinstall-Module 'PSFzf'
Tryinstall-Module 'PSEverything'
Tryinstall-Module 'PSProfiler' # --> Measure-Script
# serialization tools: eg. ConvertTo-HashString / ConvertTo-HashTable https://github.com/torgro/HashData
Tryinstall-Module 'hashdata'
# useful Tools eg. ConvertTo-FlatObject, Join-Object... https://github.com/RamblingCookieMonster/PowerShell
Tryinstall-Module 'WFTools'
# https://old.reddit.com/r/AZURE/comments/fh0ycv/azuread_vs_azurerm_vs_az/
# https://docs.microsoft.com/en-us/microsoft-365/enterprise/connect-to-microsoft-365-powershell
Tryinstall-Module 'AzureAD'
Tryinstall-Module 'Pscx'
Tryinstall-Module 'SqlServer'
if ( $IsWindows ){
# Windows Update CLI tool http://woshub.com/pswindowsupdate-module/#h2_2
# Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
# native alternative: WindowsUpdateProvider\Install-WUUpdates >= Windows Server 2019
Tryinstall-Module 'PSWindowsUpdate'
}
}
Import-Module -Name (join-path -Path $profileFolder -ChildPath "sqlite.ps1")
function Import-MyModules {
if (!( ""-eq "${env:ChocolateyInstall}" )) {
TryImport-Module "${env:ChocolateyInstall}\helpers\chocolateyProfile.psm1"
}
# does not load but test if avialable to speed up load time
# ForEach-Object { TryImport-Module -name $_ } #-parralel for ps 7 does not work currently
$modules = @( 'PowerShellGet', 'PSProfiler', 'hashdata','WFTools','AzureAD','SqlServer','PSWindowsUpdate','echoargs','pscx' )
$modules | ForEach-Object { $null = Test-ModuleExists $_ || "error $_" }
# 引入 posh-git
if ( ($host.Name -eq 'ConsoleHost') -and ($null -ne (Get-Module -ListAvailable -Name posh-git)) )
{ TryImport-Module posh-git }
# 引入 oh-my-posh
TryImport-Module oh-my-posh
if ( (Test-ModuleExists 'oh-my-posh' )) {
Set-PoshPrompt ys
Set-PoshPrompt paradox
}
# 设置 PowerShell 主题
# 引入 ps-read-line # useful history related actions
# example: https://github.com/PowerShell/PSReadLine/blob/master/PSReadLine/SamplePSReadLineProfile.ps1
if ( ($host.Name -eq 'ConsoleHost') -and (Test-ModuleExists 'PSReadLine' )) {
#TryImport-Module PSReadLine
#------------------------------- Set Hot-keys BEGIN -------------------------------
$PSReadLineOptions = @{
PredictionSource = "HistoryAndPlugin"
HistorySearchCursorMovesToEnd = $true
}
Set-PSReadLineOption @PSReadLineOptions
# Set-PSReadLineOption -EditMode Emac
# 每次回溯输入历史,光标定位于输入内容末尾
# 设置 Tab 为菜单补全和 Intellisense
# 设置 Ctrl+d 为退出 PowerShell
# 设置 Ctrl+z 为撤销
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadlineKeyHandler -Chord 'Shift+Tab' -Function Complete
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
#------------------------------- Set Hot-keys END -------------------------------
if ( $(Get-Module PSReadline).Version -ge 2.2 ) {
# 设置预测文本来源为历史记录
Set-PSReadLineOption -predictionsource history -ea SilentlyContinue
}
if ( $null -ne $(Get-Module PSFzf) ) {
#Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
#$FZF_COMPLETION_TRIGGER='...'
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
}
}
}
The MIT License (MIT)
Copyright (c) 2022 Christoffer Brobäck
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#sqlite dll
$workpath = "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll" ;
if ( $(Test-CommandExists 'everything') ) {$alternative = (everything 'wfn:System.Data.SQLite.DLL')[0] ;}
$p = if(Test-Path $workpath){$workpath} else {$alternative} ;
$p = $p ?? 'unable to set path'
if( Test-Path $p )
{
Add-Type -Path $p
echo $p
}
#ps setHistorySavePath
if (-not $env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME = Join-Path -Path "$HOME" -ChildPath ".config" }; $XDG_CONFIG_HOME = $env:XDG_CONFIG_HOME
if (-not $env:XDG_DATA_HOME) { $env:XDG_DATA_HOME = Join-Path -Path "$HOME" -ChildPath ".local/share" }; $XDG_DATA_HOME = $env:XDG_DATA_HOME
if (-not $env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME = Join-Path -Path "$HOME" -ChildPath ".cache" }; $XDG_CACHE_HOME = $env:XDG_CACHE_HOME
if (-not $env:DESKTOP_DIR) { $env:DESKTOP_DIR = Join-Path -Path "$HOME" -ChildPath "desktop" }; $DESKTOP_DIR = $env:DESKTOP_DIR
if (-not $env:NOTES_DIR) { $env:NOTES_DIR = Join-Path -Path "$HOME" -ChildPath "notes" }; $NOTES_DIR = $env:NOTES_DIR
if (-not $env:CHEATS_DIR) { $env:CHEATS_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "cheatsheets" }; $CHEATS_DIR = $env:CHEATS_DIR
if (-not $env:TODO_DIR) { $env:TODO_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "_ToDo" }; $TODO_DIR = $env:TODO_DIR
if (-not $env:DEVEL_DIR) { $env:DEVEL_DIR = Join-Path -Path "$HOME" -ChildPath "devel" }; $DEVEL_DIR = $env:DEVEL_DIR
if (-not $env:PORTS_DIR) { $env:PORTS_DIR = Join-Path -Path "$HOME" -ChildPath "ports" }; $PORTS_DIR = $env:PORTS_DIR
# Load scripts from the following locations
$EnvPath = join-path -Path $home -ChildPath 'Documents\WindowsPowerShell\snipps\snipps$'
$env:Path += ";$EnvPath"
$historyPath = "$home\appdata\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
set-PSReadlineOption -HistorySavePath $historyPath
echo "historyPath: $historyPath"
#$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
# vscode Portable Path
$vscodepath = 'D:\portapps\6, Text,programming, x Editing\PortableApps\vscode-portable\vscode-portable.exe'
[Environment]::SetEnvironmentVariable("code", $vscodepath)
#sqlite dll
$workpath = "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll" ;
if ( $(Test-CommandExists 'everything') ) {$alternative = (everything 'wfn:System.Data.SQLite.DLL')[0] ;}
$p = if(Test-Path $workpath){$workpath} else {$alternative} ;
$p = $p ?? 'unable to set path'
if( Test-Path $p )
{
Add-Type -Path $p
echo $p
}
### local variables
$whatPulseDbQuery = "select rightstr(path,instr(reverse(path),'/')-1) exe,path from (select max(path) path,max(cast(replace(version,'.','') as integer)) version from applications group by case when online_app_id = 0 then name else online_app_id end)"
if ( $(Test-CommandExists 'everything') ) {$whatPulseDbPath = (Everything 'whatpulse.db')[0]; }
[Environment]::SetEnvironmentVariable("WHATPULSE_DB", $whatPulseDbPath)
if (-not $env:WHATPULSE_DB) { $env:WHATPULSE_DB = $whatPulseDbPath }; $WHATPULSE_DB = $env:WHATPULSE_DB
[Environment]::SetEnvironmentVariable("WHATPULSE_QUERY", $whatPulseDbQuery)
if (-not $env:WHATPULSE_QUERY) { $env:WHATPULSE_QUERY = $whatPulseDbQuery }; $WHATPULSE_QUERY = $env:WHATPULSE_QUERY
$datagripPath = '$home\appdata\Roaming\JetBrains\DataGrip2021.1'
[Environment]::SetEnvironmentVariable("datagripPath", $datagripPath)
$bComparePath = 'D:\PortableApps\2. fileOrganization\PortableApps\Beyond Compare 4'
[Environment]::SetEnvironmentVariable("bComparePath", $bComparePath)
echo "paths set"
$isAdmin = ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544"))
if ( ( $null -eq $PSVersionTable.PSEdition) -or ($PSVersionTable.PSEdition -eq "Desktop") ) { $PSVersionTable.PSEdition = "Desktop" ;$IsWindows = $true }
# Alias File
# Computer : 5CG84229D5
# Date/Time : 28 June 2022 13:24:18
# Exported by : crbk01
set-alias -Name:"accelerators" -Value:"[accelerators]::Get" -Description:"" -Option:"None"
set-alias -Name:"basename" -Value:"Split-Path" -Description:"" -Option:"AllScope"
set-alias -Name:"bcompare" -Value:"start-bc" -Description:"" -Option:"AllScope"
set-alias -Name:"browserflags" -Value:"start-BrowserFlags" -Description:"" -Option:"AllScope"
set-alias -Name:"cat" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"cd" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"chdir" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"clear" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"cls" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"copy" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"cp" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"del" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"df" -Value:"get-volume" -Description:"" -Option:"AllScope"
set-alias -Name:"dir" -Value:"Get-Childitem" -Description:"" -Option:"AllScope"
set-alias -Name:"echo" -Value:"Write-Output" -Description:"" -Option:"AllScope"
set-alias -Name:"edprofile" -Value:"start-Notepad-Profile" -Description:"" -Option:"None"
set-alias -Name:"env" -Value:"Get-Environment" -Description:" custom aliases" -Option:"AllScope"
set-alias -Name:"erase" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"etsn" -Value:"Enter-PSSession" -Description:"" -Option:"None"
set-alias -Name:"everything" -Value:"invoke-Everything" -Description:"" -Option:"AllScope"
set-alias -Name:"executeThis" -Value:"invoke-FuzzyWithEverything" -Description:"" -Option:"AllScope"
set-alias -Name:"exp-pro" -Value:"open-ProfileFolder" -Description:"" -Option:"None"
set-alias -Name:"exsn" -Value:"Exit-PSSession" -Description:"" -Option:"None"
set-alias -Name:"fhx" -Value:"Format-Hex" -Description:"" -Option:"None"
set-alias -Name:"filesinfolasstream" -Value:"read-pathsAsStream" -Description:"" -Option:"AllScope"
set-alias -Name:"flush-dns" -Value:"Clear-DnsClientCache" -Description:"" -Option:"AllScope"
set-alias -Name:"gcb" -Value:"Get-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"getip" -Value:"Get-IPv4Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getip6" -Value:"Get-IPv6Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getnic" -Value:"get-mac" -Description:"" -Option:"AllScope"
set-alias -Name:"gin" -Value:"Get-ComputerInfo" -Description:"" -Option:"None"
set-alias -Name:"GitAdEPathAsSNB" -Value:"invoke-GitSubmoduleAdd" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSilently" -Value:"invoke-GitLazySilently" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSingleRemote" -Value:"invoke-gitFetchOrig" -Description:"" -Option:"AllScope"
set-alias -Name:"gitsplit" -Value:"subtree-split-rm-commit" -Description:"" -Option:"AllScope"
set-alias -Name:"GitUp" -Value:"invoke-GitLazy" -Description:"" -Option:"AllScope"
set-alias -Name:"gjb" -Value:"Get-Job" -Description:"" -Option:"None"
set-alias -Name:"gsn" -Value:"Get-PSSession" -Description:"" -Option:"None"
set-alias -Name:"gtz" -Value:"Get-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"h" -Value:"Get-History" -Description:"" -Option:"None"
set-alias -Name:"history" -Value:"Get-History" -Description:"" -Option:"AllScope"
set-alias -Name:"HistoryPath" -Value:"(Get-PSReadlineOption).HistorySavePath" -Description:"" -Option:"AllScope"
set-alias -Name:"home" -Value:"open-here" -Description:"" -Option:"AllScope"
set-alias -Name:"icm" -Value:"Invoke-Command" -Description:"" -Option:"None"
set-alias -Name:"isFolder" -Value:"get-isFolder" -Description:"" -Option:"AllScope"
set-alias -Name:"kill" -Value:"Stop-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"lp" -Value:"Out-Printer" -Description:"" -Option:"AllScope"
set-alias -Name:"ls" -Value:"Get-ChildItem" -Description:"" -Option:"None"
set-alias -Name:"lsx" -Value:"get-Childnames" -Description:"" -Option:"AllScope"
set-alias -Name:"make" -Value:"invoke-Nmake" -Description:"" -Option:"AllScope"
set-alias -Name:"man" -Value:"help" -Description:"" -Option:"None"
set-alias -Name:"md" -Value:"mkdir" -Description:"" -Option:"AllScope"
set-alias -Name:"mount" -Value:"New-PSDrive" -Description:"" -Option:"None"
set-alias -Name:"move" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"mv" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"MyAliases" -Value:"read-aliases" -Description:"" -Option:"AllScope"
set-alias -Name:"nsn" -Value:"New-PSSession" -Description:"" -Option:"None"
set-alias -Name:"open" -Value:"Invoke-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"OpenAsADmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"os-update" -Value:"Update-Packages" -Description:"" -Option:"AllScope"
set-alias -Name:"parameters" -Value:"get-parameters" -Description:"" -Option:"None"
set-alias -Name:"pastDo" -Value:"find-historyInvoke" -Description:"" -Option:"AllScope"
set-alias -Name:"pastDoEdit" -Value:"find-historyAppendClipboard" -Description:"" -Option:"AllScope"
set-alias -Name:"popd" -Value:"Pop-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"printpaths" -Value:"read-EnvPaths" -Description:"" -Option:"AllScope"
set-alias -Name:"ps" -Value:"Get-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"psVersion" -Value:"$PSVersionTable.PSVersion.Major " -Description:"" -Option:"AllScope"
set-alias -Name:"pushd" -Value:"Push-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"pwd" -Value:"Get-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"r" -Value:"Invoke-History" -Description:"" -Option:"None"
set-alias -Name:"rcjb" -Value:"Receive-Job" -Description:"" -Option:"None"
set-alias -Name:"rd" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"realpath" -Value:"Resolve-Path" -Description:"cmd-like" -Option:"AllScope"
set-alias -Name:"reboot" -Value:"exit-Nrenter" -Description:"" -Option:"AllScope"
set-alias -Name:"refreshenv" -Value:"Update-SessionEnvironment" -Description:"" -Option:"None"
set-alias -Name:"reload" -Value:"initialize-profile" -Description:"" -Option:"AllScope"
set-alias -Name:"remote" -Value:"invoke-gitRemote" -Description:"" -Option:"AllScope"
set-alias -Name:"ren" -Value:"Rename-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rjb" -Value:"Remove-Job" -Description:"" -Option:"None"
set-alias -Name:"rm" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rmdir" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rsn" -Value:"Remove-PSSession" -Description:"" -Option:"None"
set-alias -Name:"sajb" -Value:"Start-Job" -Description:"" -Option:"None"
set-alias -Name:"scb" -Value:"Set-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"set" -Value:"Set-Variable" -Description:"" -Option:"AllScope"
set-alias -Name:"sls" -Value:"Select-String" -Description:"" -Option:"None"
set-alias -Name:"spjb" -Value:"Stop-Job" -Description:"" -Option:"None"
set-alias -Name:"start-powershellAsAdmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"start-su" -Value:"start-powershellAsAdmin" -Description:"" -Option:"None"
set-alias -Name:"stz" -Value:"Set-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"touch" -Value:"Set-FileTime" -Description:"" -Option:"AllScope"
set-alias -Name:"type" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"uptime" -Value:"read-uptime" -Description:"" -Option:"AllScope"
set-alias -Name:"version" -Value:"System.Management.Automation.PSVersionHashTable" -Description:"bash-like" -Option:"None"
set-alias -Name:"which" -Value:"Get-Command" -Description:"" -Option:"AllScope"
set-alias -Name:"wjb" -Value:"Wait-Job" -Description:"" -Option:"None"
#------------------------------- Styling begin --------------------------------------
if ( (($error.length | group).name -eq $null ) -and (Test-IsInteractive) ) {
Clear-Host # remove advertisements (preferably use -noLogo)
}
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
# Style default PowerShell Console
$shell = $Host.UI.RawUI
$shell.WindowTitle= "PS"
$shell.BackgroundColor = "Black"
$shell.ForegroundColor = "White"
# Load custom theme for Windows Terminal
#Set-Theme LazyAdmin
Write-Host "PSVersion: $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)"
Write-Host "PSEdition: $($PSVersionTable.PSEdition)"
Write-Host "Profile: $PSCommandPath"
Write-Host "admin: $isAdmin"
#Module Browser Begin
#Version: 1.0.0
Add-Type -Path 'E:\Program Files (x86)\Microsoft Module Browser\ModuleBrowser.dll'
$moduleBrowser = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Module Browser', [ModuleBrowser.Views.MainView], $true)
$psISE.CurrentPowerShellTab.VisibleVerticalAddOnTools.SelectedAddOnTool = $moduleBrowser
#Module Browser End
# Start AzureAutomationISEAddOn snippet
Import-Module AzureAutomationAuthoringToolkit
# End AzureAutomationISEAddOn snippet
#ps setHistorySavePath
if (-not $env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME = Join-Path -Path "$HOME" -ChildPath ".config" }; $XDG_CONFIG_HOME = $env:XDG_CONFIG_HOME
if (-not $env:XDG_DATA_HOME) { $env:XDG_DATA_HOME = Join-Path -Path "$HOME" -ChildPath ".local/share" }; $XDG_DATA_HOME = $env:XDG_DATA_HOME
if (-not $env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME = Join-Path -Path "$HOME" -ChildPath ".cache" }; $XDG_CACHE_HOME = $env:XDG_CACHE_HOME
if (-not $env:DESKTOP_DIR) { $env:DESKTOP_DIR = Join-Path -Path "$HOME" -ChildPath "desktop" }; $DESKTOP_DIR = $env:DESKTOP_DIR
if (-not $env:NOTES_DIR) { $env:NOTES_DIR = Join-Path -Path "$HOME" -ChildPath "notes" }; $NOTES_DIR = $env:NOTES_DIR
if (-not $env:CHEATS_DIR) { $env:CHEATS_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "cheatsheets" }; $CHEATS_DIR = $env:CHEATS_DIR
if (-not $env:TODO_DIR) { $env:TODO_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "_ToDo" }; $TODO_DIR = $env:TODO_DIR
if (-not $env:DEVEL_DIR) { $env:DEVEL_DIR = Join-Path -Path "$HOME" -ChildPath "devel" }; $DEVEL_DIR = $env:DEVEL_DIR
if (-not $env:PORTS_DIR) { $env:PORTS_DIR = Join-Path -Path "$HOME" -ChildPath "ports" }; $PORTS_DIR = $env:PORTS_DIR
# Load scripts from the following locations
$EnvPath = join-path -Path $home -ChildPath 'Documents\WindowsPowerShell\snipps\snipps$'
$env:Path += ";$EnvPath"
$historyPath = "$home\appdata\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
set-PSReadlineOption -HistorySavePath $historyPath
echo "historyPath: $historyPath"
#$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
### local variables
$whatPulseDbQuery = Get-Content '.\whatPulseDbQuery.sql' -raw
if ( $(Test-CommandExists 'everything') ) {$whatPulseDbPath = (Everything 'whatpulse.db')[0]; }
[Environment]::SetEnvironmentVariable("WHATPULSE_DB", $whatPulseDbPath)
if (-not $env:WHATPULSE_DB) { $env:WHATPULSE_DB = $whatPulseDbPath }; $WHATPULSE_DB = $env:WHATPULSE_DB
[Environment]::SetEnvironmentVariable("WHATPULSE_QUERY", $whatPulseDbQuery)
if (-not $env:WHATPULSE_QUERY) { $env:WHATPULSE_QUERY = $whatPulseDbQuery }; $WHATPULSE_QUERY = $env:WHATPULSE_QUERY
$datagripPath = '$home\appdata\Roaming\JetBrains\DataGrip2021.1'
[Environment]::SetEnvironmentVariable("datagripPath", $datagripPath)
$bComparePath = 'D:\PortableApps\2. fileOrganization\PortableApps\Beyond Compare 4'
[Environment]::SetEnvironmentVariable("bComparePath", $bComparePath)
echo "paths set"
#sqlite dll
$workpath = "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll" ;
if ( $(Test-CommandExists 'everything') ) {$alternative = (everything 'wfn:System.Data.SQLite.DLL')[0] ;}
$p = if(Test-Path $workpath){$workpath} else {$alternative} ;
$p = $p ?? 'unable to set path'
if( Test-Path $p )
{
Add-Type -Path $p
echo $p
}
$isAdmin = ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544"))
if ( ( $null -eq $PSVersionTable.PSEdition) -or ($PSVersionTable.PSEdition -eq "Desktop") ) { $PSVersionTable.PSEdition = "Desktop" ;$IsWindows = $true }
# Alias File
# Computer : 5CG84229D5
# Date/Time : 28 June 2022 13:24:18
# Exported by : crbk01
set-alias -Name:"accelerators" -Value:"[accelerators]::Get" -Description:"" -Option:"None"
set-alias -Name:"basename" -Value:"Split-Path" -Description:"" -Option:"AllScope"
set-alias -Name:"bcompare" -Value:"start-bc" -Description:"" -Option:"AllScope"
set-alias -Name:"browserflags" -Value:"start-BrowserFlags" -Description:"" -Option:"AllScope"
set-alias -Name:"cat" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"cd" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"chdir" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"clear" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"cls" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"copy" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"cp" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"del" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"df" -Value:"get-volume" -Description:"" -Option:"AllScope"
set-alias -Name:"dir" -Value:"Get-Childitem" -Description:"" -Option:"AllScope"
set-alias -Name:"echo" -Value:"Write-Output" -Description:"" -Option:"AllScope"
set-alias -Name:"edprofile" -Value:"start-Notepad-Profile" -Description:"" -Option:"None"
set-alias -Name:"env" -Value:"Get-Environment" -Description:" custom aliases" -Option:"AllScope"
set-alias -Name:"erase" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"etsn" -Value:"Enter-PSSession" -Description:"" -Option:"None"
set-alias -Name:"exp-pro" -Value:"open-ProfileFolder" -Description:"" -Option:"None"
set-alias -Name:"exsn" -Value:"Exit-PSSession" -Description:"" -Option:"None"
set-alias -Name:"fhx" -Value:"Format-Hex" -Description:"" -Option:"None"
set-alias -Name:"filesinfolasstream" -Value:"read-pathsAsStream" -Description:"" -Option:"AllScope"
set-alias -Name:"flush-dns" -Value:"Clear-DnsClientCache" -Description:"" -Option:"AllScope"
set-alias -Name:"gcb" -Value:"Get-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"getip" -Value:"Get-IPv4Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getip6" -Value:"Get-IPv6Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getnic" -Value:"get-mac" -Description:"" -Option:"AllScope"
set-alias -Name:"gin" -Value:"Get-ComputerInfo" -Description:"" -Option:"None"
set-alias -Name:"gjb" -Value:"Get-Job" -Description:"" -Option:"None"
set-alias -Name:"gsn" -Value:"Get-PSSession" -Description:"" -Option:"None"
set-alias -Name:"gtz" -Value:"Get-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"h" -Value:"Get-History" -Description:"" -Option:"None"
set-alias -Name:"history" -Value:"Get-History" -Description:"" -Option:"AllScope"
set-alias -Name:"HistoryPath" -Value:"(Get-PSReadlineOption).HistorySavePath" -Description:"" -Option:"AllScope"
set-alias -Name:"home" -Value:"open-here" -Description:"" -Option:"AllScope"
set-alias -Name:"icm" -Value:"Invoke-Command" -Description:"" -Option:"None"
set-alias -Name:"isFolder" -Value:"get-isFolder" -Description:"" -Option:"AllScope"
set-alias -Name:"kill" -Value:"Stop-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"lp" -Value:"Out-Printer" -Description:"" -Option:"AllScope"
set-alias -Name:"ls" -Value:"Get-ChildItem" -Description:"" -Option:"None"
set-alias -Name:"lsx" -Value:"get-Childnames" -Description:"" -Option:"AllScope"
set-alias -Name:"make" -Value:"invoke-Nmake" -Description:"" -Option:"AllScope"
set-alias -Name:"man" -Value:"help" -Description:"" -Option:"None"
set-alias -Name:"md" -Value:"mkdir" -Description:"" -Option:"AllScope"
set-alias -Name:"mount" -Value:"New-PSDrive" -Description:"" -Option:"None"
set-alias -Name:"move" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"mv" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"MyAliases" -Value:"read-aliases" -Description:"" -Option:"AllScope"
set-alias -Name:"nsn" -Value:"New-PSSession" -Description:"" -Option:"None"
set-alias -Name:"open" -Value:"Invoke-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"OpenAsADmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"os-update" -Value:"Update-Packages" -Description:"" -Option:"AllScope"
set-alias -Name:"parameters" -Value:"get-parameters" -Description:"" -Option:"None"
set-alias -Name:"pastDo" -Value:"find-historyInvoke" -Description:"" -Option:"AllScope"
set-alias -Name:"pastDoEdit" -Value:"find-historyAppendClipboard" -Description:"" -Option:"AllScope"
set-alias -Name:"popd" -Value:"Pop-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"printpaths" -Value:"read-EnvPaths" -Description:"" -Option:"AllScope"
set-alias -Name:"ps" -Value:"Get-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"psVersion" -Value:"$PSVersionTable.PSVersion.Major " -Description:"" -Option:"AllScope"
set-alias -Name:"pushd" -Value:"Push-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"pwd" -Value:"Get-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"r" -Value:"Invoke-History" -Description:"" -Option:"None"
set-alias -Name:"rcjb" -Value:"Receive-Job" -Description:"" -Option:"None"
set-alias -Name:"rd" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"realpath" -Value:"Resolve-Path" -Description:"cmd-like" -Option:"AllScope"
set-alias -Name:"reboot" -Value:"exit-Nrenter" -Description:"" -Option:"AllScope"
set-alias -Name:"refreshenv" -Value:"Update-SessionEnvironment" -Description:"" -Option:"None"
set-alias -Name:"reload" -Value:"initialize-profile" -Description:"" -Option:"AllScope"
set-alias -Name:"ren" -Value:"Rename-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rjb" -Value:"Remove-Job" -Description:"" -Option:"None"
set-alias -Name:"rm" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rmdir" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rsn" -Value:"Remove-PSSession" -Description:"" -Option:"None"
set-alias -Name:"sajb" -Value:"Start-Job" -Description:"" -Option:"None"
set-alias -Name:"scb" -Value:"Set-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"set" -Value:"Set-Variable" -Description:"" -Option:"AllScope"
set-alias -Name:"sls" -Value:"Select-String" -Description:"" -Option:"None"
set-alias -Name:"spjb" -Value:"Stop-Job" -Description:"" -Option:"None"
set-alias -Name:"start-powershellAsAdmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"start-su" -Value:"start-powershellAsAdmin" -Description:"" -Option:"None"
set-alias -Name:"stz" -Value:"Set-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"touch" -Value:"Set-FileTime" -Description:"" -Option:"AllScope"
set-alias -Name:"type" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"uptime" -Value:"read-uptime" -Description:"" -Option:"AllScope"
set-alias -Name:"version" -Value:"System.Management.Automation.PSVersionHashTable" -Description:"bash-like" -Option:"None"
set-alias -Name:"which" -Value:"Get-Command" -Description:"" -Option:"AllScope"
set-alias -Name:"wjb" -Value:"Wait-Job" -Description:"" -Option:"None"
#------------------------------- Styling begin --------------------------------------
if ( (($error.length | group).name -eq $null ) -and (Test-IsInteractive) ) {
Clear-Host # remove advertisements (preferably use -noLogo)
}
# Keep the existing window title
if ( $(Test-CommandExists 'get-title') )
{
$windowTitle = (get-title).Trim()
if ($windowTitle.StartsWith("Administrator:")) {
$windowTitle = $windowTitle.Substring(14).Trim()
}
}
$nextId = (get-history -count 1).Id + 1;
# KevMar logging
$LastCmd = Get-History -Count 1
if ($LastCmd) {
$lastId = $LastCmd.Id
Add-Content -Value "# $($LastCmd.StartExecutionTime)" -Path $PSLogPath
Add-Content -Value "$($LastCmd.CommandLine)" -Path $PSLogPath
Add-Content -Value '' -Path $PSLogPath
$howlongwasthat = $LastCmd.EndExecutionTime.Subtract($LastCmd.StartExecutionTime).TotalSeconds
}
$currentPath = (get-location).Path.replace($home, "~")
$idx = $currentPath.IndexOf("::")
if ($idx -gt -1) { $currentPath = $currentPath.Substring($idx + 2) }
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'System.Security.Principal.WindowsPrincipal' $windowsIdentity
# Kerazy_POSH propmt
# Get Powershell version information
$MajorVersion = $PSVersionTable.PSVersion.Major
$MinorVersion = $PSVersionTable.PSVersion.Minor
# Detect if the Shell is 32- or 64-bit host
if ([System.IntPtr]::Size -eq 8) {
$ShellBits = 'x64 (64-bit)'
} elseif ([System.IntPtr]::Size -eq 4) {
$ShellBits = 'x86 (32-bit)'
}
# Set Window Title to display Powershell version info, Shell bits, username and computername
$host.UI.RawUI.WindowTitle = "PowerShell v$MajorVersion.$MinorVersion $ShellBits | $env:USERNAME@$env:USERDNSDOMAIN | $env:COMPUTERNAME | $env:LOGONSERVER"
# Set Prompt Line 1 - include Date, file path location
Write-Host(Get-Date -UFormat "%Y/%m/%d %H:%M:%S ($howlongwasthat) | ") -NoNewline -ForegroundColor DarkGreen
Write-Host(Get-Location) -ForegroundColor DarkGreen
# Set Prompt Line 2
# Check for Administrator elevation
if (Test-IsAdmin) {
Write-Host '# ADMIN # ' -NoNewline -ForegroundColor Cyan
} else {
Write-Host '# User # ' -NoNewline -ForegroundColor DarkCyan
}
if ($psISE) { $color = "Black"; }
elseif ($windowsPrincipal.IsInRole("Administrators") -eq 1)
{ $color = "Yellow";}
else{ $color = "Green";}
if ( $(Test-CommandExists 'Write-HgStatus') )
{
Write-HgStatus (Get-HgStatus)
Write-GitStatus (Get-GitStatus)
}
write-host (" [" + $nextId + "]") -NoNewLine -ForegroundColor $color
if ((get-location -stack).Count -gt 0) { write-host ("+" * ((get-location -stack).Count)) -NoNewLine -ForegroundColor Cyan }
if ( $(Test-CommandExists 'set-title') )
{ $title = $currentPath
if ($windowTitle -ne $null) { $title = ($title + " » " + $windowTitle) }
set-title $title
}
return " "
Write-Host '»' -NoNewLine -ForeGroundColor Green
' ' # need this space to avoid the default white PS>
# Style default PowerShell Console
$shell = $Host.UI.RawUI
$shell.WindowTitle= "PS"
$shell.BackgroundColor = "Black"
$shell.ForegroundColor = "White"
$colors = $host.PrivateData
$colors.verbosebackgroundcolor = "Magenta"
$colors.verboseforegroundcolor = "Green"
$colors.warningbackgroundcolor = "Red"
$colors.warningforegroundcolor = "white"
$colors.ErrorBackgroundColor = "DarkCyan"
$colors.ErrorForegroundColor = "Yellow"
# Load custom theme for Windows Terminal
#Set-Theme LazyAdmin
Write-Host "PSVersion: $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)"
Write-Host "PSEdition: $($PSVersionTable.PSEdition)"
Write-Host "Profile: $PSCommandPath"
Write-Host "admin: $isAdmin"
# 设置 PowerShell 主题
# 引入 ps-read-line # useful history related actions
# example: https://github.com/PowerShell/PSReadLine/blob/master/PSReadLine/SamplePSReadLineProfile.ps1
if (Test-ModuleExists 'PSReadLine')
{
if(!(TryImport-Module PSReadLine)) #null if fail to load
{
#------------------------------- Set Hot-keys BEGIN -------------------------------
$PSReadLineOptions = @{
HistorySavePath = $global:historyPath
PredictionSource = "HistoryAndPlugin"
HistorySearchCursorMovesToEnd = $true
}
Set-PSReadLineOption @PSReadLineOptions
echo ($host.Name -eq 'ConsoleHost')
# Set-PSReadLineOption -EditMode Emac
# 每次回溯输入历史,光标定位于输入内容末尾
# 设置 Tab 为菜单补全和 Intellisense
# 设置 Ctrl+d 为退出 PowerShell
# 设置 Ctrl+z 为撤销
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadlineKeyHandler -Chord 'Shift+Tab' -Function Complete
# 设置 Ctrl+d 为退出 PowerShell
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit
# 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
if ( $null -ne $(Get-Module PSFzf) ) {
#Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
#$FZF_COMPLETION_TRIGGER='...'
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
}
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
#------------------------------- Set Hot-keys END -------------------------------
if ( $(Get-Module PSReadline).Version -ge 2.2 ) {
# 设置预测文本来源为历史记录
Set-PSReadLineOption -predictionsource history -ea SilentlyContinue
}
if ( $(Test-CommandExists 'Set-PSReadLineOption') )
{
#------------------------------- Styling begin --------------------------------------
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
}
echo "historyPath: $global:historyPath"
}
else
{
Write-Verbose "psReadLineNotimported"
}
}
else
{
Write-Verbose "psReadLineNotpresent"
}
'PSReadLine' -AllowPrerelease
'posh-git'
'PSFzf'
'PSEverything'
'PSProfiler' # --> Measure-Script
# serialization tools: eg. ConvertTo-HashString / ConvertTo-HashTable https://github.com/torgro/HashData
'hashdata'
# useful Tools eg. ConvertTo-FlatObject, Join-Object... https://github.com/RamblingCookieMonster/PowerShell
'WFTools'
# https://old.reddit.com/r/AZURE/comments/fh0ycv/azuread_vs_azurerm_vs_az/
# https://docs.microsoft.com/en-us/microsoft-365/enterprise/connect-to-microsoft-365-powershell
'AzureAD'
'Pscx'
'SqlServer'
# Windows Update CLI tool http://woshub.com/pswindowsupdate-module/#h2_2
# Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
# native alternative: WindowsUpdateProvider\Install-WUUpdates >= Windows Server 2019
'PSWindowsUpdate'
"${env:ChocolateyInstall}\helpers\chocolateyProfile.psm1"
# 引入 posh-git
'PSFzf'
( ($host.Name -eq 'ConsoleHost') -and ($null -ne (Get-Module -ListAvailable -Name posh-git) ) ? "posh-git" : "") # 引入 oh-my-posh
( (test-path("$home/AppData/Local/oh-my-posh/oh-my-posh.exe") ? "oh-my-posh" : "" ) )
'EZOut' # help take the pain out of writing format and types XML
'echoargs' # describe arguments of a function
PowerShellGet
<Types>
<Type>
<Name>System.String</Name>
<Members>
<ScriptProperty>
<Name>ToBase64</Name>
<GetScriptBlock>
[System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($this))
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>FromBase64</Name>
<GetScriptBlock>
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($this))
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
{"Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned"}
# Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# src: https://gist.github.com/apfelchips/62a71500a0f044477698da71634ab87b
# New-Item $(Split-Path "$($PROFILE.CurrentUserCurrentHost)") -ItemType Directory -ea 0; Invoke-WebRequest -Uri "https://git.io/JYZTu" -OutFile "$($PROFILE.CurrentUserCurrentHost)"
# ref: https://devblogs.microsoft.com/powershell/optimizing-your-profile/#measure-script
# ref: Powershell $? https://stackoverflow.com/a/55362991
# ref: Write-* https://stackoverflow.com/a/38527767
# Write-Host wrapper for Write-Information -InformationAction Continue
# define these environment variables if not set already and also provide them as PSVariables
if ( ( $null -eq $PSVersionTable.PSEdition) -or ($PSVersionTable.PSEdition -eq "Desktop") ) { $PSVersionTable.PSEdition = "Desktop" ;$IsWindows = $true }
if ( -not $IsWindows ) { function Test-IsAdmin { if ( (id -u) -eq 0 ) { return $true } return $false } }
#src: https://devblogs.microsoft.com/scripting/use-a-powershell-function-to-see-if-a-command-exists/
function Test-CommandExists {
Param ($command)
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
try { Get-Command $command; return $true }
catch {return $false}
finally { $ErrorActionPreference=$oldErrorActionPreference }
}
function Clean-Object {
process {
$_.PSObject.Properties.Remove('PSComputerName')
$_.PSObject.Properties.Remove('RunspaceId')
$_.PSObject.Properties.Remove('PSShowComputerName')
}
#Where-Object { $_.PSObject.Properties.Value -ne $null}
}
function Get-Environment { # Get-Variable to show all Powershell Variables accessible via $
if ( $args.Count -eq 0 ) {
Get-Childitem env:
} elseif( $args.Count -eq 1 ) {
Start-Process (Get-Command $args[0]).Source
} else {
Start-Process (Get-Command $args[0]).Source -ArgumentList $args[1..($args.Count-1)]
}
}
function cf {
if ( $null -ne $(Get-Module PSFzf) ) {
Get-ChildItem . -Recurse -Attributes Directory | Invoke-Fzf | Set-Location
} else {
Write-Error "please install PSFzf"
}
}
if ( $(Test-CommandExists 'git') ) {
Set-Alias g git -Option AllScope
function git-root { $gitrootdir = (git rev-parse --show-toplevel) ; if ( $gitrootdir ) { Set-Location $gitrootdir } }
if ( $IsWindows ) {
function git-sh {
if ( $args.Count -eq 0 ) { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") -l
} else { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\sh") $args }
}
function git-bash {
if ( $args.Count -eq 0 ) {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l
} else {
. $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") $args
}
}
function git-vim { . $(Join-Path -Path $(Split-Path -Path $(Get-Command git).Source) -ChildPath "..\bin\bash") -l -c `'vim $args`' }
if ( -Not (Test-CommandExists 'sh') ){ Set-Alias sh git-sh -Option AllScope }
if ( -Not (Test-CommandExists 'bash') ){ Set-Alias bash git-bash -Option AllScope }
if ( -Not (Test-CommandExists 'vi') ){ Set-Alias vi git-vim -Option AllScope }
if ( -Not (Test-CommandExists 'vim') ){ Set-Alias vim git-vim -Option AllScope }
}
}
function Select-Value { # src: https://geekeefy.wordpress.com/2017/06/26/selecting-objects-by-value-in-powershell/
[Cmdletbinding()]
param(
[parameter(Mandatory=$true)] [String] $Value,
[parameter(ValueFromPipeline=$true)] $InputObject
)
process {
# Identify the PropertyName for respective matching Value, in order to populate it Default Properties
$Property = ($PSItem.properties.Where({$_.Value -Like "$Value"})).Name
If ( $Property ) {
# Create Property a set which includes the 'DefaultPropertySet' and Property for the respective 'Value' matched
$DefaultPropertySet = $PSItem.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames
$TypeName = ($PSItem.PSTypenames)[0]
Get-TypeData $TypeName | Remove-TypeData
Update-TypeData -TypeName $TypeName -DefaultDisplayPropertySet ($DefaultPropertySet+$Property |Select-Object -Unique)
$PSItem | Where-Object {$_.properties.Value -like "$Value"}
}
}
}
function pause($message="Press any key to continue . . . ") {
Write-Host -NoNewline $message
$i=16,17,18,20,91,92,93,144,145,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183
while ($null -eq $k.VirtualKeyCode -or $i -Contains $k.VirtualKeyCode){
$k = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
Write-Host ""
}
# native touch implementation
# src: https://ss64.com/ps/syntax-touch.html
function Set-FileTime {
param(
[string[]]$paths,
[bool]$only_modification = $false,
[bool]$only_access = $false
)
begin {
function updateFileSystemInfo([System.IO.FileSystemInfo]$fsInfo) {
$datetime = Get-Date
if ( $only_access ) {
$fsInfo.LastAccessTime = $datetime
} elseif ( $only_modification ) {
$fsInfo.LastWriteTime = $datetime
} else {
$fsInfo.CreationTime = $datetime
$fsInfo.LastWriteTime = $datetime
$fsInfo.LastAccessTime = $datetime
}
}
function touchExistingFile($arg) {
if ( $arg -is [System.IO.FileSystemInfo] ) {
updateFileSystemInfo($arg)
} else {
$resolvedPaths = Resolve-Path $arg
foreach ($rpath in $resolvedPaths) {
if ( Test-Path -type Container $rpath ) {
$fsInfo = New-Object System.IO.DirectoryInfo($rpath)
} else {
$fsInfo = New-Object System.IO.FileInfo($rpath)
}
updateFileSystemInfo($fsInfo)
}
}
}
function touchNewFile([string]$path) {
#$null > $path
Set-Content -Path $path -value $null;
}
}
process {
if ( $_ ) {
if ( Test-Path $_ ) {
touchExistingFile($_)
} else {
touchNewFile($_)
}
}
}
end {
if ( $paths ) {
foreach ( $path in $paths ) {
if ( Test-Path $path ) {
touchExistingFile($path)
} else {
touchNewFile($path)
}
}
}
}
}
if ( $IsWindows ) {
function stree($directory = $pwd) {
$gitrootdir = (Invoke-Command{Set-Location $args[0]; git rev-parse --show-toplevel 2>&1;} -ArgumentList $directory)
if ( Test-Path -Path "$gitrootdir\.git" -PathType Container) {
$newestExe = Get-Item "${env:ProgramFiles(x86)}\Atlassian\SourceTree\SourceTree.exe" | select -Last 1
Write-Debug "Opening $gitrootdir with $newestExe"
Start-Process -filepath $newestExe -ArgumentList "-f `"$gitrootdir`" log"
} else {
Write-Error "git directory not found"
}
}
if ( "${env:ChocolateyInstall}" -eq "" ) {
function Install-Chocolatey {
if (Get-Command choco -ErrorAction SilentlyContinue) {
Write-Error "chocolatey already installed!"
} else {
Start-Process (Get-HostExecutable) -ArgumentList "-Command Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1') -verb RunAs"
}
}
else {
function choco { Start-Process (Get-HostExecutable) -ArgumentList "-noProfile -noLogo -Command choco.exe ${args}; pause" -verb runAs }
}
}
}
function Get-HostExecutable {
if ( $PSVersionTable.PSEdition -eq "Core" ) {
$ConsoleHostExecutable = (get-command pwsh).Source
} else {
$ConsoleHostExecutable = (get-command powershell).Source
}
return $ConsoleHostExecutable
}
# don't override chocolatey sudo or unix sudo
if ( -not $(Test-CommandExists 'sudo') ) {
function sudo() {
if ( $args.Length -eq 0 ) {
Start-Process $(Get-HostExecutable) -verb "runAs"
} elseif ( $args.Length -eq 1 ) {
Start-Process $args[0] -verb "runAs"
} else {
Start-Process $args[0] -ArgumentList $args[1..$args.Length] -verb "runAs"
}
}
}
# Helper Functions
#######################################################
function uptimef {
Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime';
EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
}
function find-file($name) {
ls -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | foreach {
$place_path = $_.directory
echo "${place_path}\${_}"
}
}
function unzipf ($path) {
$dirname = (Get-Item $path).Basename
echo("Extracting", $path, "to", $dirname)
New-Item -Force -ItemType directory -Path $dirname
expand-archive $path -OutputPath $dirname -ShowProgress
}
# already expanded to save time https://github.com/nvbn/thefuck/wiki/Shell-aliases#powershell
if ( $(Test-CommandExists 'thefuck') ) {
function fuck {
$PYTHONIOENCODING_BKP=$env:PYTHONIOENCODING
$env:PYTHONIOENCODING="utf-8"
$history = (Get-History -Count 1).CommandLine
if (-not [string]::IsNullOrWhiteSpace($history)) {
$fuck = $(thefuck $args $history)
if ( -not [string]::IsNullOrWhiteSpace($fuck) ) {
if ( $fuck.StartsWith("echo") ) { $fuck = $fuck.Substring(5) } else { iex "$fuck" }
}
}
[Console]::ResetColor()
$env:PYTHONIOENCODING=$PYTHONIOENCODING_BKP
}
Set-Alias f fuck -Option AllScope
}
# hacks for old powerhsell versions
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
function Get-ExitBoolean($command) { & $command | Out-Null; $?} ; Set-Alias geb Get-ExitBoolean # fixed: https://github.com/PowerShell/PowerShell/pull/9849
function Use-Default # $var = d $Value : "DefaultValue" eg. ternary # fixed: https://toastit.dev/2019/09/25/ternary-operator-powershell-7/
{
for ($i = 1; $i -lt $args.Count; $i++){
if ($args[$i] -eq ":"){
$coord = $i; break
}
}
if ($coord -eq 0) {
throw new System.Exception "No operator!"
}
if ($args[$coord - 1] -eq ""){
$toReturn = $args[$coord + 1]
} else {
$toReturn = $args[$coord -1]
}
return $toReturn
}
Set-Alias d Use-Default
}
if ( $IsWindows ) {
# src: http://serverfault.com/questions/95431
function Test-IsAdmin { $user = [Security.Principal.WindowsIdentity]::GetCurrent(); return $(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator); }
function Reopen-here { Get-Process explorer | Stop-Process Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command 'Get-Process explorer | Stop-Process'" -verb "runAs"}
function Reset-Spooler { Start-Process "$(Get-HostExecutable)" -ArgumentList "-noProfile -noLogo -Command 'Stop-Service -Name Spooler -Force; Get-Item ${env:SystemRoot}\System32\spool\PRINTERS\* | Remove-Item -Force -Recurse; Start-Service -Name Spooler'" -verb "runAs" }
function subl { Start-Process "${Env:ProgramFiles}\Sublime Text\subl.exe" -ArgumentList $args -WindowStyle Hidden } # hide subl shim script
function get-tempfilesNfolders { foreach ($folder in @('C:\Windows\Temp\*', 'C:\Documents and Settings\*\Local Settings\temp\*', 'C:\Users\*\Appdata\Local\Temp\*', 'C:\Users\*\Appdata\Local\Microsoft\Windows\Temporary Internet Files\*', 'C:\Windows\SoftwareDistribution\Download', 'C:\Windows\System32\FNTCACHE.DAT')) {$_} }
function Export-Regestrykey { param ( $reg = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\' ,$outFile = 'H:\hkcu-regbackup.txt' ) get-childitem -path $reg | out-file $outFile }
function start-bc ($REMOTE,$LOCAL,$BASE,$MERGED) { cmd /c "${Env:ProgramFiles}\BeondCompare4\BComp.exe" "$REMOTE" "$LOCAL" "$BASE" "$MERGED" } #todo: replace hardcode with global variable pointing to path
function start-cygwin { param ( $cygwinpath = "${Env:ProgramFiles}\cygwin64\" ) ."$cygwinpath\Cygwin.bat" }
function Compare-ImagesMetadata { param ( $exifToolPath = "${Env:ProgramFiles}\geosetter\tools\" ,$inputA = "E:\Pictures\Badges & Signs & Shablon Art\00 - soulcripple front (2).jpg" ,$inputB = "E:\Pictures\Badges & Signs & Shablon Art\00 - soulcripple front.jpg" ) ; $set1 = .\exiftool.exe -a -u -g1 $inputA ; $set2 = .\exiftool.exe -a -u -g1 $inputB ; Compare-Object $set1 $set2 | select -ExpandProperty inputobject }
function new-SymbolicLink { param ( $where = 'H:\mina grejer\Till Github' ,$from = 'H:\mina grejer\Project shelf\Till Github' ) New-Item -Path $where -ItemType SymbolicLink -Value $from }
}
if (Test-CommandExists 'search-Everything')
{
function invoke-Everything([string]$filter) { @(Search-Everything -filter $filter -global) }
function invoke-FuzzyWithEverything($searchstring) { menu @(everything "ext:exe $searchString") | %{& $_ } } #use whatpulse db first, then everything #todo: sort by rescent use #use everything to find executable for fast execution
function Every-execute ($inputx) { $filter = "ext:exe $inputx" ; $filter } #& (Every-Menu $filter)
function Every-AsHashMap { param( $filter = 'ext:psd1 \module') $q = @{} ; everything $filter | %{@{ name = (get -item $_).name ; time=(get -item $_).LastWriteTime ; path=(get -item $_) } } | sort -object -property time | %{ $q[$_.name] = $_.path } ; $q | select -property values}
function Every-execute { param( $filter = 'regex:".*\\data\\[^\\]*.ahk"',$navigate=$true) Every-Menu | % { if($navigate) {cd ($_ | split -path -parent)} ; . $_ } }
function Every-Load { param( $psFileFilter = 'convert-xlsx-to-csv.ps1') . ( everythnig $psFileFilter | select -first 1) } ; invoke-expression "ExcelToCsv -File 'D:\unsorted\fannyUtskick.xlsx'"
function Every-Explore { param( $filter = 'ext:exe lasso') ; Every-Menu $filter | % { $path = if(!( Test-Path $_ -PathType Container)) { $_ | split-path -leaf } else {$_} ; explorer $path } }
function Every-Menu { param( $filter) $a= @(everything $filter) ; if($a.count -eq 1) {$a} else {menu $a} }
}
if (Test-CommandExists 'git')
{ #todo: move to git aliases
function invoke-gitCheckout () { & git checkout $args }
function invoke-gitFetchOrig { git fetch origin }
Function invoke-GitLazy($path,$message) { cd $path ; git lazy $message } ;
Function invoke-GitLazySilently {Out-File -FilePath .\lazy.log -inputObject (invoke-GitLazy 'AutoCommit' 2>&1 )} ; #todo: parameterize #todo: rename to more descriptive #todo: breakout
function invoke-gitRemote { param ($subCommand = 'get-url',$name = "origin" ) git remote $subCommand $name }
Function invoke-GitSubmoduleAdd([string]$leaf,[string]$remote,[string]$branch) { git submodule add -f --name $leaf -- $remote $branch ; git commit -am $leaf+$remote+$branch } ; #todo: move to git aliases #Git Ad $leaf as submodule from $remote and branch $branch
}
if ( $null -ne $(Get-Module PSReadline -ea SilentlyContinue)) {
function find-historyAppendClipboard($searchstring) { $path = get-historyPath; menu @( get-content $path | where{ $_ -match $searchstring }) | %{ Set-Clipboard -Value $_ }} #search history of past expressions and adds to clipboard
function find-historyInvoke($searchstring) { $path = get-historyPath; menu @( get-content $path | where{ $_ -match $searchstring }) | %{Invoke-Expression $_ } } #search history of past expressions and invokes it, doesn't register the expression itself in history, but the pastDo expression.
}
function split-fileByLineNr { param( $pathName = '.\gron.csv',$OutputFilenamePattern = 'output_done_' , $LineLimit = 60) ;
$ext = $pathName | split-path -Extension
$inputx = Get-Content ;
$line = 0 ;
$i = 0 ;
$path = 0 ;
$start = 0 ;
while ($line -le $inputx.Length) {
if ($i -eq $LineLimit -Or $line -eq $inputx.Length) {
$path++ ;
$pathname = "$OutputFilenamePattern$path$ext" ;
$inputx[$start..($line - 1)] | Out -File $pathname -Force ;
$start = $line ;
$i = 0 ;
Write-Host "$pathname" ;
} ;
$i++ ;
$line++
}
}
function split-fileByMatch($pathName , $regex) { #param( $pathName = 'C:\Users\crbk01\Documents\WindowsPowerShell\snipps\Modules\Todo SplitUp.psm1' , $regex = '(?<=function\s)[^\s\(]*') ;
$ext = ($pathName | split-path -Extension)
$parent = ($pathName | split-path -Parent)
$OriginalName = ($pathName | split-path -LeafBase)
$inputx = Get-Content $pathName; $line = 0 ; $i = 0 ; $start = @(select-string -path $pathName -pattern $regex ) | select linenumber ; $LineLimit = $start | select -Skip 1 ; $names = @() ; [regex]::matches($inputx,$regex).groups.value | %{$names+= $_ }
$occurence = 0 ;
while ($line -le $inputx.Length) {
if ($i -eq ([int]$LineLimit[$occurence].linenumber -1) -Or $line -eq $inputx.Length)
{
$currentName = $names[$occurence];
$pathname = Join-Path -path $parent -childPath "$OriginalName-$currentName$ext" ;
$u = ([int]$start[$occurence].linenumber -1)
$inputx[$u..($line - 1)] > $pathname
$occurence++ ;
Write-Host "$u..($line - 1)$pathname" ;
};
$i++ ;
$line++
}
}
#function aliasCode { & $env:code }
function .. { Set-Location ".." }
function .... { Set-Location (Join-Path -Path ".." -ChildPath "..") }
function all { process { $_ | Select-Object * } } # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7#piping-objects-to-functions
function cdc { Set-Location "$XDG_CONFIG_HOME" }
function cdcheat { Set-Location "$CHEATS_DIR" }
function cdd { Set-Location "$DESKTOP_DIR" }
function cddd { Set-Location "$DEVEL_DIR" }
function cddev { Set-Location "$DEVEL_DIR" }
function cdn { Set-Location "$NOTES_DIR" }
function cdports { Set-Location "$PORTS_DIR" }
function cdt { Set-Location "$TODO_DIR" }
function clear-Days_Back { param( $path = "C:\Support\SQLBac\" ,$Daysback = "0" ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $CurrentDate = Get-Date $DatetoDelete = $CurrentDate.AddDays($Daysback) Get-ChildItem $path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item }
function ConvertFrom-Bytes { param( [string]$bytes, [string]$savepath ) $dir = Split-Path $savepath if (!(Test-Path $dir)) { md $dir | Out-Null } [convert]::FromBase64String($bytes) | Set-Content $savepath -Encoding Byte }
function ConvertTo-Bytes ( [string]$path ) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } [convert]::ToBase64String((Get-Content $path -Encoding Byte)) }
function df { get-volume }
function enter-dir { param( $path = '%USERPROFILE%\Desktop\' ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } Set-Location $Path }; #if no param, navigate to desktop # 5. 更改工作目录 # 输入要切换到的路径 # 用法示例:cd C:/ # 默认路径:D 盘的桌面
function exit-Nrenter { shutdown /r } #reboot
function export($name, $value) { set-item -force -path "env:$name" -value $value; }
function foldercontain($folder,$name) { $q = get-childitem $folder; return $q -contains $name }
function Get-AllNic { Get-NetAdapter | Sort-Object -Property MacAddress } # 1. 获取所有 Network Interface
function get-Childnames { param( $path = $pwd) (Get-ChildItem -path $path).Name ; Write-Host("") }; # 3. 查看目录 ls & ll
function Get-DefaultAliases { Get-Alias | Where-Object { $_.Options -match "ReadOnly" }}
function get-envVar { Get-Childitem -Path Env:*}
function get-EspHeader { param( $path = '.\FormiD.esp', $max = 13,$headerSize = 3 ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $q = ((( -join (gc $path | select -first $headerSize)) -replace "[^\w. ] {1,}","å").split("å") -match "^.*[.](esp |esm)$") ; $q | ? {($q | select -first $max) -NotContains $_}}
function get-historyPath { (Get-PSReadlineOption).HistorySavePath }
function Get-IPv4Routes { Get-NetRoute -AddressFamily IPv4 | Where-Object -FilterScript {$_.NextHop -ne '0.0.0.0'} } # 2. 获取 IPv4 关键路由
function Get-IPv6Routes { Get-NetRoute -AddressFamily IPv6 | Where-Object -FilterScript {$_.NextHop -ne '::'} } # 3. 获取 IPv6 关键路由
function get-isFolder {$PSBoundParameters -is [system.in.folder]}
function get-parameters { Get-Member -Parameter *}
function get-RegInstallpaths { Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | % { Get -ItemProperty $_.PsPath } | Select DisplayName,InstallLocation }
function get-whatpulse { param( $program,$path) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $query = "select rightstr(path,instr(reverse(path),'/') -1) exe,path from (select max(path) path,max(cast(replace(version,'.','') as integer)) version from applications group by case when online_app_id = 0 then name else online_app_id end)" ; $adapter = newSqliteConnection -source (Everything 'whatpulse.db')[0] -query $query ; $b=@($data.item('exe')) ; $a = @($data.item('path')) ; $i=0 ; while($i -lt $a.Length) {$res[$b[$i]]=$a[$i] ; $i++ } ; $res | where { $_.name -match $program -and $_.path -match $path}}
function grep { process { $_ | Select-String -Pattern $args } } # function grep($regex, $dir) { if ( $dir ) { ls $dir | select-string $regex return } $input | select-string $regex }
function grepv($regex) { $input | ? { !$_.Contains($regex) } }
function Initialize-Profile { . $PROFILE.CurrentUserCurrentHost} #function initialize-profile { & $profile } #reload-profile is an unapproved verb.
function invoke-Nmake { nmake.exe $args -nologo }; # 1. 编译函数 make
function invoke-powershellAsAdmin { Start-Process powershell -Verb runAs } #new ps OpenAsADmin
function join-ByRuncunfig { param( $prefix='[$]APPLICATION_CONFIG_DIR[$][/]'
,$refixReplace='C:\Users\crbk01\AppData\Roaming\JetBrains\DataGrip2021.1\',
$runconfig="TillMinaMedelanden.run.xml",$output='runConfig/Combined.sql') [xml]$xml=get -content $runConfig -Encoding UTF8 ; $xml.component.configuration.'script -file' | %
{$_.value -replace $prefix, ($prefixReplace -replace '\\','/')} | % {" - -:$_"
; get -content -path $_ -Encoding UTF8 ; "go" } >> $output }
function list { process { $_ | Format-List * } } # fl is there by default
function man { Get-Help $args[0] | out-host -paging }
function md { New-Item -type directory -path (Join-Path "$args" -ChildPath "") }
function measure-ExtOccurenseRecursivly { param( $path = "D:\Project Shelf\MapBasic" ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } Get-ChildItem -Path $path -Recurse -File | group Extension -NoElement | sort Count -Descending | select -Property name }
function measure-words { param( $inputStream = (Get -ChildItem | % { Get -Content $_.name }), $regex="[^a-z0-9_-]") $hash = @{} ; $a="" ; $inputStream | % {$a+=$_} ; $a -split $regex | % { $_.tolower()} | % {$hash[$_]++} ; $sorted= % {$hash.GetEnumerator() | sort -object {[int]$_.value}} ; return $sorted} ; $sorted | where{$_.name -notmatch "^\d+$"} | where{$_.name.length -gt 4 }
function mkdir { New-Item -type directory -path (Join-Path "$args" -ChildPath "") }
function My-Scripts { Get-Command -CommandType externalscript }
function open-here { param( $Path = $pwd ) Invoke-Item $Path }; # 4. 打开当前工作目录 # 输入要打开的路径 # 用法示例:open C:\ # 默认路径:当前工作文件夹
function open-ProfileFolder { explorer (split-path -path $profile -parent)}
function pgrep($name) { Get-Process $name }
function pkill($name) { Get-Process $name -ErrorAction SilentlyContinue | kill }
function pull () { & get pull $args }
function read-aliases { Get-Alias | Where-Object { $_.Options -notmatch "ReadOnly" }}
function read-EnvPaths { ($Env:Path).Split(";") }
function read-headOfFile { param( $linr = 10, $path ) if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } gc -Path $path -TotalCount $linr }
function read-json { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PSCustomObject] $input ) $json = [ordered]@{}; ($input).PSObject.Properties | % { $json[$_.Name] = $_.Value } $json.SyncRoot }
function read-paramNaliases ($command) { (Get-Command $command).parameters.values | select name, @{n='aliases';e={$_.aliases}} }
function read-pathsAsStream { get-childitem | out-string -stream } # filesInFolAsStream ;
function read-uptime { Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime'; EXPRESSION= {$_.ConverttoDateTime($_.lastbootuptime)}} } #doesn't psreadline module implement this already?
function Remove-CustomAliases { Get-Alias | Where-Object { ! $_.Options -match "ReadOnly" } | % { Remove-Item alias:$_ }} # https://stackoverflow.com/a/2816523
function remove-TempfilesNfolders { foreach ($folder in get-tempfilesNfolders) {Remove-Item $folder -force -recurse} }
function Sanatize-path { param( $path='G:\mhk',$replaceChar='_') if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } $regex= "[^\)\w \\\ -:.åäöÅÄÖ %\ {,~$\(!@¤£é&=#§]" ; Get -ChildItem $path -Recurse | Where -Object {$_.name -match $regex} | rename -item -newName {$_.name -replace $regex,$replaceChar}}
function sed($path, $find, $replace) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } (Get-Content $path).replace("$find", $replace) | Set-Content $path }
function set-FileEncodingUtf8 ( [string]$path ) { if (!$path -or !(Test-Path $path)) { throw "file not found: '$path'" } sc $path -encoding utf8 -value(gc $path) }
function set-x { Set-PSDebug -trace 2}
function set+x { Set-PSDebug -trace 0}
function sort-PathByLvl { param( $inputList) $inputList | Sort {($_ -split '\\').Count}, {$_} -Descending | select -object -first 2 | % { $error.clear() ; try { out -null -input (test -ModuleManifest $_ > '&2>&1' ) } catch { "Error" } ; if (!$error) { $_ } }}
function start-BrowserFlags { vivaldi "vivaldi://flags" } #todo: use standard browser instead of hardcoded
function start-notepad-profile { notepad $profile}
function string { process { $_ | Out-String -Stream } }
function touch($path) { "" | Out-File $path -Encoding ASCII }
function which($name) { Get-Command $name | Select-Object -ExpandProperty Definition } #should use more
Remove-Item alias:ls -ea SilentlyContinue ; function ls { Get-Childitem} # ls -al is musclememory by now so ignore all args for this "alias"
#------------------------------- Functions END -------------------------------
#------------------------------- Set alias BEGIN -------------------------------
$TAType = [psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators") ; $TAType::Add('accelerators',$TAType)
set-alias accelerators [accelerators]::Get
set-alias edprofile start-Notepad-Profile
set-alias exp-pro open-ProfileFolder
set-alias kidStream get-childitem | out-string -stream
set-alias history (Get-PSReadlineOption).HistorySavePath
set-alias parameters get-parameters
set-alias start-su start-powershellAsAdmin
set-alias version $PSVersionTable # bash-like
Set-Alias cat Get-Content -Option AllScope
Set-Alias cd Set-Location -Option AllScope
Set-Alias clear Clear-Host -Option AllScope
Set-Alias cp Copy-Item -Option AllScope
Set-Alias history Get-History -Option AllScope
Set-Alias kill Stop-Process -Option AllScope
Set-Alias lp Out-Printer -Option AllScope
Set-Alias mv Move-Item -Option AllScope
Set-Alias ps Get-Process -Option AllScope
Set-Alias pwd Get-Location -Option AllScope
Set-Alias which Get-Command -Option AllScope
Set-Alias open Invoke-Item -Option AllScope
Set-Alias basename Split-Path -Option AllScope
Set-Alias realpath Resolve-Path -Option AllScope # cmd-like Set-Alias rm Remove-Item -Option AllScope
Set-Alias rmdir Remove-Item -Option AllScope
Set-Alias echo Write-Output -Option AllScope
Set-Alias cls Clear-Host -Option AllScope
Set-Alias chdir Set-Location -Option AllScope
Set-Alias copy Copy-Item -Option AllScope
Set-Alias del Remove-Item -Option AllScope
Set-Alias dir Get-Childitem -Option AllScope
Set-Alias erase Remove-Item -Option AllScope
Set-Alias move Move-Item -Option AllScope
Set-Alias rd Remove-Item -Option AllScope
Set-Alias ren Rename-Item -Option AllScope
Set-Alias set Set-Variable -Option AllScope
Set-Alias type Get-Content -Option AllScope
Set-Alias env Get-Environment -Option AllScope # custom aliases
Set-Alias flush-dns Clear-DnsClientCache -Option AllScope
Set-Alias touch Set-FileTime -Option AllScope
set-alias lsx get-Childnames -Option AllScope
set-alias filesinfolasstream read-childrenAsStream -Option AllScope
set-alias bcompare start-bc -Option AllScope
set-alias GitAdEPathAsSNB invoke-GitSubmoduleAdd -Option AllScope
set-alias GitUp invoke-GitLazy -Option AllScope
set-alias gitSilently invoke-GitLazySilently -Option AllScope
set-alias gitSingleRemote invoke-gitFetchOrig -Option AllScope
set-alias executeThis invoke-FuzzyWithEverything -Option AllScope
set-alias filesinfolasstream read-pathsAsStream -Option AllScope
set-alias everything invoke-Everything -Option AllScope
set-alias make invoke-Nmake -Option AllScope
set-alias MyAliases read-aliases -Option AllScope
set-alias OpenAsADmin invoke-powershellAsAdmin -Option AllScope
set-alias home open-here -Option AllScope
set-alias pastDo find-historyInvoke -Option AllScope
set-alias pastDoEdit find-historyAppendClipboard -Option AllScope
set-alias HistoryPath (Get-PSReadlineOption).HistorySavePath -Option AllScope
set-alias reboot exit-Nrenter -Option AllScope
set-alias browserflags start-BrowserFlags -Option AllScope
set-alias df get-volume -Option AllScope
set-alias printpaths read-EnvPaths -Option AllScope
set-alias reload initialize-profile -Option AllScope
set-alias uptime read-uptime -Option AllScope
set-alias getnic get-mac -Option AllScope # 1. 获取所有 Network Interface set-alias ll Get-ChildItem -Option AllScope
set-alias getip Get-IPv4Routes -Option AllScope
set-alias getip6 Get-IPv6Routes -Option AllScope
set-alias os-update Update-Packages -Option AllScope
set-alias remote invoke-gitRemote -Option AllScope
set-alias gitsplit subtree-split-rm-commit -Option AllScope
set-alias isFolder get-isFolder -Option AllScope
set-alias start-powershellAsAdmin invoke-powershellAsAdmin -Option AllScope
set-alias psVersion $PSVersionTable.PSVersion.Major -Option AllScope
#------------------------------- Set alias END -------------------------------
Write-Host "PSVersion: $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)"
Write-Host "PSEdition: $($PSVersionTable.PSEdition)"
Write-Host "Profile: $PSCommandPath"
# Alias File
# Computer : 5CG84229D5
# Date/Time : 28 June 2022 13:24:18
# Exported by : crbk01
set-alias -Name:"accelerators" -Value:"[accelerators]::Get" -Description:"" -Option:"None"
set-alias -Name:"basename" -Value:"Split-Path" -Description:"" -Option:"AllScope"
set-alias -Name:"bcompare" -Value:"start-bc" -Description:"" -Option:"AllScope"
set-alias -Name:"browserflags" -Value:"start-BrowserFlags" -Description:"" -Option:"AllScope"
set-alias -Name:"cat" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"cd" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"chdir" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"clear" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"cls" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"copy" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"cp" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"del" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"df" -Value:"get-volume" -Description:"" -Option:"AllScope"
set-alias -Name:"dir" -Value:"Get-Childitem" -Description:"" -Option:"AllScope"
set-alias -Name:"echo" -Value:"Write-Output" -Description:"" -Option:"AllScope"
set-alias -Name:"edprofile" -Value:"start-Notepad-Profile" -Description:"" -Option:"None"
set-alias -Name:"env" -Value:"Get-Environment" -Description:" custom aliases" -Option:"AllScope"
set-alias -Name:"erase" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"etsn" -Value:"Enter-PSSession" -Description:"" -Option:"None"
set-alias -Name:"everything" -Value:"invoke-Everything" -Description:"" -Option:"AllScope"
set-alias -Name:"executeThis" -Value:"invoke-FuzzyWithEverything" -Description:"" -Option:"AllScope"
set-alias -Name:"exp-pro" -Value:"open-ProfileFolder" -Description:"" -Option:"None"
set-alias -Name:"exsn" -Value:"Exit-PSSession" -Description:"" -Option:"None"
set-alias -Name:"fhx" -Value:"Format-Hex" -Description:"" -Option:"None"
set-alias -Name:"filesinfolasstream" -Value:"read-pathsAsStream" -Description:"" -Option:"AllScope"
set-alias -Name:"flush-dns" -Value:"Clear-DnsClientCache" -Description:"" -Option:"AllScope"
set-alias -Name:"gcb" -Value:"Get-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"getip" -Value:"Get-IPv4Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getip6" -Value:"Get-IPv6Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getnic" -Value:"get-mac" -Description:"" -Option:"AllScope"
set-alias -Name:"gin" -Value:"Get-ComputerInfo" -Description:"" -Option:"None"
set-alias -Name:"GitAdEPathAsSNB" -Value:"invoke-GitSubmoduleAdd" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSilently" -Value:"invoke-GitLazySilently" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSingleRemote" -Value:"invoke-gitFetchOrig" -Description:"" -Option:"AllScope"
set-alias -Name:"gitsplit" -Value:"subtree-split-rm-commit" -Description:"" -Option:"AllScope"
set-alias -Name:"GitUp" -Value:"invoke-GitLazy" -Description:"" -Option:"AllScope"
set-alias -Name:"gjb" -Value:"Get-Job" -Description:"" -Option:"None"
set-alias -Name:"gsn" -Value:"Get-PSSession" -Description:"" -Option:"None"
set-alias -Name:"gtz" -Value:"Get-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"h" -Value:"Get-History" -Description:"" -Option:"None"
set-alias -Name:"history" -Value:"Get-History" -Description:"" -Option:"AllScope"
set-alias -Name:"HistoryPath" -Value:"(Get-PSReadlineOption).HistorySavePath" -Description:"" -Option:"AllScope"
set-alias -Name:"home" -Value:"open-here" -Description:"" -Option:"AllScope"
set-alias -Name:"icm" -Value:"Invoke-Command" -Description:"" -Option:"None"
set-alias -Name:"isFolder" -Value:"get-isFolder" -Description:"" -Option:"AllScope"
set-alias -Name:"kill" -Value:"Stop-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"lp" -Value:"Out-Printer" -Description:"" -Option:"AllScope"
set-alias -Name:"ls" -Value:"Get-ChildItem" -Description:"" -Option:"None"
set-alias -Name:"lsx" -Value:"get-Childnames" -Description:"" -Option:"AllScope"
set-alias -Name:"make" -Value:"invoke-Nmake" -Description:"" -Option:"AllScope"
set-alias -Name:"man" -Value:"help" -Description:"" -Option:"None"
set-alias -Name:"md" -Value:"mkdir" -Description:"" -Option:"AllScope"
set-alias -Name:"mount" -Value:"New-PSDrive" -Description:"" -Option:"None"
set-alias -Name:"move" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"mv" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"MyAliases" -Value:"read-aliases" -Description:"" -Option:"AllScope"
set-alias -Name:"nsn" -Value:"New-PSSession" -Description:"" -Option:"None"
set-alias -Name:"open" -Value:"Invoke-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"OpenAsADmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"os-update" -Value:"Update-Packages" -Description:"" -Option:"AllScope"
set-alias -Name:"parameters" -Value:"get-parameters" -Description:"" -Option:"None"
set-alias -Name:"pastDo" -Value:"find-historyInvoke" -Description:"" -Option:"AllScope"
set-alias -Name:"pastDoEdit" -Value:"find-historyAppendClipboard" -Description:"" -Option:"AllScope"
set-alias -Name:"popd" -Value:"Pop-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"printpaths" -Value:"read-EnvPaths" -Description:"" -Option:"AllScope"
set-alias -Name:"ps" -Value:"Get-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"psVersion" -Value:"$PSVersionTable.PSVersion.Major " -Description:"" -Option:"AllScope"
set-alias -Name:"pushd" -Value:"Push-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"pwd" -Value:"Get-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"r" -Value:"Invoke-History" -Description:"" -Option:"None"
set-alias -Name:"rcjb" -Value:"Receive-Job" -Description:"" -Option:"None"
set-alias -Name:"rd" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"realpath" -Value:"Resolve-Path" -Description:"cmd-like" -Option:"AllScope"
set-alias -Name:"reboot" -Value:"exit-Nrenter" -Description:"" -Option:"AllScope"
set-alias -Name:"refreshenv" -Value:"Update-SessionEnvironment" -Description:"" -Option:"None"
set-alias -Name:"reload" -Value:"initialize-profile" -Description:"" -Option:"AllScope"
set-alias -Name:"remote" -Value:"invoke-gitRemote" -Description:"" -Option:"AllScope"
set-alias -Name:"ren" -Value:"Rename-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rjb" -Value:"Remove-Job" -Description:"" -Option:"None"
set-alias -Name:"rm" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rmdir" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rsn" -Value:"Remove-PSSession" -Description:"" -Option:"None"
set-alias -Name:"sajb" -Value:"Start-Job" -Description:"" -Option:"None"
set-alias -Name:"scb" -Value:"Set-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"set" -Value:"Set-Variable" -Description:"" -Option:"AllScope"
set-alias -Name:"sls" -Value:"Select-String" -Description:"" -Option:"None"
set-alias -Name:"spjb" -Value:"Stop-Job" -Description:"" -Option:"None"
set-alias -Name:"start-powershellAsAdmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"start-su" -Value:"start-powershellAsAdmin" -Description:"" -Option:"None"
set-alias -Name:"stz" -Value:"Set-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"touch" -Value:"Set-FileTime" -Description:"" -Option:"AllScope"
set-alias -Name:"type" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"uptime" -Value:"read-uptime" -Description:"" -Option:"AllScope"
set-alias -Name:"version" -Value:"System.Management.Automation.PSVersionHashTable" -Description:"bash-like" -Option:"None"
set-alias -Name:"which" -Value:"Get-Command" -Description:"" -Option:"AllScope"
set-alias -Name:"wjb" -Value:"Wait-Job" -Description:"" -Option:"None"
# Alias File
# Exported by : crbk01
# Date/Time : 28 June 2022 13:23:03
# Computer : 5CG84229D5
set-alias -Name:"foreach" -Value:"ForEach-Object" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"%" -Value:"ForEach-Object" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"where" -Value:"Where-Object" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"?" -Value:"Where-Object" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"clc" -Value:"Clear-Content" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cli" -Value:"Clear-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"clp" -Value:"Clear-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"clv" -Value:"Clear-Variable" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cpi" -Value:"Copy-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cvpa" -Value:"Convert-Path" -Description:"" -Option:"ReadOnly"
set-alias -Name:"dbp" -Value:"Disable-PSBreakpoint" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ebp" -Value:"Enable-PSBreakpoint" -Description:"" -Option:"ReadOnly"
set-alias -Name:"epal" -Value:"Export-Alias" -Description:"" -Option:"ReadOnly"
set-alias -Name:"epcsv" -Value:"Export-Csv" -Description:"" -Option:"ReadOnly"
set-alias -Name:"fl" -Value:"Format-List" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ft" -Value:"Format-Table" -Description:"" -Option:"ReadOnly"
set-alias -Name:"fw" -Value:"Format-Wide" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gal" -Value:"Get-Alias" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gbp" -Value:"Get-PSBreakpoint" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gc" -Value:"Get-Content" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gci" -Value:"Get-ChildItem" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gcm" -Value:"Get-Command" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gdr" -Value:"Get-PSDrive" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gcs" -Value:"Get-PSCallStack" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ghy" -Value:"Get-History" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gi" -Value:"Get-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gl" -Value:"Get-Location" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gm" -Value:"Get-Member" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gmo" -Value:"Get-Module" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gp" -Value:"Get-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gpv" -Value:"Get-ItemPropertyValue" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gps" -Value:"Get-Process" -Description:"" -Option:"ReadOnly"
set-alias -Name:"group" -Value:"Group-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gu" -Value:"Get-Unique" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gv" -Value:"Get-Variable" -Description:"" -Option:"ReadOnly"
set-alias -Name:"iex" -Value:"Invoke-Expression" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ihy" -Value:"Invoke-History" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ii" -Value:"Invoke-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ipmo" -Value:"Import-Module" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ipal" -Value:"Import-Alias" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ipcsv" -Value:"Import-Csv" -Description:"" -Option:"ReadOnly"
set-alias -Name:"measure" -Value:"Measure-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"mi" -Value:"Move-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"mp" -Value:"Move-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"nal" -Value:"New-Alias" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ndr" -Value:"New-PSDrive" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ni" -Value:"New-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"nv" -Value:"New-Variable" -Description:"" -Option:"ReadOnly"
set-alias -Name:"nmo" -Value:"New-Module" -Description:"" -Option:"ReadOnly"
set-alias -Name:"oh" -Value:"Out-Host" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rbp" -Value:"Remove-PSBreakpoint" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rdr" -Value:"Remove-PSDrive" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ri" -Value:"Remove-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rni" -Value:"Rename-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rnp" -Value:"Rename-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rp" -Value:"Remove-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rmo" -Value:"Remove-Module" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rv" -Value:"Remove-Variable" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gerr" -Value:"Get-Error" -Description:"" -Option:"ReadOnly"
set-alias -Name:"rvpa" -Value:"Resolve-Path" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sal" -Value:"Set-Alias" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sbp" -Value:"Set-PSBreakpoint" -Description:"" -Option:"ReadOnly"
set-alias -Name:"select" -Value:"Select-Object" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"si" -Value:"Set-Item" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sl" -Value:"Set-Location" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sp" -Value:"Set-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"saps" -Value:"Start-Process" -Description:"" -Option:"ReadOnly"
set-alias -Name:"spps" -Value:"Stop-Process" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sv" -Value:"Set-Variable" -Description:"" -Option:"ReadOnly"
set-alias -Name:"irm" -Value:"Invoke-RestMethod" -Description:"" -Option:"ReadOnly"
set-alias -Name:"iwr" -Value:"Invoke-WebRequest" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ac" -Value:"Add-Content" -Description:"" -Option:"ReadOnly"
set-alias -Name:"clear" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"compare" -Value:"Compare-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cpp" -Value:"Copy-ItemProperty" -Description:"" -Option:"ReadOnly"
set-alias -Name:"diff" -Value:"Compare-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gsv" -Value:"Get-Service" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sleep" -Value:"Start-Sleep" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sort" -Value:"Sort-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"start" -Value:"Start-Process" -Description:"" -Option:"ReadOnly"
set-alias -Name:"sasv" -Value:"Start-Service" -Description:"" -Option:"ReadOnly"
set-alias -Name:"spsv" -Value:"Stop-Service" -Description:"" -Option:"ReadOnly"
set-alias -Name:"tee" -Value:"Tee-Object" -Description:"" -Option:"ReadOnly"
set-alias -Name:"write" -Value:"Write-Output" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cat" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"cp" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"ls" -Value:"Get-ChildItem" -Description:"" -Option:"None"
set-alias -Name:"man" -Value:"help" -Description:"" -Option:"None"
set-alias -Name:"mount" -Value:"New-PSDrive" -Description:"" -Option:"None"
set-alias -Name:"mv" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"ps" -Value:"Get-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"rm" -Value:"Remove-Item" -Description:"" -Option:"None"
set-alias -Name:"rmdir" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"cnsn" -Value:"Connect-PSSession" -Description:"" -Option:"ReadOnly"
set-alias -Name:"dnsn" -Value:"Disconnect-PSSession" -Description:"" -Option:"ReadOnly"
set-alias -Name:"ogv" -Value:"Out-GridView" -Description:"" -Option:"ReadOnly"
set-alias -Name:"shcm" -Value:"Show-Command" -Description:"" -Option:"ReadOnly"
set-alias -Name:"cd" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"dir" -Value:"Get-Childitem" -Description:"" -Option:"AllScope"
set-alias -Name:"echo" -Value:"Write-Output" -Description:"" -Option:"AllScope"
set-alias -Name:"fc" -Value:"Format-Custom" -Description:"" -Option:"ReadOnly"
set-alias -Name:"kill" -Value:"Stop-Process" -Description:"" -Option:"AllScope"
set-alias -Name:"pwd" -Value:"Get-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"type" -Value:"Get-Content" -Description:"" -Option:"AllScope"
set-alias -Name:"h" -Value:"Get-History" -Description:"" -Option:"None"
set-alias -Name:"history" -Value:"Get-History" -Description:"" -Option:"AllScope"
set-alias -Name:"md" -Value:"mkdir" -Description:"" -Option:"AllScope"
set-alias -Name:"popd" -Value:"Pop-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"pushd" -Value:"Push-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"r" -Value:"Invoke-History" -Description:"" -Option:"None"
set-alias -Name:"cls" -Value:"Clear-Host" -Description:"" -Option:"AllScope"
set-alias -Name:"chdir" -Value:"Set-Location" -Description:"" -Option:"AllScope"
set-alias -Name:"copy" -Value:"Copy-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"del" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"erase" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"move" -Value:"Move-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"rd" -Value:"Remove-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"ren" -Value:"Rename-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"set" -Value:"Set-Variable" -Description:"" -Option:"AllScope"
set-alias -Name:"icm" -Value:"Invoke-Command" -Description:"" -Option:"None"
set-alias -Name:"clhy" -Value:"Clear-History" -Description:"" -Option:"ReadOnly"
set-alias -Name:"gjb" -Value:"Get-Job" -Description:"" -Option:"None"
set-alias -Name:"rcjb" -Value:"Receive-Job" -Description:"" -Option:"None"
set-alias -Name:"rjb" -Value:"Remove-Job" -Description:"" -Option:"None"
set-alias -Name:"sajb" -Value:"Start-Job" -Description:"" -Option:"None"
set-alias -Name:"spjb" -Value:"Stop-Job" -Description:"" -Option:"None"
set-alias -Name:"wjb" -Value:"Wait-Job" -Description:"" -Option:"None"
set-alias -Name:"nsn" -Value:"New-PSSession" -Description:"" -Option:"None"
set-alias -Name:"gsn" -Value:"Get-PSSession" -Description:"" -Option:"None"
set-alias -Name:"rsn" -Value:"Remove-PSSession" -Description:"" -Option:"None"
set-alias -Name:"etsn" -Value:"Enter-PSSession" -Description:"" -Option:"None"
set-alias -Name:"rcsn" -Value:"Receive-PSSession" -Description:"" -Option:"ReadOnly"
set-alias -Name:"exsn" -Value:"Exit-PSSession" -Description:"" -Option:"None"
set-alias -Name:"sls" -Value:"Select-String" -Description:"" -Option:"None"
set-alias -Name:"gcb" -Value:"Get-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"gin" -Value:"Get-ComputerInfo" -Description:"" -Option:"None"
set-alias -Name:"gtz" -Value:"Get-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"scb" -Value:"Set-Clipboard" -Description:"" -Option:"None"
set-alias -Name:"stz" -Value:"Set-TimeZone" -Description:"" -Option:"None"
set-alias -Name:"fhx" -Value:"Format-Hex" -Description:"" -Option:"None"
set-alias -Name:"accelerators" -Value:"[accelerators]::Get" -Description:"" -Option:"None"
set-alias -Name:"edprofile" -Value:"start-Notepad-Profile" -Description:"" -Option:"None"
set-alias -Name:"exp-pro" -Value:"open-ProfileFolder" -Description:"" -Option:"None"
set-alias -Name:"kidStream" -Value:"get-childitem" -Description:"" -Option:"None"
set-alias -Name:"parameters" -Value:"get-parameters" -Description:"" -Option:"None"
set-alias -Name:"start-su" -Value:"start-powershellAsAdmin" -Description:"" -Option:"None"
set-alias -Name:"version" -Value:"System.Management.Automation.PSVersionHashTable" -Description:"" -Option:"None"
set-alias -Name:"lp" -Value:"Out-Printer" -Description:"" -Option:"AllScope"
set-alias -Name:"which" -Value:"Get-Command" -Description:"" -Option:"AllScope"
set-alias -Name:"open" -Value:"Invoke-Item" -Description:"" -Option:"AllScope"
set-alias -Name:"basename" -Value:"Split-Path" -Description:"" -Option:"AllScope"
set-alias -Name:"realpath" -Value:"Resolve-Path" -Description:"" -Option:"AllScope"
set-alias -Name:"env" -Value:"Get-Environment" -Description:"" -Option:"AllScope"
set-alias -Name:"flush-dns" -Value:"Clear-DnsClientCache" -Description:"" -Option:"AllScope"
set-alias -Name:"touch" -Value:"Set-FileTime" -Description:"" -Option:"AllScope"
set-alias -Name:"lsx" -Value:"get-Childnames" -Description:"" -Option:"AllScope"
set-alias -Name:"filesinfolasstream" -Value:"read-pathsAsStream" -Description:"" -Option:"AllScope"
set-alias -Name:"bcompare" -Value:"start-bc" -Description:"" -Option:"AllScope"
set-alias -Name:"GitAdEPathAsSNB" -Value:"invoke-GitSubmoduleAdd" -Description:"" -Option:"AllScope"
set-alias -Name:"GitUp" -Value:"invoke-GitLazy" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSilently" -Value:"invoke-GitLazySilently" -Description:"" -Option:"AllScope"
set-alias -Name:"gitSingleRemote" -Value:"invoke-gitFetchOrig" -Description:"" -Option:"AllScope"
set-alias -Name:"executeThis" -Value:"invoke-FuzzyWithEverything" -Description:"" -Option:"AllScope"
set-alias -Name:"everything" -Value:"invoke-Everything" -Description:"" -Option:"AllScope"
set-alias -Name:"make" -Value:"invoke-Nmake" -Description:"" -Option:"AllScope"
set-alias -Name:"MyAliases" -Value:"read-aliases" -Description:"" -Option:"AllScope"
set-alias -Name:"OpenAsADmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"home" -Value:"open-here" -Description:"" -Option:"AllScope"
set-alias -Name:"pastDo" -Value:"find-historyInvoke" -Description:"" -Option:"AllScope"
set-alias -Name:"pastDoEdit" -Value:"find-historyAppendClipboard" -Description:"" -Option:"AllScope"
set-alias -Name:"HistoryPath" -Value:"C:\Users\crbk01\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt" -Description:"" -Option:"AllScope"
set-alias -Name:"reboot" -Value:"exit-Nrenter" -Description:"" -Option:"AllScope"
set-alias -Name:"browserflags" -Value:"start-BrowserFlags" -Description:"" -Option:"AllScope"
set-alias -Name:"df" -Value:"get-volume" -Description:"" -Option:"AllScope"
set-alias -Name:"printpaths" -Value:"read-EnvPaths" -Description:"" -Option:"AllScope"
set-alias -Name:"reload" -Value:"initialize-profile" -Description:"" -Option:"AllScope"
set-alias -Name:"uptime" -Value:"read-uptime" -Description:"" -Option:"AllScope"
set-alias -Name:"getnic" -Value:"get-mac" -Description:"" -Option:"AllScope"
set-alias -Name:"getip" -Value:"Get-IPv4Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"getip6" -Value:"Get-IPv6Routes" -Description:"" -Option:"AllScope"
set-alias -Name:"os-update" -Value:"Update-Packages" -Description:"" -Option:"AllScope"
set-alias -Name:"remote" -Value:"invoke-gitRemote" -Description:"" -Option:"AllScope"
set-alias -Name:"gitsplit" -Value:"subtree-split-rm-commit" -Description:"" -Option:"AllScope"
set-alias -Name:"isFolder" -Value:"get-isFolder" -Description:"" -Option:"AllScope"
set-alias -Name:"start-powershellAsAdmin" -Value:"invoke-powershellAsAdmin" -Description:"" -Option:"AllScope"
set-alias -Name:"psVersion" -Value:"7" -Description:"" -Option:"AllScope"
set-alias -Name:"refreshenv" -Value:"Update-SessionEnvironment" -Description:"" -Option:"None"
function setProfile($p,$g) { Set-Content -Path $p -Value $g }
$gitInvoke = { param([ref]$gist,[ref]$gistProfile) $gist.value = Invoke-RestMethod $gistUrl -ErrorAction Stop ;
$gistProfile.value = $gist.Files."profile.ps1".Content }
function versionSetCheck
{ param([ref]$cv,[ref]$cp) $cv.value = "0.0.0"
if ($cp.value -match $versionRegEx) {
$cv.value = $matches.Version
}
return cv.value
}
$tryUpdateProfile = {
param ($gistUrl, $latestVersionFile, $versionRegEx)
try {
& $gitInvoke ([ref]$gist,[ref]$gistprofile)
versionSetCheck ([ref]$gistVersion,[ref]$gistProfile)
setProfile $latestVersionFile $gistVersion
Write-Verbose "Installed newer version of profile" -Verbose
. $profile
return
}
catch {
# we can hit rate limit issue with GitHub since we're using anonymous
Write-Verbose -Verbose "Was not able to access gist to check for newer version"
}
}
function Initialize-Profile {
$null = Start-ThreadJob -Name "Get version of `$profile from gist" -ArgumentList $gistUrl, $latestVersionFile, $versionRegEx -ScriptBlock
$tryUpdateProfile
if ((Get-Module PSReadLine).Version -lt 2.2) {
throw "Profile requires PSReadLine 2.2+"
}
}
function prompt {
Write-Verbose "Your version: $currentVersion" -Verbose; Write-Verbose "New version: $latestVersion" -Verbose
$choice = Read-Host -Prompt "Found newer profile, install? (Y)"
if ($choice -eq "Y" -or $choice -eq "") {
Initialize-Profile
}
$global:LASTEXITCODE = $currentLastExitCode
}
if ([System.IO.File]::Exists($latestVersionFile)) {
$latestVersion = [System.IO.File]::ReadAllText($latestVersionFile)
$currentProfile = [System.IO.File]::ReadAllText($profile)
if ([version]$latestVersion -gt (versionSetCheck ([ref]$currentVersion,[ref]$currentProfile))) {
prompt
}
}
<#
* FileName: Microsoft.PowerShell_profile.ps1
* Author: perXautomatik
* Email: christoffer.broback@gmail.com
* Date: 08/03/2022
* Copyright: No copyright. You can use this code for anything with no warranty.
#>
#loadMessage
echo "Microsoft.PowerShell_profile.ps1"
# Increase history
$MaximumHistoryCount = 10000
#src: https://stackoverflow.com/a/34098997/7595318
function Test-IsInteractive {
# Test each Arg for match of abbreviated '-NonInteractive' command.
$NonInteractiveFlag = [Environment]::GetCommandLineArgs() | Where-Object{ $_ -like '-NonInteractive' }
if ( (-not [Environment]::UserInteractive) -or ( $NonInteractiveFlag -ne $null ) ) {
return $false
}
return $true
}
#if ( Test-IsInteractive ) { (preferably use -noLogo) } # Clear-Host # remove advertisements
function Download-Latest-Profile {
New-Item $( Split-Path $($PROFILE.CurrentUserCurrentHost) ) -ItemType Directory -ea 0
if ( $(Get-Content "$($PROFILE.CurrentUserCurrentHost)" | Select-String "62a71500a0f044477698da71634ab87b" | Out-String) -eq "" ) {
Move-Item -Path "$($PROFILE.CurrentUserCurrentHost)" -Destination "$($PROFILE.CurrentUserCurrentHost).bak"
}
Invoke-WebRequest -Uri "https://gist.githubusercontent.com/apfelchips/62a71500a0f044477698da71634ab87b/raw/Profile.ps1" -OutFile "$($PROFILE.CurrentUserCurrentHost)"
Reload-Profile
}
# Produce UTF-8 by default
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8' # Fix Encoding for PS 5.1 https://stackoverflow.com/a/40098904
}
#------------------------------- Set Paths -------------------------------
$paths = join-path -Path (split-path $profile -Parent) -ChildPath 'setPaths.ps1'
Import-Module $paths
#------------------------------- Set Paths end -------------------------------
#------------------------------- Import Modules BEGIN -------------------------------
$profileFolder = (split-path $profile -Parent)
$pos = join-path -Path $profileFolder -ChildPath 'importModules.ps1'
Import-Module $pos
#------------------------------- Import Modules END -------------------------------
#------------------------------- overloading begin
#https://www.sapien.com/blog/2014/10/21/a-better-tostring-method-for-hash-tables/
#better hashtable ToString method
Update-TypeData -TypeName "System.Collections.HashTable" `
-MemberType ScriptMethod `
-MemberName "ToString" -Value { $hashstr = "@{"; $keys = $this.keys; foreach ($key in $keys) { $v = $this[$key];
if ($key -match "\s") { $hashstr += "`"$key`"" + "=" + "`"$v`"" + ";" }
else { $hashstr += $key + "=" + "`"$v`"" + ";" } }; $hashstr += "}";
return $hashstr }
#------------------------------- overloading end
#------------------------------- SystemMigration -------------------------------
#choco check if installed
#path to list of aps to install
#choco ask to install if not present
#list of portable apps,download source
#path
#download and extract if not present, ask to confirm
#path to portable apps
#path to standard download location
#git Repos paths and origions,
#git systemwide profile folder
#git global path
#everything data folder
#autohotkey script to run on startup
#startup programs
#reg to add if not present
#------------------------------- SystemMigration end -------------------------------
#------------------------------- Styling begin --------------------------------------
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
#------------------------------- Styling begin --------------------------------------
if ( (($error.length | group).name -eq $null ) -and (Test-IsInteractive) ) {
Clear-Host # remove advertisements (preferably use -noLogo)
}
# Keep the existing window title
if ( $(Test-CommandExists 'get-title') )
{
$windowTitle = (get-title).Trim()
if ($windowTitle.StartsWith("Administrator:")) {
$windowTitle = $windowTitle.Substring(14).Trim()
}
}
$nextId = (get-history -count 1).Id + 1;
# KevMar logging
function prompt {
$lastSuccess = $?
$color = @{
Reset = "`e[0m"
Red = "`e[31;1m"
Green = "`e[32;1m"
Yellow = "`e[33;1m"
Grey = "`e[37m"
}
# set color of PS based on success of last execution
if ($lastSuccess -eq $false) {
$lastExit = $color.Red
} else {
$lastExit = $color.Green
}
# get the execution time of the last command
$lastCmdTime = ""
$lastCmd = Get-History -Count 1
if ($null -ne $lastCmd) {
$cmdTime = $lastCmd.Duration.TotalMilliseconds
$units = "ms"
$timeColor = $color.Green
if ($cmdTime -gt 250 -and $cmdTime -lt 1000) {
$timeColor = $color.Yellow
} elseif ($cmdTime -ge 1000) {
$timeColor = $color.Red
$units = "s"
$cmdTime = $lastCmd.Duration.TotalSeconds
if ($cmdTime -ge 60) {
$units = "m"
$cmdTIme = $lastCmd.Duration.TotalMinutes
}
}
$lastCmdTime = "$($color.Grey)[$timeColor$($cmdTime.ToString("#.##"))$units$($color.Grey)]$($color.Reset) "
}
# get git branch information if in a git folder or subfolder
$gitBranch = ""
$path = Get-Location
while ($path -ne "") {
if (Test-Path (Join-Path $path .git)) {
$branch = git rev-parse --abbrev-ref --symbolic-full-name --% @{u}
# handle case where branch is local
if ($lastexitcode -ne 0) {
$branch = git rev-parse --abbrev-ref HEAD
}
$branchColor = $color.Green
if ($branch -match "/master") {
$branchColor = $color.Red
}
$gitBranch = " $($color.Grey)[$branchColor$branch$($color.Grey)]$($color.Reset)"
break
}
$path = Split-Path -Path $path -Parent
}
# truncate the current location if too long
$currentDirectory = $executionContext.SessionState.Path.CurrentLocation.Path
$maxPath = 24
if ($currentDirectory.Length -gt $maxPath) {
$currentDirectory = "`u{2026}" + $currentDirectory.SubString($currentDirectory.Length - $maxPath)
}
"$($lastExit)PS$($color.Reset) $lastCmdTime$currentDirectory$gitBranch$('>' * ($nestedPromptLevel + 1)) "
$lastId = $LastCmd.Id
Add-Content -Value "# $($LastCmd.StartExecutionTime)" -Path $PSLogPath
Add-Content -Value "$($LastCmd.CommandLine)" -Path $PSLogPath
Add-Content -Value '' -Path $PSLogPath
$howlongwasthat = $LastCmd.EndExecutionTime.Subtract($LastCmd.StartExecutionTime).TotalSeconds
}
gcm fsdf -erroraction silentlycontinue
$currentPath = (get-location).Path.replace($home, "~")
$idx = $currentPath.IndexOf("::")
if ($idx -gt -1) { $currentPath = $currentPath.Substring($idx + 2) }
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'System.Security.Principal.WindowsPrincipal' $windowsIdentity
$title = $currentPath
if ($windowTitle -ne $null)
{
$title = ($title + " » " + $windowTitle)
}
if ($psISE)
{
$color = "Black";
}
elseif ($windowsPrincipal.IsInRole("Administrators") -eq 1)
{
$color = "Yellow";
}
else
{
$color = "Green";
}
# Kerazy_POSH propmt
# Get Powershell version information
$MajorVersion = $PSVersionTable.PSVersion.Major
$MinorVersion = $PSVersionTable.PSVersion.Minor
# Detect if the Shell is 32- or 64-bit host
if ([System.IntPtr]::Size -eq 8) {
$ShellBits = 'x64 (64-bit)'
} elseif ([System.IntPtr]::Size -eq 4) {
$ShellBits = 'x86 (32-bit)'
}
# Set Window Title to display Powershell version info, Shell bits, username and computername
$host.UI.RawUI.WindowTitle = "PowerShell v$MajorVersion.$MinorVersion $ShellBits | $env:USERNAME@$env:USERDNSDOMAIN | $env:COMPUTERNAME | $env:LOGONSERVER"
# Set Prompt Line 1 - include Date, file path location
Write-Host(Get-Date -UFormat "%Y/%m/%d %H:%M:%S ($howlongwasthat) | ") -NoNewline -ForegroundColor DarkGreen
Write-Host(Get-Location) -ForegroundColor DarkGreen
# Set Prompt Line 2
# Check for Administrator elevation
if (Test-IsAdmin) {
Write-Host '# ADMIN # ' -NoNewline -ForegroundColor Cyan
} else {
Write-Host '# User # ' -NoNewline -ForegroundColor DarkCyan
}
if ($psISE) { $color = "Black"; }
elseif ($windowsPrincipal.IsInRole("Administrators") -eq 1)
{ $color = "Yellow";}
else{ $color = "Green";}
if ( $(Test-CommandExists 'Write-HgStatus') )
{
Write-HgStatus (Get-HgStatus)
Write-GitStatus (Get-GitStatus)
}
write-host (" [" + $nextId + "]") -NoNewLine -ForegroundColor $color
if ((get-location -stack).Count -gt 0) { write-host ("+" * ((get-location -stack).Count)) -NoNewLine -ForegroundColor Cyan }
if ( $(Test-CommandExists 'set-title') )
{ $title = $currentPath
if ($windowTitle -ne $null) { $title = ($title + " » " + $windowTitle) }
set-title $title
}
return " "
Write-Host '»' -NoNewLine -ForeGroundColor Green
' ' # need this space to avoid the default white PS>
# Style default PowerShell Console
$shell = $Host.UI.RawUI
$shell.WindowTitle= "PS"
$shell.BackgroundColor = "Black"
$shell.ForegroundColor = "White"
$colors = $host.PrivateData
$colors.verbosebackgroundcolor = "Magenta"
$colors.verboseforegroundcolor = "Green"
$colors.warningbackgroundcolor = "Red"
$colors.warningforegroundcolor = "white"
$colors.ErrorBackgroundColor = "DarkCyan"
$colors.ErrorForegroundColor = "Yellow"
# Load custom theme for Windows Terminal
#Set-Theme LazyAdmin
Write-Host "PSVersion: $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)"
Write-Host "PSEdition: $($PSVersionTable.PSEdition)"
Write-Host "Profile: $PSCommandPath"
Write-Host "admin: $isAdmin"
<#
# 设置 PowerShell 主题
* Author: 刘 鹏
* Email: littleNewton6@outlook.com
* Date: 2021, Aug. 21
# 引入 ps-read-line # useful history related actions
# example: https://github.com/PowerShell/PSReadLine/blob/master/PSReadLine/SamplePSReadLineProfile.ps1
#>
if (Test-ModuleExists 'PSReadLine')
{
# 引入 ps-read-line
if(!(TryImport-Module PSReadLine)) #null if fail to load
{
#------------------------------- Set Hot-keys BEGIN -------------------------------
$PSReadLineOptions = @{
HistorySavePath = $global:historyPath
# 设置预测文本来源为历史记录
PredictionSource = "HistoryAndPlugin"
# 每次回溯输入历史,光标定位于输入内容末尾
HistorySearchCursorMovesToEnd = $true
}
Set-PSReadLineOption @PSReadLineOptions
echo ($host.Name -eq 'ConsoleHost')
# Set-PSReadLineOption -EditMode Emac
# 每次回溯输入历史,光标定位于输入内容末尾
# 设置 Tab 为菜单补全和 Intellisense
# 设置 Ctrl+d 为退出 PowerShell
# 设置 Ctrl+z 为撤销
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadlineKeyHandler -Chord 'Shift+Tab' -Function Complete
# 设置 Ctrl+d 为退出 PowerShell
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit
# 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo
# 设置向上键为后向搜索历史记录 # Autocompletion for arrow keys @ https://dev.to/ofhouse/add-a-bash-like-autocomplete-to-your-powershell-4257
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
# 设置向下键为前向搜索历史纪录
if ( $null -ne $(Get-Module PSFzf) ) {
#Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
#$FZF_COMPLETION_TRIGGER='...'
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
}
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
#------------------------------- Set Hot-keys END -------------------------------
if ( $(Get-Module PSReadline).Version -ge 2.2 ) {
# 设置预测文本来源为历史记录
Set-PSReadLineOption -predictionsource history -ea SilentlyContinue
}
if ( $(Test-CommandExists 'Set-PSReadLineOption') )
{
#------------------------------- Styling begin --------------------------------------
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
}
echo "historyPath: $global:historyPath"
}
else
{
Write-Verbose "psReadLineNotimported"
}
}
else
{
Write-Verbose "psReadLineNotpresent"
}
#https://www.sapien.com/blog/2014/10/21/a-better-tostring-method-for-hash-tables/
#better hashtable ToString method
Update-TypeData -TypeName "System.Collections.HashTable" `
-MemberType ScriptMethod `
-MemberName "ToString" -Value { $hashstr = "@{"; $keys = $this.keys; foreach ($key in $keys) { $v = $this[$key];
if ($key -match "\s") { $hashstr += "`"$key`"" + "=" + "`"$v`"" + ";" }
else { $hashstr += $key + "=" + "`"$v`"" + ";" } }; $hashstr += "}";
return $hashstr }
#ps setHistorySavePath
if (-not $env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME = Join-Path -Path "$HOME" -ChildPath ".config" }; $XDG_CONFIG_HOME = $env:XDG_CONFIG_HOME
if (-not $env:XDG_DATA_HOME) { $env:XDG_DATA_HOME = Join-Path -Path "$HOME" -ChildPath ".local/share" }; $XDG_DATA_HOME = $env:XDG_DATA_HOME
if (-not $env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME = Join-Path -Path "$HOME" -ChildPath ".cache" }; $XDG_CACHE_HOME = $env:XDG_CACHE_HOME
if (-not $env:DESKTOP_DIR) { $env:DESKTOP_DIR = Join-Path -Path "$HOME" -ChildPath "desktop" }; $DESKTOP_DIR = $env:DESKTOP_DIR
if (-not $env:NOTES_DIR) { $env:NOTES_DIR = Join-Path -Path "$HOME" -ChildPath "notes" }; $NOTES_DIR = $env:NOTES_DIR
if (-not $env:CHEATS_DIR) { $env:CHEATS_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "cheatsheets" }; $CHEATS_DIR = $env:CHEATS_DIR
if (-not $env:TODO_DIR) { $env:TODO_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "_ToDo" }; $TODO_DIR = $env:TODO_DIR
if (-not $env:DEVEL_DIR) { $env:DEVEL_DIR = Join-Path -Path "$HOME" -ChildPath "devel" }; $DEVEL_DIR = $env:DEVEL_DIR
if (-not $env:PORTS_DIR) { $env:PORTS_DIR = Join-Path -Path "$HOME" -ChildPath "ports" }; $PORTS_DIR = $env:PORTS_DIR
# Load scripts from the following locations
$EnvPath = join-path -Path $home -ChildPath 'Documents\WindowsPowerShell\snipps\snipps$'
$env:Path += ";$EnvPath"
$historyPath = "$home\appdata\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
set-PSReadlineOption -HistorySavePath $historyPath
echo "historyPath: $historyPath"
#$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
# vscode Portable Path
$vscodepath = 'D:\portapps\6, Text,programming, x Editing\PortableApps\vscode-portable\vscode-portable.exe'
[Environment]::SetEnvironmentVariable("code", $vscodepath)
#sqlite dll
$workpath = "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll" ;
if ( $(Test-CommandExists 'everything') )
{
$alternative = try{everything 'wfn:System.Data.SQLite.DLL'} catch{$null}[0] ;
$pq = if(Test-Path $workpath){$workpath} else {$alternative} ?? 'unable to set path' ;
if( Test-Path $pq )
{
# $pq = try{Add-Type -Path $pq}catch{'unable to set path'}
echo $pq
}
}
### local variables
$whatPulseDbQuery = "select rightstr(path,instr(reverse(path),'/')-1) exe,path from (select max(path) path,max(cast(replace(version,'.','') as integer)) version from applications group by case when online_app_id = 0 then name else online_app_id end)"
$whatPulseDbPath = (Everything 'whatpulse.db')[0];
[Environment]::SetEnvironmentVariable("WHATPULSE_DB", $whatPulseDbPath)
if (-not $env:WHATPULSE_DB) { $env:WHATPULSE_DB = $whatPulseDbPath }; $WHATPULSE_DB = $env:WHATPULSE_DB
[Environment]::SetEnvironmentVariable("WHATPULSE_QUERY", $whatPulseDbQuery)
if (-not $env:WHATPULSE_QUERY) { $env:WHATPULSE_QUERY = $whatPulseDbQuery }; $WHATPULSE_QUERY = $env:WHATPULSE_QUERY
$datagripPath = '$home\appdata\Roaming\JetBrains\DataGrip2021.1'
[Environment]::SetEnvironmentVariable("datagripPath", $datagripPath)
$bComparePath = 'D:\PortableApps\2. fileOrganization\PortableApps\Beyond Compare 4'
[Environment]::SetEnvironmentVariable("bComparePath", $bComparePath)
echo "paths set"
#ps setHistorySavePath
if (-not $env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME = Join-Path -Path "$HOME" -ChildPath ".config" }; $XDG_CONFIG_HOME = $env:XDG_CONFIG_HOME
if (-not $env:XDG_DATA_HOME) { $env:XDG_DATA_HOME = Join-Path -Path "$HOME" -ChildPath ".local/share" }; $XDG_DATA_HOME = $env:XDG_DATA_HOME
if (-not $env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME = Join-Path -Path "$HOME" -ChildPath ".cache" }; $XDG_CACHE_HOME = $env:XDG_CACHE_HOME
if (-not $env:DESKTOP_DIR) { $env:DESKTOP_DIR = Join-Path -Path "$HOME" -ChildPath "desktop" }; $DESKTOP_DIR = $env:DESKTOP_DIR
if (-not $env:NOTES_DIR) { $env:NOTES_DIR = Join-Path -Path "$HOME" -ChildPath "notes" }; $NOTES_DIR = $env:NOTES_DIR
if (-not $env:CHEATS_DIR) { $env:CHEATS_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "cheatsheets" }; $CHEATS_DIR = $env:CHEATS_DIR
if (-not $env:TODO_DIR) { $env:TODO_DIR = Join-Path -Path "$env:NOTES_DIR" -ChildPath "_ToDo" }; $TODO_DIR = $env:TODO_DIR
if (-not $env:DEVEL_DIR) { $env:DEVEL_DIR = Join-Path -Path "$HOME" -ChildPath "devel" }; $DEVEL_DIR = $env:DEVEL_DIR
if (-not $env:PORTS_DIR) { $env:PORTS_DIR = Join-Path -Path "$HOME" -ChildPath "ports" }; $PORTS_DIR = $env:PORTS_DIR
# Load scripts from the following locations
$EnvPath = join-path -Path $home -ChildPath 'Documents\WindowsPowerShell\snipps\snipps$'
$env:Path += ";$EnvPath"
$historyPath = "$home\appdata\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
set-PSReadlineOption -HistorySavePath $historyPath
echo "historyPath: $historyPath"
#$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
# vscode Portable Path
$vscodepath = 'D:\portapps\6, Text,programming, x Editing\PortableApps\vscode-portable\vscode-portable.exe'
[Environment]::SetEnvironmentVariable("code", $vscodepath)
#sqlite dll
$workpath = "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll" ;
if ( $(Test-CommandExists 'everything') ) {$alternative = (everything 'wfn:System.Data.SQLite.DLL')[0] ;}
$p = if(Test-Path $workpath){$workpath} else {$alternative} ;
$p = $p ?? 'unable to set path'
if( Test-Path $p )
{
Add-Type -Path $p
echo $p
}
### local variables
$whatPulseDbQuery = "select rightstr(path,instr(reverse(path),'/')-1) exe,path from (select max(path) path,max(cast(replace(version,'.','') as integer)) version from applications group by case when online_app_id = 0 then name else online_app_id end)"
if ( $(Test-CommandExists 'everything') ) {$whatPulseDbPath = (Everything 'whatpulse.db')[0]; }
[Environment]::SetEnvironmentVariable("WHATPULSE_DB", $whatPulseDbPath)
if (-not $env:WHATPULSE_DB) { $env:WHATPULSE_DB = $whatPulseDbPath }; $WHATPULSE_DB = $env:WHATPULSE_DB
[Environment]::SetEnvironmentVariable("WHATPULSE_QUERY", $whatPulseDbQuery)
if (-not $env:WHATPULSE_QUERY) { $env:WHATPULSE_QUERY = $whatPulseDbQuery }; $WHATPULSE_QUERY = $env:WHATPULSE_QUERY
$datagripPath = '$home\appdata\Roaming\JetBrains\DataGrip2021.1'
[Environment]::SetEnvironmentVariable("datagripPath", $datagripPath)
$bComparePath = 'D:\PortableApps\2. fileOrganization\PortableApps\Beyond Compare 4'
[Environment]::SetEnvironmentVariable("bComparePath", $bComparePath)
echo "paths set"
$isAdmin = ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544"))
if ( ( $null -eq $PSVersionTable.PSEdition) -or ($PSVersionTable.PSEdition -eq "Desktop") ) { $PSVersionTable.PSEdition = "Desktop" ;$IsWindows = $true }
function NewSqliteConnection {
param(
[Parameter(Mandatory=$true)]
[string]$source
,[Parameter(Mandatory=$true)]
[string]$query
)
$con = New-Object -TypeName System.Data.SQLite.SQLiteConnection
;$safePath = $source.trim()
$con.ConnectionString = "Data Source=$safepath"
;
$con.Open() ;
$sql = $con.CreateCommand() ;
$sql.CommandText = "$QUERY" ;
$adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $sql ;
$data = New-Object System.Data.DataTable ;
$adapter.fill($data) ;
$adapter
}
# http://get-powershell.com/post/2008/06/25/Stuffing-the-output-of-the-last-command-into-an-automatic-variable.aspx
* FileName: Microsoft.PowerShell_profile.ps1
* Author: perXautomatik
* Email: christoffer.broback@gmail.com
* Date: 08/03/2022
* Copyright: No copyright. You can use this code for anything with no warranty.
#>
#loadMessage
echo "Microsoft.PowerShell_profile.ps1"
# Increase history
$MaximumHistoryCount = 10000
function Out-Default {
if ($input.GetType().ToString() -ne 'System.Management.Automation.ErrorRecord') {
try {
$input | Tee-Object -Variable global:lastobject | Microsoft.PowerShell.Core\Out-Default
} catch {
$input | Microsoft.PowerShell.Core\Out-Default
}
} else {
$input | Microsoft.PowerShell.Core\Out-Default
}
}
#src: https://stackoverflow.com/a/34098997/7595318
function Test-IsInteractive {
# Test each Arg for match of abbreviated '-NonInteractive' command.
$NonInteractiveFlag = [Environment]::GetCommandLineArgs() | Where-Object{ $_ -like '-NonInteractive' }
if ( (-not [Environment]::UserInteractive) -or ( $NonInteractiveFlag -ne $null ) ) {
return $false
}
return $true
}
#if ( Test-IsInteractive ) { (preferably use -noLogo) } # Clear-Host # remove advertisements
function Download-Latest-Profile {
New-Item $( Split-Path $($PROFILE.CurrentUserCurrentHost) ) -ItemType Directory -ea 0
if ( $(Get-Content "$($PROFILE.CurrentUserCurrentHost)" | Select-String "62a71500a0f044477698da71634ab87b" | Out-String) -eq "" ) {
Move-Item -Path "$($PROFILE.CurrentUserCurrentHost)" -Destination "$($PROFILE.CurrentUserCurrentHost).bak"
}
Invoke-WebRequest -Uri "https://gist.githubusercontent.com/apfelchips/62a71500a0f044477698da71634ab87b/raw/Profile.ps1" -OutFile "$($PROFILE.CurrentUserCurrentHost)"
Reload-Profile
}
# Produce UTF-8 by default
if ( $PSVersionTable.PSVersion.Major -lt 7 ) {
# https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8' # Fix Encoding for PS 5.1 https://stackoverflow.com/a/40098904
}
#------------------------------- Set Paths -------------------------------
$paths = join-path -Path (split-path $profile -Parent) -ChildPath 'setPaths.ps1'
Import-Module $paths
#------------------------------- Set Paths end -------------------------------
#------------------------------- Import Modules BEGIN -------------------------------
$profileFolder = (split-path $profile -Parent)
$pos = join-path -Path $profileFolder -ChildPath 'importModules.ps1'
Import-Module $pos
#------------------------------- Import Modules END -------------------------------
#------------------------------- overloading begin
#https://www.sapien.com/blog/2014/10/21/a-better-tostring-method-for-hash-tables/
#better hashtable ToString method
Update-TypeData -TypeName "System.Collections.HashTable" `
-MemberType ScriptMethod `
-MemberName "ToString" -Value { $hashstr = "@{"; $keys = $this.keys; foreach ($key in $keys) { $v = $this[$key];
if ($key -match "\s") { $hashstr += "`"$key`"" + "=" + "`"$v`"" + ";" }
else { $hashstr += $key + "=" + "`"$v`"" + ";" } }; $hashstr += "}";
return $hashstr }
#------------------------------- overloading end
#------------------------------- SystemMigration -------------------------------
#choco check if installed
#path to list of aps to install
#choco ask to install if not present
#list of portable apps,download source
#path
#download and extract if not present, ask to confirm
#path to portable apps
#path to standard download location
#git Repos paths and origions,
#git systemwide profile folder
#git global path
#everything data folder
#autohotkey script to run on startup
#startup programs
#reg to add if not present
#------------------------------- SystemMigration end -------------------------------
#------------------------------- Styling begin --------------------------------------
#change selection to neongreen
#https://stackoverflow.com/questions/44758698/change-powershell-psreadline-menucomplete-functions-colors
$colors = @{
"Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m"
}
Set-PSReadLineOption -Colors $colors
# Style default PowerShell Console
$shell = $Host.UI.RawUI
$shell.WindowTitle= "PS"
$shell.BackgroundColor = "Black"
$shell.ForegroundColor = "White"
# Load custom theme for Windows Terminal
#Set-Theme LazyAdmin
#------------------------------- SystemMigration -------------------------------
#choco check if installed
#path to list of aps to install
#choco ask to install if not present
#list of portable apps,download source
#path
#download and extract if not present, ask to confirm
#path to portable apps
#path to standard download location
#git Repos paths and origions,
#git systemwide profile folder
#git global path
#everything data folder
#autohotkey script to run on startup
#startup programs
#reg to add if not present
#------------------------------- SystemMigration end -------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment