PowerShell: Alternate script behavior when dot sourced vs run directly

I use dot sourcing in my PowerShell scripts to reuse functions* and sometimes I want different behavior if they are included (dot sourced) or run directly. This concept is used in Python to provide an easy way to run tests against the code when run directly but not when it is imported.

You are not restricted to running tests using this approach, but I think that automated testing is useful so that is the example I provide below.

*I know that I can use PowerShell modules in versions >= 2. Sometimes I still use v1 or just don’t want to use modules.

# A silly example function to illustrate the point
Function StartsWithA_fail {
	param (
	# This isn't actually checking that the starting character is an a
	$testString -match "[aA].*"
# An equivalent of Python's if __name__ == "__main__"
# if not dot sourced then we do sometheing else (tests in this case)
if ( !($MyInvocation.Line -match "^\s*\.\s")) {
	Write-Host "Running tests on StartsWithA_fail."
	# Run through some tests of our functions
	$results = @()
	$results += (StartsWithA_fail "alpha") -eq $true
	$results += (StartsWithA_fail "Alpha") -eq $true
	$results += (StartsWithA_fail " alpha") -eq $false
	$results += (StartsWithA_fail "beta") -eq $false
	$failed = @($results | Where-Object {$_ -eq $false})
	"{0} tests run" -f $results.length
	"{0} tests passed" -f ($results.Length - $failed.Length)
	"{0} tests failed" -f $failed.Length

Leave a Comment

Your email address will not be published.