Skip to content

Instantly share code, notes, and snippets.

@techthoughts2
Last active February 25, 2022 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techthoughts2/2b4d8e590a7fa41f32a76013df664020 to your computer and use it in GitHub Desktop.
Save techthoughts2/2b4d8e590a7fa41f32a76013df664020 to your computer and use it in GitHub Desktop.
#region functions
function Convert-PSToVSCodeSnippet {
<#
.SYNOPSIS
Converts PowerShell Code to VSCode snippet format
.DESCRIPTION
Leverages the ConvertTo-VSCodeSnippet script available on PSGallery to convert PowerShell code to properly formatted VSCode snippet JSON
.EXAMPLE
Convert-PSToVSCodeSnippet -Name 'MySnippet' -Body $body -Prefix 'MyPrefix' -Description 'MyDescription'
.PARAMETER Name
The name of the snippet.
.PARAMETER Body
The body of the snippet. This is the actual content.
.PARAMETER Description
The snippet description.
.NOTES
! You must have previously installed the ConvertTo-VSCodeSnippet in $scriptPath
Install-Script ConvertTo-VSCodeSnippet
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]
$Body,
[Parameter()]
[string]
$Prefix = $Name,
[Parameter()]
[string]
$Description
)
$convertScriptInfo = Get-InstalledScript -Name ConvertTo-VSCodeSnippet
if ($null -eq $convertScriptInfo) {
throw 'ConvertTo-VSCodeSnippet src not found. Please install it from PSGallery'
}
$installedLocation = $convertScriptInfo.InstalledLocation
$scriptPath = '{0}\\ConvertTo-VSCodeSnippet.ps1' -f $installedLocation
.$scriptPath -Name $Name -Body $Body -Scope 'powershell' -Prefix $Name -Description $Description
} #Convert-PSToVSCodeSnippet
function Get-Weather {
<#
.SYNOPSIS
Returns weather report information.
.DESCRIPTION
Console-oriented weather forecast that returns weather information for specified parameters.
.EXAMPLE
Get-Weather
Returns full weather information based on the location of your IP with all defaults.
.EXAMPLE
Get-Weather -Short
Returns basic weather information based on the location of your IP.
.EXAMPLE
Get-Weather -City 'London' -Units Metric -Language 'en'
Returns full weather information for the city of Londa in Metric units with UK language.
.EXAMPLE
Get-Weather -City 'San Antonio' -Units USCS -Short
Returns basic weather information for the city of San Antonio in United State customary units.
.PARAMETER City
The city you would like to get the weather from. If not specified the city of your IP is used.
.PARAMETER Units
Units to display Metric vs United States cusomtary units
.PARAMETER Language
Language to display results in
.PARAMETER Short
Will return only basic weather information
.NOTES
https://github.com/chubin/wttr.in
https://wttr.in/:help
#>
[CmdletBinding()]
param (
[Parameter(
Position = 0,
Mandatory = $false
)]
[string]
$City,
[Parameter(Position = 1)]
[ValidateSet('Metric', 'USCS')]
[string]
$Units = 'USCS',
[Parameter(Position = 2)]
[ValidateSet('ar', 'af', 'be', 'ca', 'da', 'de', 'el', 'en', 'et', 'fr', 'fa', 'hu', 'ia', 'id', 'it', 'nb', 'nl', 'pl', 'pt-br', 'ro', 'ru', 'tr', 'th', 'uk', 'vi', 'zh-cn', 'zh-tw')]
[string]
$Language = 'en',
[Parameter(Position = 3)]
[switch]
$Short
)
$uriString = 'https://wttr.in/'
if ($City) {
$uriString += "$City"
}
switch ($Units) {
'Metric' {
$uriString += "?m"
}
'USCS' {
$uriString += "?u"
}
}
if ($Short) {
$uriString += "&format=4"
}
$uriString += "&lang=$Language"
Write-Verbose "URI: $uriString"
$invokeSplat = @{
Uri = $uriString
ErrorAction = 'Stop'
}
try {
Invoke-RestMethod @invokeSplat
}
catch {
Write-Error $_
}
} #Get-Weather
function Set-MonitorInputSource {
<#
.SYNOPSIS
Helper function to set the monitor input.
.DESCRIPTION
Uses ControlMyMonitor.exe to adjust VPCCode 60 for your monitor input.
.EXAMPLE
Set-MonitorInputSource -InputSource HDMI
Switched to HDMI input
.EXAMPLE
Set-MonitorInputSource -InputSource DisplayPort
Switches to DisplayPort input
.PARAMETER InputSource
HDMI or DisplayPort
.LINK
https://www.nirsoft.net/utils/control_my_monitor.html
.LINK
https://johnstonsoftwaresolutions.com/2019/02/09/tip-switch-monitor-inputs-with-command-line/
.NOTES
ControlMyMonitor.exe does not support dynamically retrieving a lot of info.
So, you will need to open ControlMyMonitor.exe and determine the names of your monitors.
They should look something like: \\.\DISPLAY1\Monitor0
Plug your monitor names into the $monitors array below.
You may also have to fiddle with the settings of your input numbers.
These will different between make/model and the connections you are using.
#>
[CmdletBinding()]
param(
[ValidateSet('HDMI', 'DisplayPort')]
[string]$InputSource
)
$ExePath = "$env:USERPROFILE\AppData\Local\ControlMyMonitor.exe"
if (Test-Path $ExePath) {
$InputSourceHash = @{
'DisplayPort' = 15 #differs depending on monitor brand/model and connection
'HDMI' = 17 #differs depending on monitor brand/model and connection
}
$monitors = @(
# you may have 1 or more monitors listed here
'\\.\DISPLAY1\Monitor0',
'\\.\DISPLAY2\Monitor0',
'\\.\DISPLAY3\Monitor0'
)
foreach ($monitor in $monitors) {
$argList = @(
'/SetValue'
$monitor
'60'
$InputSourceHash[$InputSource]
)
$argList
Start-Process -FilePath $ExePath -ArgumentList $argList -Wait
}
}
else {
Write-Warning "Unable to locate ControlMyMoniror.exe at: [$ExePath]"
}
} #Set-MonitorInputSource
function Get-MonitorVPCValue {
<#
.SYNOPSIS
Helper function to get VPC values from your monitor.
.DESCRIPTION
Uses ControlMyMonitor.exe to retrieve VPCCode values from your monitor.
.EXAMPLE
Get-MonitorVPCValue -VPCCode 60
Returns value for VPC Code 60 - which is monitor input
.EXAMPLE
Get-MonitorVPCValue -VPCCode 10
Returns value for VPC Code 10 - which is monitor brightness level
.PARAMETER VPCCode
VPC Code number
.LINK
https://www.nirsoft.net/utils/control_my_monitor.html
.LINK
https://johnstonsoftwaresolutions.com/2019/02/09/tip-switch-monitor-inputs-with-command-line/
.NOTES
Open ControlMyMonitor.exe to determine what VPC Codes you can query.
#>
[CmdletBinding()]
param(
[string]$VPCCode
)
$ExePath = "$env:USERPROFILE\AppData\Local\ControlMyMonitor.exe"
$argList = @(
'/GetValue'
'\\.\DISPLAY1\Monitor0'
$VPCCode
)
$p = Start-Process -FilePath $ExePath -ArgumentList $argList -Wait -PassThru
return $p.ExitCode
} #Get-MonitorVPCValue
function Show-Pics {
<#
.SYNOPSIS
Launches the default browser to display reddit pictures.
.DESCRIPTION
Long description
.EXAMPLE
C:\PS> Show-Pics -URL https://i.imgur.com/fcuRqwl.jpg
Launches default browser to provided link.
.EXAMPLE
C:\PS> $severalURLs | Show-Pics
Launches default browser tab for each provided link.
.PARAMETER URL
i.redd.it or imgur URL
.NOTES
Jake Morrison - @jakemorrison - https://www.techthoughts.info
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
HelpMessage = 'i.redd.it or imgur URL')]
[ValidatePattern('i.redd.it|imgur')]
[string]$URL
)
begin {
Write-Verbose "Starting Show-Pics function"
}
process {
try {
Start-Process $URL -ErrorAction Stop
Write-Verbose "Browser launch successful."
}
catch {
Write-Error $_
}
}
end {
Write-Verbose "All done."
}
} #Show-Pics
function Get-Reddit {
<#
.SYNOPSIS
PowerShell based interactive reddit browser
.DESCRIPTION
Uses PowerShell to establish a connection to reddit and pulls down a JSON payload for the specified subreddit. The number of threads (default 3) specified by the user is then evaluated and output to the console window. If the thread is picture-based the user has the option to display those images in their native browser.
.PARAMETER Subreddit
The name of the desired subreddit - Ex PowerShell or aww
.PARAMETER Threads
The number of threads that will be pulled down - the default is 3
.PARAMETER ShowPics
Determines if pics will be shown (if available)
.EXAMPLE
PS C:\> Get-Reddit -Subreddit PowerShell
Retrieves the top 3 threads of the PowerShell subreddit
.EXAMPLE
PS C:\> Get-Reddit -Subreddit aww -Threads 4
Retrieves the top 4 threads of the aww subreddit
.EXAMPLE
PS C:\> Get-Reddit -Subreddit PowerShell -ShowPics
Retrieves the top 3 threads of the aww subreddit and if pictures are available, displays them in the native browser
.NOTES
Jake Morrison - @jakemorrison - https://www.techthoughts.info
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $false,
Position = 1,
HelpMessage = 'The name of the desired subreddit')]
[string]$Subreddit,
[Parameter(Mandatory = $false,
ValueFromPipeline = $false,
Position = 2,
HelpMessage = 'The number of threads that will be pulled down')]
[ValidateRange(1, 25)]
[int]$Threads = 3,
[Parameter(Mandatory = $false,
ValueFromPipeline = $false,
Position = 3,
HelpMessage = 'Determines if pics will be shown (if available)')]
[switch]$ShowPics
)
Write-Verbose "Specified subreddit: $Subreddit"
Write-Verbose "Specified # of threads: $Threads"
$results = @()
Write-Verbose "Initiating Download"
$uri = "http://www.reddit.com/r/$Subreddit/.json"
Write-Verbose "URI: $uri"
try {
$invokeWebRequestSplat = @{
Uri = $uri
ErrorAction = 'Stop'
}
$rawReddit = Invoke-WebRequest @invokeWebRequestSplat
Write-Verbose "Download successful."
}
catch {
Write-Error $_
return $results
}
if ($rawReddit) {
Write-Verbose "Converting JSON..."
$redditInfo = $rawReddit | ConvertFrom-Json
Write-Verbose "Generating output..."
for ($i = 0; $i -lt $Threads; $i++) {
$childObject = $null #reset
$childObject = $redditInfo.data.children.data[$i]
$obj = [PSCustomObject]@{
Title = $childObject.title
URL = $childObject.url
# PermaLink = $childObject.permalink
Score = $childObject.score
# Ups = $childObject.ups
# Downs = $childObject.downs
Author = $childObject.author
Comments = $childObject.num_comments
}
$results += $obj
if ($obj.url -like "*i.redd.it*" -or $url -like "*imgur*" -and $ShowPics) {
Show-Pics -url $obj.url
}
}
} #if_rawReddit
else {
Write-Warning -Message 'No information was returned from reddit.'
} #else_rawReddit
return $results
} #Get-Reddit
function Clear-All {
<#
.SYNOPSIS
Clears all errors, variables, console, and sets locations back to C:\
.NOTES
System variables are not cleared - as they are gathered previously and left un-touched.
#>
$sysvariables = $sysvars
#clear all errors
$error.clear()
#clear all non-system variables
Get-Variable |
Where-Object {
$sysvariables -notcontains $_.Name `
-and $_.Name -ne "sysvariables" `
-and $_.Name -ne 'GitPromptSettings' `
-and $_.Name -ne 'PoshSettings' } |
ForEach-Object { Remove-Variable $_.name -Scope Global }
Clear-Host
Set-Location C:\
} #Clear-All
function Get-ChocoInstalls {
<#
.SYNOPSIS
Lists local chocolately installs
#>
choco list --localonly
} #Get-ChocoInstalls
function Open-Here {
<#
.SYNOPSIS
Opens explorer window to the current console path location
#>
explorer $pwd
} #Open-Here
function Get-Syntax {
<#
.SYNOPSIS
Get beautiful syntax for any cmdlet
#>
[CmdletBinding()]
param (
$Command,
[switch]
$PrettySyntax
)
$check = Get-Command -Name $Command
$params = @{
Name = if ($check.CommandType -eq 'Alias') {
Get-Command -Name $check.Definition
}
else {
$Command
}
Syntax = $true
}
$pretty = $true
if ($pretty -eq $true) {
(Get-Command @params) -replace '(\s(?=\[)|\s(?=-))', "`r`n "
}
else {
Get-Command @params
}
} #Get-Syntax
function Sort-Reverse {
<#
.SYNOPSIS
Quickly and easily reverses a list
#>
$rank = [int]::MaxValue
$input | Sort-Object { (--(Get-Variable rank -Scope 1).Value) }
} #Sort-Reverse
function Set-WorkingDirectory {
<#
.SYNOPSIS
Changes directory to main daily working directory
#>
Set-Location -Path "$env:USERPROFILE\desktop\project\0_CodeProject"
} #Set-WorkingDirectory
#endregion
#region variables
#Write-Host "Initializing the Shell..." -ForegroundColor DarkCyan -BackgroundColor White
#D:\Users\user\Documents\PowerShell\Modules\oh-my-posh\2.0.342\Themes
# D:\Users\user\Documents\PowerShell
# https://ohmyposh.dev/docs/configure/
# C:\Users\user\.jake.omp.json
# https://www.nerdfonts.com/
<#
curl -fLo "<FONT NAME> Nerd Font Complete.otf" \
https://github.com/ryanoasis/nerd-fonts/raw/master/patched-fonts/<FONT_PATH>/complete/<FONT_NAME>%20Nerd%20Font%20Complete.otf
https://github.com/ryanoasis/nerd-fonts/releases/download/v2.1.0/CascadiaCode.zip
https://github.com/adam7/delugia-code/releases
#>
$global:sysvars = Get-Variable | Select-Object -ExpandProperty Name
$global:sysvars += 'sysvars'
$greetings =
'Welcome back Jake',
'Glad to see you Jake!',
'Happy coding Jake!',
'Have a great day Jake!',
'Be one with the Snover!',
'May the PowerShell be with you!'
$env:AWS_DEFAULT_REGION = 'us-west-2'
$env:AWS_PROFILE = 'dev'
# $env:AWS_CONFIG_FILE = '~/.aws/config'
$env:AWS_CONFIG_FILE = $env:USERPROFILE + '/.aws/config'
#endregion
#region aliases
# set easy aliases for various functions
New-Alias -Name ca -value Clear-All
New-Alias -Name op -value Open-Here
New-Alias -Name syn -value Get-Syntax
New-Alias -Name sr -value Sort-Reverse
New-Alias -Name work -Value Set-WorkingDirectory
New-Alias -Name gw -Value Get-Weather
New-Alias -Name chocol -Value Get-ChocoInstalls
#endregion
#region modules
# load up any desired modules
if ($host.Name -eq 'ConsoleHost') {
$modulesToLoad = @(
'posh-git',
'oh-my-posh',
'Terminal-Icons'
'CredentialManager'
)
}
else {
$modulesToLoad = @(
'posh-git'
'Terminal-Icons'
'CredentialManager'
)
}
foreach ($module in $modulesToLoad) {
Write-Host -ForegroundColor Gray ("Jake, at your request I am loading up the $module module...")
try {
Import-Module $module -ErrorAction Stop
Write-Host "$module loaded." -ForegroundColor Magenta
}
catch {
Write-Host "Jake, $module has failed to load." -ForegroundColor DarkRed
}
}
#endregion
#region secure variables
# secure variables
$secureGMap = Get-StoredCredential -Target GoogleMap -Type Generic
$global:GoogleAPIKey = ConvertFrom-SecureString -SecureString $secureGMap.Password -AsPlainText
$secureBMap = Get-StoredCredential -Target BingMap -Type Generic
$global:BingAPIKey = ConvertFrom-SecureString -SecureString $secureBMap.Password -AsPlainText
$secureToken = Get-StoredCredential -Target token -Type Generic
$global:token = ConvertFrom-SecureString -SecureString $secureToken.Password -AsPlainText
$secureChannel = Get-StoredCredential -Target channel -Type Generic
$global:channel = ConvertFrom-SecureString -SecureString $secureChannel.Password -AsPlainText
#endregion
#region settings
$ProgressPreference = 'SilentlyContinue'
if ((Get-Module PSReadLine).Version -ge 2.2) {
# Set-PSReadlineOption -ContinuationPrompt ">>>"
# Set-PSReadLineOption -Colors @{Selection = "`e[92;7m" }
Set-PSReadLineOption -PredictionSource History
# Set-PSReadLineOption -Colors @{ InlinePrediction = "$([char]0x1b)[38;5;238m" }
# Set-PSReadLineOption -Colors @{ InlinePrediction = '#8A0303' }
Set-PSReadLineOption -Colors @{ InlinePrediction = '#2F7004' }
# Set-PSReadLineOption -Colors @{ InlinePrediction = "$([char]0x1b)[36;7;238m" }
}
#endregion
#region prompt
[version]$versionReq = '7.0.0.0'
if ($host.Name -eq 'ConsoleHost' -and $host.Version -gt $versionReq) {
if ((Get-Module oh-my-posh).Version -ge 3.133.1) {
# https://www.hanselman.com/blog/PatchingTheNewCascadiaCodeToIncludePowerlineGlyphsAndOtherNerdFontsForTheWindowsTerminal.aspx
# https://www.hanselman.com/blog/HowToMakeAPrettyPromptInWindowsTerminalWithPowerlineNerdFontsCascadiaCodeWSLAndOhmyposh.aspx
# Set-Theme Jake #v2
Set-PoshPrompt -Theme ~/.jake.omp.json #v3
}
}
elseif ($host.Name -eq 'Visual Studio Code Host') {
Write-Host 'Loading EditorServicesCommandSuite...' -ForegroundColor Gray
if (Get-Module -Name EditorServicesCommandSuite -ListAvailable) {
# Import-Module EditorServicesCommandSuite -ErrorAction SilentlyContinue #workaround
Import-Module EditorServicesCommandSuite
Import-EditorCommand -Module EditorServicesCommandSuite
}
function prompt {
$color = @{
Reset = "`e[0m"
Red = "`e[31;1m"
Green = "`e[32;1m"
Yellow = "`e[33;1m"
Grey = "`e[37;0m"
White = "`e[37;1m"
Invert = "`e[7m"
RedBackground = "`e[41m"
}
# 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) "
}
# truncate the current location if too long
$currentDirectory = $executionContext.SessionState.Path.CurrentLocation.Path
$consoleWidth = [Console]::WindowWidth
$maxPath = [int]($consoleWidth / 4.5)
if ($currentDirectory.Length -gt $maxPath) {
$currentDirectory = "`u{2026}" + $currentDirectory.SubString($currentDirectory.Length - $maxPath)
}
$global:promptDateTime = [datetime]::Now
$Global:promptDate = $global:promptDateTime.ToString("MM-dd-yy")
$Global:promptTime = $global:promptDateTime.ToString("HH:mm")
# $global:promptPath = $pwd.ToString().split('\')[-2..-1] -join '\'
$global:promptPath = $currentDirectory
# "${lastCmdTime}${currentDirectory}${gitBranch}${devBuild}`n${lastExit}PS$($color.Reset)$('>' * ($nestedPromptLevel + 1)) "
Write-Host ${lastCmdTime}
Write-Host -Object ("[{0} {1}]" -f $global:promptDate, $global:PromptTime) -ForegroundColor Green -NoNewline
Write-Host (" {0}>" -f $global:promptPath) -NoNewline
Write-VcsStatus
return " "
}
}
else {
# Custom prompt function
function global:prompt {
$global:promptDateTime = [datetime]::Now
$Global:promptDate = $global:promptDateTime.ToString("MM-dd-yy")
$Global:promptTime = $global:promptDateTime.ToString("HH:mm")
# truncate the current location if too long
$currentDirectory = $executionContext.SessionState.Path.CurrentLocation.Path
$consoleWidth = [Console]::WindowWidth
$maxPath = [int]($consoleWidth / 4.5)
if ($currentDirectory.Length -gt $maxPath) {
$currentDirectory = ".." + $currentDirectory.SubString($currentDirectory.Length - $maxPath)
}
# $global:promptPath = $pwd.ToString().split('\')[-2..-1] -join '\'
$global:promptPath = $currentDirectory
# "${lastCmdTime}${currentDirectory}${gitBranch}${devBuild}`n${lastExit}PS$($color.Reset)$('>' * ($nestedPromptLevel + 1)) "
Write-Host -Object ("[{0} {1}]" -f $global:promptDate, $global:PromptTime) -ForegroundColor Green -NoNewline
(" {0}> " -f $global:promptPath)
Write-VcsStatus
return " "
}
}
#endregion
#_________________________________________________________________________________________
# Set-Location C:\
#_________________________________________________________________________________________
Write-Host "Initilization complete." ($greetings | Get-Random) -ForegroundColor Cyan -BackgroundColor Black
#_________________________________________________________________________________________
Write-Host -ForegroundColor Cyan ($greetings | Get-Random)
Write-Host $host.Name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment