$MyInvocation.MyCommand.Path returning NULL

后端 未结 2 1474
一向
一向 2020-12-18 18:52

I have the following code as the beginning of a longer script:

$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
& $ScriptPath\\build_functions.ps1
&         


        
相关标签:
2条回答
  • 2020-12-18 19:15

    $MyInvocation is an automatic variable populated at script run time, then if you execute $MyInvocation.MyCommand.Path in a powershell console or ISE isn't populated;

    that's why in your test the $ScriptPath has no value ($null)

    0 讨论(0)
  • 2020-12-18 19:22

    I don't if what happened to me was why some where seeking null in $MyInvocation.MyCommand.Path, but I will explain how I found the solution.

    I had scripts that were working in production, yet when I loaded the .ps1 file up and tried to get $MyInvocation.MyCommand.Path it was null. My version of Powershell was 4.0, but 1.0 for the ISE (%windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe).

    But it didn't occur to me at first why they should work, yet when I manually inspected $MyInvocation.MyCommand.Path or $MyInvocation in PowerShell why it was null, and why I was getting a null error for Split-Path -parent $MyInvocation.MyCommand.Path.

    So I thought I needed to upgrade the powershell to 5.1 on my Windows 2012 R2 Server like on my desktop NUC PC.

    The real problem was that I found that if I set a break point in my .ps1 file and ran it to the spot where I was doing:

    $ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path

    That it worked. Of course it worked, I had been using it for a while. Why didn't I see it before?

    What went wrong? I was trying to manually run the PowerShell in pieces using the run step command, when I had never run the script before since PowerShell was open!

    I have to say this is probably a No Duh moment.

    But we had recently had a server crash and had it restored (VSphere Clustered) and reseeded, so I thought maybe I have an older version of PowerShell.

    PowerShell allows you to have multiple files/windows open inside it, yet the variables are shared between them. Apparently until you actually try to run the script (not step by step run), it has no script file executing and can't get you the path.

    I hope this post saves someone from wasting a bunch of time like I did!

    0 讨论(0)
提交回复
热议问题