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