PowerShell

Profile Template

A template for PowerShell profile, mainly a reminder for some useful efficiencies you can do.

#Example Param Block
<#
Param(
	[Type]$lol = "rofl"				# Default value that persists even if they don't hand it a value
	[Parameter(Mandatory=$true)][Type]$lol		# Makes sure that they provide input for this parameter
	[Parameter(Position=0)][Type]$lol		# Position in the parameter list when function called
	[Parameter(ValueFromPipeline=$true)][Type]$lol	# Whether or not the parameter will accept value from pipeline
	[Parameter(HelpMessage="Help!")][Type]$lol	# The parameter's help message if the specific parameter is called using get-help your-function -Parameter lol
	[ValidateSet("1","2","3")][Type]$lol		# Restrict input to a predefined set of values
	[ValidateNotNullOrEmpty()][Type]$lol		# Ensures that the parameter isn't null or empty
	[ValidateScript({$_ -gt 0})][Type]$lol		# Custom validation using a script block
)
#>

# =================================== QUICK JUMPS

function CDroot(){ Set-location "C:\" }
function CDtemp(){ Set-location "C:\Temp\" }
function CDdesktop(){ Set-location "$ENV:USERPROFILE\Desktop" }
function CDlocalscripts(){ Set-location "$ENV:USERPROFILE\Documents\Local Scripts\" }
function CDgithub(){ Set-location "$ENV:USERPROFILE\Documents\GitHub" }
function CDonedrive(){ Set-location $ENV:OneDrive }

# =================================== PROFILE HELPERS
# Chocolatey profile
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
  Import-Module "$ChocolateyProfile"
}


# =================================== CUSTOM FUNCTIONS

# Flushes user defined variables.
function flush-variables(){
	$variables = get-variable
	foreach($variable in $variables){
		write-host "$($variable.name) " -ForegroundColor Yellow -NoNewline
		if(!($global:defaultVariables.name.contains($variable.name))){
			if(!($variable.name -eq "defaultVariables")){
				try{
					Remove-variable -name $variable.name -Scope Script -ErrorAction Stop
				}catch{
					if($_.FullyQualifiedErrorID.contains("VariableNotRemovableRare")){continue}
					if($_.FullyQualifiedErrorID.contains("VariableNotRemovableSystem")){continue}
					throw $_
				}
			}
		}
	}
}

# Gets all your current variables. Usually used at the start of your session.
function get-defaultVars(){ $global:defaultVariables = Get-Variable }


# =================================== PROFILE SELECTOR
$choicesProfile = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choicesProfile.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Local'))
$choicesProfile.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&External'))
$choicesProfile.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Both'))
$choicesProfile.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&None'))


$loadTools = $Host.UI.PromptForChoice("", "Profile Select?", $choicesProfile, 1)
add-type -Assembly System.Web.Extensions
write-host ""
switch($loadTools){
    0 { Clear-host
        $host.ui.RawUI.WindowTitle = "Personal Only"
        Set-PSReadlineKeyHandler -Key Tab -Function Complete
        Import-Module "<Your Personal Module.psm1>" }

    1 { Clear-host
        $host.ui.RawUI.WindowTitle = "External Tools Name"
        Set-PSReadlineKeyHandler -Key Tab -Function Complete 
        . "Location of External Profile" }

    2 { Clear-host
        $host.ui.RawUI.WindowTitle = "Both Profiles Loaded"
        Set-PSReadlineKeyHandler -Key Tab -Function Complete
        Import-Module "<Personal psm1 path>"
        . "<External Profile path>" }
    3 { return }
}Code language: PowerShell (powershell)
Click to open template

Param block cheat sheet

param(
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true)]

   etc to do
)Code language: PowerShell (powershell)
Click to open template

Useful Functions

Show-HostColours: Simple function to see your shells colour theme easily.

function Show-HostColours(){
    $Colours = @('Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'darkRed', 'darkGreen', 'darkYellow', 'darkBlue', 'darkMagenta', 'darkCyan')
    write-host "`n"
    foreach($colour in $colours){
        write-host $colour -ForegroundColor $colour -NoNewline
        if($colour.Length -lt 7 -or $colour.length -eq 7){
            write-host "`t`t" -NoNewline
        }else{
            write-host "`t" -NoNewline
        }
        write-host "    " -BackgroundColor $colour
    }    
}Code language: PowerShell (powershell)
Click to view function

Show-CustomCommands: Filter function allowing you to search non-standard functions using a tag in your function names.

Function Show-CustomCommands([String]$Filter,[Switch]$listAll){

    $SearchTag = "<INSERT YOUR LIBRARY FUNCTION TAG>"
    $fileObjects = Get-ChildItem "<INSERT YOUR LIBRARY PATH>" -Recurse
    $psFunctions = Get-ChildItem function:\
    $Customcommands = @()
    $CustomFiles = @()
    $i = 1
    foreach($item in $fileObjects){
        if($item.name.contains(".psm1") -or $item.name.contains(".ps1")){
            $Entry = [PSCustomObject]@{
                ID      = $i
                Name    = $item.name
            }
            $CustomFiles += $Entry
            $i++
        }
    }

    if($listAll){
        foreach($file in $CustomFiles){
            $functionsExist = $false
            Write-Host "`n$($file.Name)" -ForegroundColor Yellow

            foreach($function in $psFunctions){
                if($function.name.contains($SearchTag)){
                    if($filter -eq ""){
                        if($file.Name.contains($function.Source)){
                            Write-Host "`t$($function.name)"
                            $functionsExist = $true
                        }
                    }else{
                        if($function.name -like "*$filter*"){
                            if($file.name.contains($function.Source)){
                                Write-Host "`t$($function.name)"
                                $functionsExist = $true
                            }
                        }
                    }
                }
            }
            if(!$functionsExist){
                write-host "..."
            }
        }
    }else{
        if($filter -eq ""){
            $functionsExist = $false
            $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
            foreach($file in $CustomFiles){
                Write-Host "[$($file.ID)] $($file.name)"
                $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList "$($file.ID)"))
            }
            Write-host "`nPlease select a file to view custom functions from:`n" -ForegroundColor Yellow
            $userAction = $Host.UI.PromptForChoice("","", $choices, 0)
            write-host "$($CustomFiles[$userAction].name)" -ForegroundColor Yellow
            Foreach($function in $psFunctions){
                if($CustomFiles[$userAction].Name.contains($function.Source) -and $function.source -ne ""){
                    Write-Host "`t$($function.name)"
                    $functionsExist = $true
                }
            }

            if(!$functionsExist){
                write-host "No Custom Functions"
            }
        }else{
            foreach($function in $psfunctions){
                if($function.name.contains($SearchTag)){
                    if($function.name -like "*$filter*"){
                        $Entry = [PSCustomObject]@{
                            'Function'  = $function.Name
                            Source      = $function.Source
                        }
                        $Customcommands += $Entry
                    }
                }
            }
            $Customcommands = $Customcommands | Sort-Object Function
            return $Customcommands
        }
    }
}Code language: PowerShell (powershell)
Click to view function