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 8,567 times
9
-
How you call the exe and how you pass the script name? – CB. Feb 01 '12 at 11:22
-
I convert the script into exe using a utility..the functionality works fine with script but if i use the exe in place of script it doesnt work.. – Abhishek_Mishra Feb 01 '12 at 11:28
-
The only way I know is using $Myinvocation. Maybe the utility (PS2EXE maybe§??) can't convert the PSCmdlet.MyInvocation Property referring to an exe or his enclosure. – CB. Feb 01 '12 at 11:47
-
yes i too think so thats y i m searching for other option..Neways thanks fr ur interest.. – Abhishek_Mishra Feb 01 '12 at 13:22
-
maybe if you explain why you need the script name we could suggest an alternative solution. – EBGreen Feb 01 '12 at 15:01
-
I want to access the script directory within script thats y i need script name so that i cud get the path of it at run time.. – Abhishek_Mishra Feb 02 '12 at 10:44
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
- 14,930
- 1
- 31
- 35
-
Well that worked that is wat i actually wanted thanks a lot jon Z..:) – Abhishek_Mishra Feb 02 '12 at 10:45
-
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
2
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,348
- 1
- 30
- 49
-
When called from within a function, `$MyInvocation.InvocationName` is the function's name. – Laurent CAPRANI Apr 26 '18 at 22:41