脚本当前目录 PowerShell54


在 PowerShell 中,获取当前脚本执行的目录对于自动化任务和管理文件非常有用。本指南将介绍获取脚本当前目录的几种方法,以便在脚本中使用它。

使用 $PSCommandPath

$PSCommandPath 变量包含脚本的完整路径(包括文件名)。您可以使用以下代码获取脚本当前目录:```powershell
$currentDirectory = Split-Path $PSCommandPath -Parent
```

使用 Get-Location

Get-Location cmdlet 可用于获取当前目录。它返回一个 对象,其中包含目录的路径。```powershell
$currentDirectory = Get-Location
$
```

使用 CD

CD cmdlet 可用于更改当前目录。通过在 CD 后面带上一个目录路径,您可以设置脚本的当前目录。```powershell
CD C:MyDirectory
$currentDirectory = Get-Location
$
```

使用 ()

() 方法可用于获取脚本当前目录。它返回一个字符串,其中包含目录的路径。```powershell
$currentDirectory = []::GetCurrentDirectory()
```

获取绝对路径

使用 Split-Path -Resolve cmdlet 可以获取脚本当前目录的绝对路径。```powershell
$currentDirectory = Split-Path $PSCommandPath -Parent -Resolve
```

获取相对路径

使用 Split-Path -Leaf cmdlet 可以获取相对于脚本目录的脚本当前目录的相对路径。```powershell
$currentDirectory = Split-Path $PSCommandPath -Parent -Leaf
```

使用 PowerShell Drive

可以使用 PowerShell 驱动器获取当前脚本当前目录。例如,は以下のコードは、現在のユーザーのホーム ディレクトリを返します。```powershell
$currentDirectory = ($env:HOMEDRIVE + $env:HOMEPATH)
```

使用 Path 变量

Path 变量包含当前目录的路径。您可以使用以下代码获取当前脚本当前目录:```powershell
$currentDirectory = (Split-Path $env:Path)[0]
```

将当前目录存储在变量中

获取脚本当前目录后,您可以将其存储在一个变量中以供将来使用。```powershell
$scriptDirectory = $currentDirectory
```

示例

以下示例脚本演示了如何获取脚本当前目录并将其存储在变量中:```powershell
$scriptDirectory = Get-Location
Write-Host "The current script directory is: $scriptDirectory"
```

获取脚本当前目录是 PowerShell 中一项有用的技术,可用于自动化任务和管理文件。本文介绍了获取脚本当前目录的几种不同方法,以便根据您的需要选择最合适的方法。

2024-12-04


上一篇:C# 中使用 PowerShell 脚本

下一篇:终止 PowerShell 脚本