简体   繁体   中英

Powershell - getting the scriptname of calling script in dot-sourced function

is there any way to get the scriptname of the calling script into a dot-sourced ps1 script? This would be awsome for logging.

eg: script test1.ps1 is calling a function from dot-sourced log.ps1.

The String "test.ps1" is needed in log.ps1. Is this possible? Thanks in advance

If you are dot sourcing log.ps1 then the execution is still occurring within Test.ps1 .

To get the name of the executing script use:

$ExecutingScript = $MyInvocation.MyCommand.Name
# Test.ps1

You can then use $ExecutingScript in whatever logging functions provided by the dot sourced script.

If you need the entire path to the executing script, you would use:

$MyInvocation.InvocationName
# C:\Whereever\Test.ps1

你可以试试 :

$a = Split-Path $PSCommandPath -Leaf

I was trying to solve similar or maybe same problem - how to generate log file name based on script name. Solution from @SomeShinyObject is nice but when you have your logging script sourced from file, that is sourced from another file, then you have problem. I have arrived at following solution. In case anyone is interested.

$scriptFileName = Get-Item (Get-PSCallStack)[(Get-PSCallStack).length-1].ScriptName
$log = "$($scriptFileName.DirectoryName)\log\$($scriptFileName.Basename).log"

It basically gets highest frame from the call stack by first getting stack depth using (Get-PSCallStack).length then it uses this value in obtaining the frame itself and gets ScriptName from there, which is uppermost script in calling hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM