Search code examples
powershell

Get running script name from a function


I can't seem to get this idea to work with good results.

I am trying to have meaningful automatic filename creating based on the running script name.

   function GetScriptName {
            $callStack = Get-PSCallStack
            $callerScript = $callStack[2].Location  # Get the outermost script location
            
            if ([string]::IsNullOrWhiteSpace($callerScript)) {
                return $null
            }
            
            return $callerScript
        }

If I paste the function above into a script and run that script the function works.

If I import the function into a script and call it with GetScriptName while that script is running often there is nothing returned or I get the file name of the function which is not helpful.

$callStack = Get-PSCallStack
$callerScript = $callStack[1].Location

i have tested with various numbers inside [] and I have tested a function that contains the line below

[System.IO.Path]::GetFileName($MyInvocation.MyCommand.Path)

All results are either blank or the file name of the function inconsistent unless the code above is run in the script itself.


Solution

  • Unless someone has a better answer. I will just add the following to my scripts that need automatic names. Its a bummer that I can't get it to work as an imported function.

    $filename = $home + [IO.Path]::DirectorySeparatorChar + (Get-Date).ToString("yyyy-MM-dd_") + [System.IO.Path]::GetFileName($MyInvocation.MyCommand.Path) -replace '\.[^.]+$','.csv'