簡體   English   中英

Powershell:如何在格式表中替換值

[英]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-ObjectFormat-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM