Retrieve executed script information the best way

Brass Contributor

Hello,

 

I have this piece of code at the begining of most of my script.

 

 

$ScriptFolderPath = $PSSCRIPTROOT
$ScriptFolderName = (get-item $ScriptFolderPath ).Name
$BaseFolder = (get-item $ScriptFolderPath ).parent.FullName
$ScriptName = $MyInvocation.MyCommand.Name
$ScriptNameNoExtension = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Source)

 

 

Is there a clean, durable and standardized way of getting all these values (working in PS5 and 7) ?

 

Thank you.

9 Replies
For logging? Start-Transcript -Path c:\temp\log.txt at the start en Stop-Transcript at the end of the script logs all console output, but setting up variables won't be shown in it unless you write-host $ScriptFolderPath for example
Did this help?

@Harm_Veenstra 

 

Sorry for the late answer.

I think my question was not clear enough.

 

Basically I need to set these variables because I want to use them in my scripts (so transcript isn't an option). But as you can see in my code I am using different ways to get the said values.

 

My question was, is there any standardize way to all the values? (Using the same logic for all of them). Still not clear maybe...

Ah, you want to read them from somewhere in your scripts? Or do you want to output them? Confused :D
Let say script $ScriptFolderPath, I use it to call CSV files located next to the called script.
$ScriptNameNoExtension, I use it to generate log files with the name of the script. Etc
Do you want to insert these into your script as a Code snippet or something? Like a template script?
Template script if you will yes.

The section of code I have written in my first message is at the beginning of all my main scripts.
I just want to know what is best to retrieve these values. Using $PSSCRIPTROOT method, using $myinvocation or something else.
For the PowerShell_ISE editor, you could create snippets like this https://learn.microsoft.com/en-us/powershell/module/ise/new-isesnippet?view=powershell-5.1 . Import them in your script when running ISE by using CTRL-J. In VSCode it's a bit different, https://code.visualstudio.com/docs/editor/userdefinedsnippets