在PowerShell中非破坏性地编辑对象

时间:2018-01-23 19:10:18

标签: powershell

我正在尝试格式化生成的对象而不会破坏它。但是我所有的努力和研究都让我失望了。欢迎任何提示。

我的代码如下所示:

Set-Location 'C:\Temp'
$Files = Get-ChildItem -File | Select-Object FullName, Length

我得到的是这个:

FullName                       Length
--------                       ------
C:\Temp\CleanupScript.txt       10600
C:\Temp\Columns.csv              4214
C:\Temp\Content.html           271034
C:\Temp\Content.txt            271034
C:\Temp\DirSizes.csv               78

我想要的是:

FullName                       Length
--------                       ------
Temp\CleanupScript.txt          10600
Temp\Columns.csv                 4214
Temp\Content.html              271034
Temp\Content.txt               271034
Temp\DirSizes.csv                  78

当我尝试这个时:

$Files = Get-ChildItem -File | Select-Object FullName, Length | % { $_.FullName.Remove(0, 3) }

我得到了正确的结果,但我丢失了长度列。

PS C:\Temp> $Files
Temp\CleanupScript.txt
Temp\Columns.csv
Temp\Content.html
Temp\Content.txt
Temp\DirSizes.csv

请帮忙。

非常感谢 帕特里克

2 个答案:

答案 0 :(得分:3)

The easiest way to do this is to construct the property you want in the Select command, such as:

$Files = Get-ChildItem -File | Select @{l='FullName';e={$_.FullName.Substring(3)}},Length

The format for this is a hashtable with two entries. The keys are lable (or name), and expression. You can shorten them to l (or n), and e. The label entry defines the name of the property you are constructing, and the expression defines the value.

If you want to retain all of the original methods and properties of the objects you should add a property to them rather than using calculated properties. You can do that with Add-Member as such:

$Files = GCI -File | %{Add-Member -inputobject $_ -notepropertyname 'ShortPath' -notepropertyvalue $_.FullName.Substring(3) -PassThru}

Then you can use that property by name like $Files | FT ShortPath,Length -Auto, while still retaining the ability to use the file's methods like Copy() and what not.

答案 1 :(得分:3)

I would recommend using a calculated property and Split-Path -NoQualifier; e.g.:

Get-ChildItem -File | Select-Object `
  @{Name = "NameNoQualifier"; Expression = {Split-Path $_.FullName -NoQualifier}},
  Length

For help on calculated properties, see the help for Select-Object.

(Aside: To correct your terminology a bit, this is not modifying objects non-destructively but rather outputting new objects containing the properties you want formatted how you want them.)