Author : MD TAREQ HASSAN | Updated : 2022/08/27

Get script name

The script in which command is being executed

#
# returns same (full path) from script and from whithin function
# StackOverflow answer: <https://stackoverflow.com/a/43643346/4802664>
#
$scriptName = Split-Path -Path $PSCommandPath -Leaf 

#
# This is usefull when you want to call a script with "current script name" as parameter
# (you cannot call utility function from other script, so use this command to get current script name, if script name changes it will still work)
# . ./init.ps1 -ScriptNameWithExtension (Split-Path -Path $PSCommandPath -Leaf)
#

Name of the callter script when function is being called

function Get-CurrentScriptName {

    param(
        [bool]$WithExtension = $true
    )

    #
    # Init
    #
    $scriptName = ''

    #
    # Followings give caller script name with extension:
    # 1. $MyInvocation.ScriptName -> When used in a function in the called script -> 
    # 2. $MyInvocation.MyCommand.Name -> When used in the caller script (the script itself)
    # 
    # Note: $MyInvocation.MyCommand.Name -> give function name when used inside function
    #
    $scriptNameWithFullPath = $MyInvocation.ScriptName
    if (-not [string]::IsNullOrWhiteSpace($scriptNameWithFullPath)) {
        $scriptName = Split-Path $scriptNameWithFullPath -Leaf
    }
    else {
        $scriptName = $MyInvocation.MyCommand.Name
    }

    #
    # With or without extension
    #
    if (-not $WithExtension) {
        #Write-Host "Removing script extension"
        $scriptName = $scriptName.Split(".")[0]
    }

    #
    # Return script name as string
    #
    return "$scriptName"
}

Get current script directory

PowerShell 7+: $PSScriptRoot

For all versions:

function Get-CurrentScriptDirectory {

    $ScriptPath = ""
    
    if ($psISE) { # If using ISE
        $ScriptPath = Split-Path -Parent $psISE.CurrentFile.FullPath
    } elseif($PSVersionTable.PSVersion.Major -gt 3) { # If Using PowerShell 3 or greater
        $ScriptPath = $PSScriptRoot
    } else { # If using PowerShell 2 or lower
        $ScriptPath = split-path -parent $MyInvocation.MyCommand.Path
    }

    Write-Output $ScriptPath
}

StackOverflow question: https://stackoverflow.com/questions/5466329/whats-the-best-way-to-determine-the-location-of-the-current-powershell-script

Load scripts

Load a single script

. [path]/[script_name].ps1 # . ./xyz.ps1

Load all scripts in a folder

$utilityScriptsFolder = (Join-Path $PSScriptRoot "utilities") # there multiple scripts in 'utilities' folder

(Get-ChildItem -Path $utilityScriptsFolder -Filter *.ps1 -Recurse) | ForEach-Object {
    . $_.FullName
}