Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the name of the calling script from a Powershell Module?

I have two Powershell files, a module and a script that calls the module.

Module: test.psm1

Function Get-Info {
    $MyInvocation.MyCommand.Name
}

Script: myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info

When I run ./myTest.ps1 I get

Get-Info

I want to return the name of the calling script (test.ps1). How can I do that?

like image 753
Mark Allison Avatar asked Apr 29 '14 16:04

Mark Allison


People also ask

How do I get the PowerShell script name?

You want to know the name of the currently running script. To determine the name that the user actually typed to invoke your script (for example, in a “Usage” message), use the $myInvocation. InvocationName variable.

How do I return a PowerShell script?

The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

How do you call a PowerShell script from a function?

A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.

Can you call a PowerShell script from another PowerShell script?

PowerShell scripts can run other scripts. Just put the command that runs the second script as a command in the first script (the same way as you would type it on the PowerShell command line). You can experiment with this very easily by doing a quick test.


1 Answers

Use PSCommandPath instead in your module:
Example test.psm1

function Get-Info{
    $MyInvocation.PSCommandPath
}

Example myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info

Output:

C:\Users\moomin\Documents\myTest.ps1

If you want only the name of the script that could be managed by doing

GCI $MyInvocation.PSCommandPath | Select -Expand Name

That would output:

myTest.ps1
like image 57
TheMadTechnician Avatar answered Sep 21 '22 04:09

TheMadTechnician