调查背景:
想知道如何自动获取当前运行的脚本名称,脚本路径,脚本父文件夹。
先说结论:
我是谁?
MyInvocation.MyCommand.Path -Leaf (不能用于function中,否则会报错)
我在哪?
完整路径: PSScriptRoot 或者MyInvocation.MyCommand.Path)-后者不能用于function中,否则会报错。
我从哪里来?-谁是我父亲,我是谁父亲,谁是我侄子,谁是我孙子。
父脚本的完整路径: myInvocation.psCommandPath
父脚本的目录信息: myInvocation.psScriptRoot 在以下场景中执行
执行脚本命令行,没有父亲,返回为空。
执行脚本内Function,父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地source其他脚本)父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地&其他脚本)父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地&其他脚本)父亲为当前脚本,返回当前脚本路径。
A & B, B & C. C的父亲为B。返回B脚本路径。
测试结论如下:
尽量使用 PSScriptRoot 来查找Script本身的路径,慎用 myInvocation.scriptName & myInvocation.psScriptRoot 返回的均为调用者脚本信息。找到谁是调用者脚本很关键。
$myInvocation.myCommand.name 均为调用者信息,调用者可能是Function,script.
更多信息参考:
$MyInvocation
Contains information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command. $MyInvocation is populated only for scripts, function, and script blocks.
$PSScriptRoot ?
PSScriptRoot contains the directory path of the script being executed currently. psm1), but beginning with PowerShell 3.0, it works for all PowerShell script files.
Beside above, what is MyInvocation MyCommand definition? MyCommand. Definition can be useful to determine the folder in which the current script is stored, i.e. to access other resources located in the same folder. Now, $MyInvocation turns out to be useless because it always returns information about who invoked the current script block.
$?
in Powershell? Edit: TechNet answers in tautology, without explaining what 'succeed' or 'fail' mean. $? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.
Which built in variable can be used to refer to the current object in PowerShell?
PowerShell has many predefined variables, called automatic variables. Some of them are used for scripting, some give info about the environment. For example, _ ), and is a most frequently used variable in scripting.