Powershell灵魂三问:我是谁,我在哪,我从哪里来?

调查背景:

想知道如何自动获取当前运行的脚本名称,脚本路径,脚本父文件夹。

先说结论:

我是谁?

myInvocation.myCommand.name (如果在Function中调用该命令,返回Function名称。如果在当前脚本调用其他脚本,即运行&<scriptname>,且该命令写在子脚本上,返回子脚本的名称) Split-PathMyInvocation.MyCommand.Path -Leaf (不能用于function中,否则会报错)

我在哪?

完整路径: PSCommandPath 目录信息:PSScriptRoot 或者(Split-PathMyInvocation.MyCommand.Path)-后者不能用于function中,否则会报错。

我从哪里来?-谁是我父亲,我是谁父亲,谁是我侄子,谁是我孙子。

父脚本的完整路径: myInvocation.scriptName &myInvocation.psCommandPath
父脚本的目录信息: myInvocation.psScriptRoot 如myInvocation.psScriptRoot 在以下场景中执行
执行脚本命令行,没有父亲,返回为空。
执行脚本内Function,父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地source其他脚本)父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地&其他脚本)父亲为当前脚本,返回当前脚本路径。
执行其他脚本的Function,(本地&其他脚本)父亲为当前脚本,返回当前脚本路径。
A & B, B & C. C的父亲为B。返回B脚本路径。

测试结论如下:

尽量使用 PSCommandPath 和PSScriptRoot 来查找Script本身的路径,慎用 MyInvocation。myInvocation.scriptName & myInvocation.psCommandPath &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 is an Automatic Variable, which are built-in variables that contain information about the PowerShell environment itself.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, _ is a variable that contains the current argument (similar to Perl's_ ), and is a most frequently used variable in scripting.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容