Is there any other way except $MyInvocation.InvocationName in powershell to get the script name? As i need to turn my script in an exe and in that case it doesnt work on that exe.
Asked
Active
Viewed 1.1k times
2 Answers
11
I'm assuming since you convert the powershell script to an executable that you are after the location of the executable. You can get it this way:
[Environment]::GetCommandLineArgs()[0]

jon Z
- 15,838
- 1
- 33
- 35
-
2fwiw - if you are debugging this in ISE, the script name becomes the second parameter: `[Environment]::GetCommandLineArgs()[1]` – Dave Wise May 13 '13 at 18:47
-
Try `$PSCommandPath` or `$MyInvocation.PSCommandPath` (according to this great answer : https://stackoverflow.com/a/43643346/5649639) – SebMa Nov 04 '21 at 22:31
3
If you want something that works within and outside of ISE you can use
$MyInvocation.InvocationName
Since full paths and .\YourScript.ps1 can be returned you can parse the name with:
[Regex]::Match( $MyInvocation.InvocationName, '[^\\]+\Z', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::SingleLine ).Value

Simon Mattes
- 4,866
- 2
- 33
- 53
-
When called from within a function, `$MyInvocation.InvocationName` is the function's name. – Laurent CAPRANI Apr 26 '18 at 22:41