我有一些路徑,比方說C:\Windows\System32\WindowsPowerShell\。我想找到這樣一個字串,當附加時(從右側),將使該路徑指向C:\.
好吧,如果設定了路徑,這很容易;我可以做到C:\Windows\System32\WindowsPowerShell\..\..\..\。
然而,我正在尋找的是一個每次都可以作業的固定字串,無論初始路徑看起來如何(尤其是它有多長)。Windows 是否提供了一些技巧來幫助解決這個問題?如果不可能實作,那么這是一個有效的答案。
加分項:我可以這樣參考不同的硬碟嗎?
uj5u.com熱心網友回復:
用于Convert-Path決議/合并給定路徑,然后繼續添加..,直到到達卷的根:
# Grab current location from `$pwd` automatic variable
$path = "$pwd"
# Calculate path root
$root = [System.IO.Path]::GetPathRoot($path)
while((Convert-Path $path) -ne $root){
# We haven't reached the root yet, keep backing up
$path = Join-Path $path '..'
}
$path現在包含C:\Current\Relative\Path\..\..\..,您現在可以執行以下操作:
& path\to\myBinary.exe (Join-Path $path.Replace("$pwd","").TrimStart('\') targetfile.ext)
$path.Replace("$pwd", "")只給我們\..\..\.., 并TrimStart('\')洗掉前導路徑分隔符以使路徑相對,因此傳遞給二進制檔案的結果字串將是..\..\..\targetfile.ext
uj5u.com熱心網友回復:
固定字串不是一種選擇,但很容易為任意長度的給定路徑動態構造一個。
利用這一事實*,當應用于LHS 上的字串時,會將該字串復制給定次數(例如,'x' * 3yield xxx):
# Sample input path.
$path = 'C:\Windows\System32\WindowsPowerShell'
# Concatenate as many '..\' instances as there are components in the path.
$relativePathToRoot = '..\' * $path.Split('\').Count
$absolutePathToRoot = Join-Path $path $relativePathToRoot
# Sample output
[pscustomobject] @{
RelativePathToRoot = $relativePathToRoot
AbsolutePathToRoot = $absolutePathToRoot
}
注意:在 Unix 上,使用'../' * $path.Split('/').Count; 對于跨平臺解決方案,請使用"..$([IO.Path]::DirectorySeparatorChar)" * $path.Split([IO.Path]::DirectorySeparatorChar).Count; 對于可以在任一平臺上處理任一分隔符(并/在結果中使用)的解決方案,請使用'../' * ($path -split '[\\/]').Count
輸出:
RelativePathToRoot AbsolutePathToRoot
------------------ ------------------
..\..\..\..\ C:\Windows\System32\WindowsPowerShell..\..\..\..\
uj5u.com熱心網友回復:
根在 FileInfo 物件中可用。
PS C:\src\t> (Get-ChildItem -Path 'C:\Windows\System32\WindowsPowerShell\').PSDrive.Root
C:\
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/445181.html
上一篇:獲取桌面上運行的程式
