当前位置 博文首页 > PowerShell包含另一个脚本文件和获取当前脚本所在目录的方法例子

    PowerShell包含另一个脚本文件和获取当前脚本所在目录的方法例子

    作者:洪哥 时间:2021-02-07 21:18

    本文介绍在PowerShell脚本中,如何获取脚本文件(.ps1文件)所在的目录。本文介绍在方法适用于PowerShell 3.0。

    在PowerShell 3.0中,有一个变量可以很方便的获取脚本所在的目录。我们在e:\ps\script1.ps1和script2.ps1,内容分别如下:

    script1.ps1内容:

    复制代码 代码如下:

    Write-Host "This is script1.ps1"
    Write-Host "Let me call script2.ps1:"

    . "$PSScriptRoot\script2.ps1"

    script2.ps1内容:

    复制代码 代码如下:

    Write-Host "This is script2.ps1"

    运行script1.ps1,将用调用script2.ps1的脚本代码。

    注意,在script1.ps1脚本中,我们使用了$PSScriptRoot这一变量来获取脚本所在的目录。这个变量在PowerShell 3.0中新增加的一个变量。在运行script1.ps1脚本时,这个变量就代指了E:\ps这个目录路径。

    好了,关于PowerShell使用$PSScriptRoot获取脚本所在的目录,本文就介绍这么多,希望对大家有所帮助。

    js