【问题标题】:$MyInvocation.MyCommand.Name Providing Strange Results$MyInvocation.MyCommand.Name 提供奇怪的结果
【发布时间】:2014-09-01 18:49:53
【问题描述】:

为什么$MyInvocation.MyCommand.Name 在函数内执行时会给出函数的名称? 根据this,它旨在为您提供脚本文件名。 这是我正在使用的代码:

function startScript
{
    $ScriptName = $MyInvocation.MyCommand.Name
    $ScriptName
}

$ScriptName = $MyInvocation.MyCommand.Name
$ScriptName

startScript

<#
Output:

testing.ps1
startScript
#>

【问题讨论】:

    标签: powershell


    【解决方案1】:

    根据PowerShell documentation

    $MyInvocation
           Contains an information about the current command, such as the name, 
           parameters, parameter values, and information about how the command was
           started, called, or "invoked," such as the name of the script that called
           the current command. 
    
           $MyInvocation is populated only for scripts, function, and script blocks. 
           You can use the information in the System.Management.Automation.InvocationInfo
           object that $MyInvocation returns in the current script, such as the path
           and file name of the script ($MyInvocation.MyCommand.Path) or the name of a
           function ($MyInvocation.MyCommand.Name) to identify the current command. 
           This is particularly useful for finding the name of the current script.
    

    如果您对脚本路径感兴趣,另请参阅以下段落:

       Beginning in Windows PowerShell 3.0, $MyInvocation has the following new
       properties. 
    
       -- PSScriptRoot: Contains the full path to the script that invoked the
          current command. The value of this property is populated only when
          the caller is a script.  
    

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2012-12-16
      • 2012-12-06
      • 2016-08-24
      相关资源
      最近更新 更多