Written by 10:28 am Microsoft, Microsoft Azure, PowerShell, Windows, Windows Server • 9 Comments

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"

Tags: , , , , , , , Last modified: June 26, 2019
Close Search Window
Close