當我在Powershell中輸入dir命令時,總是顯示當前路徑 幾個空行,實在是沒必要。我想設定一個別名,從結果中洗掉當前路徑。但是我可以使用什么命令/屬性來洗掉該路徑?我在互聯網或 dir 的手冊頁上找不到任何東西。
我使用 Powershell 7.2.1 并且是 PS 新手。

uj5u.com熱心網友回復:
首先,我認為提到 7.2.1 會嚇跑人們試圖回答你的問題。許多人,比如我自己,目前都使用 5.x。如果我知道如何將 7.x 安裝到 WinPE 上,我可能會做出改變。我可能錯了,但這似乎是個問題。
其次,Dir 在 PowerShell 中是 Get-ChildItem 的別名。請參閱此兼容性別名串列
第三,您需要查看使用檔案和檔案夾、Get-ChildItem和Get-Item。
第四,PowerShell 中的一切都是物件。因此,您在 Dir 中看到的所有額外行實際上并不是由 Dir 創建的,它們是 PowerShell 粘貼在那里以使其可讀的格式化絨毛。PowerShell 獲取 Dir/Get-ChildItem 回傳的物件并嘗試使它們對您來說很漂亮,但是當您直接使用這些物件時,所有這些額外的絨毛都不存在。當您開始使用 Pipeline 時,請記住這一點,它只是一次將一組物件送入管道。
第五,PowerShell 5.x 和更新版本的所有版本都有相當多的重疊,所以理論上,如果我很謹慎,我給你的 5.x 代碼應該在 7.x 中作業。如果我犯了錯誤,我想很抱歉 - 我試過了!
在這段代碼中:
- 輪流注釋掉頂部附近的“Objects =”行,然后取消注釋。
- 注意注釋掉的“$_ | Format-List -Property *”。如果您取消注釋它,它將生成一個長輸出,其中包含正在饋入管道的物件中的所有屬性。您可以使用它來查看我主要如何訪問這些物件來設定變數。
- 注意代碼中 SubString 的使用。我很難證明 SubString 在 PowerShell 核心中可用,但如果是,它是一種可用于將路徑分解為部分的工具。另一個工具是Split-Path,所以你可能想研究一下。
- 如果您有所需的單個檔案的確切名稱,則在下面的代碼中將 *.ps1 替換為該確切名稱。或者在許多將 \FileName.ext 添加到路徑末尾的命令中都可以。
- 此代碼在 Windows 中運行良好,但在其他作業系統中您可能需要進行調整。
# Uncomment only one of the following lines at a time:
#$Objects = Get-ChildItem -Path $Home -File # Gets files in home path
#$Objects = Get-ChildItem -Path $Home -Directory # Gets Directories in home path
#$Objects = Get-ChildItem -Path $PSScriptRoot -File # Gets files in same folder as the script
#$Objects = Get-ChildItem -Path $PSScriptRoot -Directory # Gets Directories in same folder as the script
$Objects = Get-ChildItem -Path "$Home\Documents" -File
#$Objects = Get-ChildItem -Path "$PSScriptRoot\*.ps1" -File
#$Objects = Get-Item -Path "$PSScriptRoot\*.ps1"
$Objects | ForEach-Object { # Get files
#$_ | Format-List -Property *
$f =$_.FullName # Get full path name
$d = "$($_.PSDrive):\" # Get the drive
$dp = $_.DirectoryName # Get drive and path
$p = $dp.SubString($d.Length) # Get path only
$n = $_.BaseName # Get file name only
$x = $_.Extension # Get file extension only
$nx = $_.Name # Get files name and extension
Write-Host
Write-Host "f: $f"
Write-Host "dp: $dp, nx: $nx"
Write-Host "d: $d, p: $p, n: $n, x: $x"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/430820.html
