简体   繁体   English

Powershell-在点源函数中获取调用脚本的脚本名

[英]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? 有什么办法可以将调用脚本的脚本名转换成基于点的ps1脚本? This would be awsome for logging. 这对于日志记录来说太糟糕了。

eg: script test1.ps1 is calling a function from dot-sourced log.ps1. 例如:脚本test1.ps1正在从基于点的log.ps1中调用一个函数。

The String "test.ps1" is needed in log.ps1. log.ps1中需要字符串“ test.ps1”。 Is this possible? 这可能吗? Thanks in advance 提前致谢

If you are dot sourcing log.ps1 then the execution is still occurring within Test.ps1 . 如果您是点源log.ps1那么执行仍在Test.ps1Test.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. 然后,您可以在点源脚本提供的任何日志记录功能中使用$ExecutingScript

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. @SomeShinyObject的解决方案很好,但是当您的日志记录脚本来自文件时,又是来自另一个文件,那么您就遇到了问题。 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. 它首先通过使用(Get-PSCallStack).length获取堆栈深度来从调用堆栈中获取最高帧,然后再使用此值获取帧本身并从此处获取ScriptName,这是调用层次结构中最高级的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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