Wie in früheren Antworten erwähnt, unterliegt die Verwendung von "$ MyInvocation" Umfangsproblemen und liefert nicht unbedingt konsistente Daten (Rückgabewert vs. direkter Zugriffswert). Ich habe festgestellt, dass die "sauberste" (konsistenteste) Methode zum Abrufen von Skriptinformationen wie Skriptpfad, Name, Parameter, Befehlszeile usw. unabhängig vom Umfang (in Haupt- oder nachfolgenden / verschachtelten Funktionsaufrufen) die Verwendung von "Get-" ist. Variable "on" MyInvocation "...
# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value
# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path
# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath
# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name
# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName
Sie können also die gleichen Informationen wie $ PSCommandPath erhalten, aber noch viel mehr. Ich bin mir nicht sicher, aber es sieht so aus, als ob "Get-Variable" erst auf PS3 verfügbar war, also nicht viel Hilfe für wirklich alte (nicht aktualisierte) Systeme.
Es gibt auch einige interessante Aspekte bei der Verwendung von "-Scope", da Sie zurückverfolgen können, um die Namen usw. der aufrufenden Funktion (en) abzurufen. 0 = aktuell, 1 = übergeordnet usw.
Hoffe das ist etwas hilfreich.
Ref, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable