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"
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
Yes. I use this in scripts that generate email reports. Handy to be able to track down which script was responsible for the email.
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
Hi,
Can anyone tell me how to get the PID of the script inside the script.
Thanks,
Just stumbled on this looking for somehting else, but @Vaibhav $pid
Hi
this returns a file called script.ps1.log
I prefer
$scriptLog = ($scriptName).Replace(“ps1″,”log”)
Thanks for this blog post, really helpful!
Thank you :)
This got me on the right path, but ended up using:
($MyInvocation.MyCommand.Source + “.log”)