根据从另一个脚本或shell调用的不同来区分脚本中的代码



当脚本A从另一个脚本B调用时,我试图区分脚本A中的代码,而不是单独运行时。

脚本A

$callingScript = $MyInvocation.MyCommand.Source | Split-Path -Leaf
if($callingScript -eq "$($MyInvocation.MyCommand.Name)"){
# Script is run from Shell
}else{
# Skript is called from script B.ps1
}

脚本B

(...)
& "$($PSScriptRoot)A.ps1" 

结果总是$callingScript是A.ps1并且Name也是A。有什么想法可以做到这一点吗?

在脚本中,$MyInvocation.PSCommandPath包含:

  • 调用脚本的完整路径-如果有的话。

  • 否则,空字符串;也就是说,如果直接从PowerShell提示符或通过CLI-powershell.exe(Windows PowerShell(/pwsh(PowerShell Core(调用脚本,则返回空字符串。

因此:

if (-not $MyInvocation.PSCommandPath){
# Script was called from the PowerShell prompt or via the PowerShell CLI.
'DIRECT invocation'
}
else {
# Script was called from the script whose path is reflected in
# $MyInvocation.PSCommandPath
'Invocation VIA SCRIPT'
}

注意

  • 据我所知,$MyInvocation.ScriptName包含与$MyInvocation.PSCommandPath相同的信息;为了与$PSCommandPath对称,我在上面选择了后者

  • 函数相对于这些属性被忽略-只有封装脚本才重要。

    • 然而,Get-PSCallStack的输出也反映了函数。

    • 如果点源一个脚本(. ./script.ps1(,定义了一个调用目标脚本的函数,并且您稍后调用该函数,则无论您从调用函数,$MyInvocation.PSCommandPath仍将反映源-脚本(即使您直接从提示或通过另一个脚本调用它(。

这个应该有效:
Script-A.ps1

if ($MyInvocation.InvocationName -eq $MyInvocation.MyCommand.Source)
{
Out-Host -InputObject ('Script startet with: ' + $MyInvocation.InvocationName)
}
else
{
Out-Host -InputObject ('Script startet with: ' + $MyInvocation.ScriptName)
}

脚本-B.ps1

& C:TempScript-A.ps1

输出:

PS C:> C:TempScript-A.ps1
Script startet with: C:TempScript-A.ps1
PS C:> C:TempScript-B.ps1
Script startet with: C:TempScript-B.ps1

事实上,我会使用输入参数(开关(来识别这种情况,因为上面的方法只有在ISE中使用F5执行文件或直接在powershell.exe中运行脚本时才有效。

最新更新