Powershell 拆分路径-路径$PSCommandPath-父级
我正在使用Powershell 拆分路径-路径$PSCommandPath-父级,powershell,Powershell,我正在使用PowerShellVer5.1.14393.2248 我的脚本位于以下路径中:C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker 我想获得如下父路径:C:\Anwendungen\PowershellAddOn\Modules。 当我跑步时: $destination = Split-Path -Path $PSCommandPath -Parent $destination 我仍然会得到C:\Anwendu
PowerShell
Ver<代码>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
我做错了什么?运行脚本时,应该检查$PSCommandPath的输出。它可能不会指向
C:\Anwendungen\powershell加载项\Modules\PSScriptVersionChecker
,因为调用时:
拆分路径C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker
您将获得C:\Anwendungen\PowershellAddOn\Modules
阅读:
$PSCommandPath
包含正在运行的脚本的完整路径和文件名。
此变量在所有脚本中都有效。
…
$PSScriptRoot
包含从中运行脚本的目录。
在Windows PowerShell 2.0中,此变量仅在脚本模块中有效
(.psm1)。从Windows PowerShell 3.0开始,它在所有脚本中都有效。
使用:
或者,在Windows PowerShell 3.0及更高版本中:
$destination = Split-Path -Path $PSScriptRoot -Parent
Martin,你是对的,意思是:使用$PSCommandPath是错误的做法。将我的脚本放在:C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker\test.ps1中,$PSCommandPath使我得到:C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker\test.ps1,因此使用拆分路径会导致C:\Anwendungen\PowershellAddOn\Modules\PSScriptVersionChecker而不是(根据需要):C:\Anwendungen\PowershellAddOn\Modules。更好的方法是使用:获取位置(可能)谢谢我使用的是
$scriptPath=split path-parent$MyInvocation.MyCommand.Definition
谢谢Josef,同时我注意到了我的错误…人们不敢低估阅读和理解PowerShell帮助:-)谢谢
$destination = Split-Path -Path $PSScriptRoot -Parent