, , , ,

Get name of the PowerShell script file inside the script

PowerShell

When you create a PowerShell script you sometimes want to create some output for a log file for example. In many cases, it makes sense to use the script file name for the log file so you can easily see from which .ps1 the .log file was generated for example. To get the name of the PowerShell ps1. file you can use the following command from MyInvocation:

$MyInvocation.MyCommand

This will return the ps1. file object. To get only the name string you could use:

$MyInvocation.MyCommand.Name

To create a log file with the script file name you could use the following commands:

$path = Get-Location
$scriptName = $MyInvocation.MyCommand.Name
$scriptLog = "$path\$scriptName.log"

9 responses

  1. Claudio Spizzi Avatar
    Claudio Spizzi

    The Get-Location command returns the path where the shell lives. This can ne diffetent to the script location.

    So if you want store the log allways in the same location as the scirpts, us one of the following:
    $PSScriptRoot
    Split-Path -Path $MyInvocation.MyCommand.Path

  2. Daniel Avatar

    Yes. I use this in scripts that generate email reports. Handy to be able to track down which script was responsible for the email.

  3. stephane Avatar

    Hi thomas,

    To complete your article, I think it is important to add that the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script. (Nested script scenarios for example).

    The $PSScriptRoot though, returns the current script root of the current script. Also,$PSScriptRoot works only for modules in PS version 2.0. It works in every script from Powershell version 3.0 and above.

    If you are launching your script from the ISE and it is not saved, it wont work. You can then use $psISE.CurrentFile.FullPath to get the path of the current active tab.

    Cheers

  4. Vaibhav Avatar
    Vaibhav

    Hi,
    Can anyone tell me how to get the PID of the script inside the script.

    Thanks,

  5. David Wallis Avatar

    Just stumbled on this looking for somehting else, but @Vaibhav $pid

  6. logg.sar Avatar

    Hi

    this returns a file called script.ps1.log

    I prefer

    $scriptLog = ($scriptName).Replace(“ps1″,”log”)

  7. Ian Manning Avatar

    Thanks for this blog post, really helpful!

  8. JGStew Avatar

    This got me on the right path, but ended up using:

    ($MyInvocation.MyCommand.Source + “.log”)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.