Get the currently-running PowerShell script’s name

I’ve previously needed to get the name of the PowerShell script that’s running from within the script itself. I came across this solution, but today ran into a scenario where that doesn’t work.

This will work, unless it’s being called from within a function – in which case it will return the function’s name instead:

$scriptName = $MyInvocation.MyCommand.Name

I needed to get the calling script’s name from within a logging function in one of my scripts, so I ended up doing this:

$scriptName = $MyInvocation.ScriptName.Replace((Split-Path $MyInvocation.ScriptName),'').TrimStart('')

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s