Powershell中的Powershell文件的文件夹路径

时间:2012-01-30 12:37:12

标签: powershell

似乎没有人问这个简单的问题,所以我会。

我的PowerShell脚本文件位于:C:/this-folder/that-folder/another-folder/powershell-file.ps1

如何获取返回的变量:C:/this-folder/that-folder/another-folder/

4 个答案:

答案 0 :(得分:33)

在您的脚本中尝试此命令:

Split-Path -parent $MyInvocation.MyCommand.Definition

答案 1 :(得分:17)

在PowerShell 3.0中,您可以使用新的$PSScriptRoot变量获取它,使用$PSCommandPath可以获得完整的脚本路径。

MVP Keith Hill也有一篇很棒的帖子,你可以查一下:

http://rkeithhill.wordpress.com/2010/09/19/determining-scriptdir-safely/

答案 2 :(得分:2)

我假设你想知道你的脚本在运行时运行的文件夹。

这应该这样做:

Split-Path $MyInvocation.MyCommand.Path

答案 3 :(得分:1)

您可以使用标准.Net方法

$dirName=[System.IO.Path]::GetDirectoryName("c:\temp\abc\myproj1\newdata.txt")

来自http://techibee.com/powershell/powershell-get-parent-directory-name-from-file-or-directory-path/2595