代码之家  ›  专栏  ›  技术社区  ›  Purclot

拆分路径-路径$PSCommandPath-父级

  •  1
  • Purclot  · 技术社区  · 6 年前

    我在用 PowerShell 版本。 5.1.14393.2248 我的脚本位于以下路径中: C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker .

    我想得到这样的父路径: C:\Anwendungen\PowershellAddOn\Modules . 当我跑步时:

    $destination = Split-Path -Path $PSCommandPath -Parent
    $destination 
    

    我还是会 C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker 而不是 C:\Anwendungen\PowershellAddOn\Modules

    我做错了什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Martin Brandl    6 年前

    你应该 检查$PSCommandPath的输出 当运行脚本时。它可能没有指向 C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker 从你调用:

    Split-Path C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker

    你会得到 C:\Anwendungen\PowershellAddOn\Modules .

        2
  •  1
  •   JosefZ    6 年前

    阅读 about_Automatic_Variables :

    $PSCommandPath
       Contains the full path and file name of the script that is being run. 
       This variable is valid in all scripts.
    …
    
    $PSScriptRoot
       Contains the directory from which a script is being run. 
    
       In Windows PowerShell 2.0, this variable is valid only in script modules
       (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
    

    使用:

    $destination = Split-Path -Path (Split-Path -Path $PSCommandPath -Parent) -Parent
    

    或者,在Windows PowerShell 3.0及更高版本中:

    $destination = Split-Path -Path $PSScriptRoot -Parent