当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 中的 $PSScriptRoot - 获取执行脚本的完整路径

作者:精品下载站 日期:2024-12-14 16:36:51 浏览:14 分类:玩电脑

PowerShell 中的 $PSScriptRoot - 获取执行脚本的完整路径


PowerShell 中的$PSScriptRoot 自动变量 包含在脚本或命令中使用 $PSScriptRoot 变量的脚本的完整路径。 $PSScriptRoot 是只读的自动变量之一,当调用者是脚本时会分配其值。

在本文中,我将解释 PowerShell 中的 $PSScriptRoot 自动变量及其信息。

PowerShell PSScriptRoot 为空

如果在 PowerShell 脚本之外使用或者调用者不是脚本或命令,则 PowerShell PSScriptRoot

让我们使用以下命令了解 PowerShell $PSScriptRoot 为空

PS D:\PowerShell> $PSScriptRoot

PS D:\PowerShell>

[玩转系统] PowerShell 中的 $PSScriptRoot - 获取执行脚本的完整路径

在上面的脚本中,由于 PSScriptRoot 不是由脚本或任何命令调用的,因此其默认值为空或 null。

酷提示: Get-ChildItem cmdlet - 在 PowerShell 中搜索文件!

PowerShell 中的 $PSScriptRoot 变量

PowerShell $PSscriptRoot 包含当前脚本或命令正在执行或运行的目录的完整文件系统路径。

让我们通过一个例子来了解PowerShell PSScriptRoot,运行以下命令

PS D:\PowerShell> Get-ChildItem -Path $PSScriptRoot                                                                     

    Directory: D:\PowerShell


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-10-2020     19:17                Excel
d-----       17-07-2021     15:15                FTP-101
d-----       05-10-2020     21:14                Zip
-a----       04-10-2020     14:40             51 ActiveDirectoryGroupList.csv
-a----       24-10-2020     19:15             29 complist.txt
-a----       24-10-2020     20:08            118 comppingstatus.csv
-a----       04-10-2020     12:29           8579 Employee.xlsx
-a----       03-07-2021     17:01            961 print-spooler-service.ps1
-a----       05-10-2020     21:01        2775006 vscode-docker-master.zip

[玩转系统] PowerShell 中的 $PSScriptRoot - 获取执行脚本的完整路径

在上面的 PowerShell Get-ChildItem 命令中,命令内使用 $PSScriptRoot 变量。它获取执行脚本父目录的完整路径。

在 PowerShell 2.0 版本中,PowerShell PSScriptRoot 变量仅在脚本模块 (.psm1) 中有效。现在它在所有脚本中都有效。

酷提示:如何在 PowerShell 中创建常量和只读变量!

结论

PowerShell PSScriptRoot 自动变量包含有关正在执行脚本的目录的信息以及在脚本或命令中使用它时分配的值。

PowerShell 中还有其他自动变量,如 $Error,如果在脚本执行中引发错误,则包含错误信息。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯