[英]Powershell: how to replace a value within format-table
我想用相對路徑來縮短目錄:
$Dir = get-childitem C:\temp -recurse
$List = $Dir | where {$_.extension -eq ".txt"}
$List | format-table name, Directory -replace "C:\temp", ""
我收到此錯誤:
Format-Table : A parameter cannot be found that matches parameter name 'replace'.
At line:3 char:38
+ $List | format-table name, Directory -replace "C:\temp", ""
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Format-Table], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.FormatTableCommand
什么是正確的語法?
您可以使用計算所得的屬性 。 例:
$List | Format-Table name,
@{Name = "Directory"; $Expression = {$_.FullName -replace "C:\\temp", ""}}
計算出的屬性只是指示該屬性內容的哈希表。 計算的屬性可用於格式化cmdlet,這些cmdlet可以選擇屬性並輸出新的自定義對象(例如Select-Object
, Format-List
等)。
( -replace
一句: -replace
運算符使用正則表達式,因此您需要編寫C:\\\\temp
而不是C:\\temp
。)
如果您的目標是輸出文件系統項目目錄名稱: Directory
不是所有文件系統對象的屬性。 你是這個意思嗎?
Get-ChildItem C:\Temp\*.txt -Recurse | Format-Table Name,
@{Name = "Directory"; Expression = {$_.FullName -replace 'C:\\temp', ''}}
注意此命令如何利用管道(不需要中間的$List
或$Dir
變量)。
添加到@Bill_Stewart的答案中。
$Dir = get-childitem C:\temp -recurse
$List = $Dir | where {$_.extension -eq ".txt"}
$List | format-table name, @{Label="Directory"; Expression={$_.Directory -replace "C:\\temp", ""}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.