TripToBelize
TripToBelize

Reputation: 73

Replace strings in Powershell object

For example, I am looking to replace the word 'Windows' with 'Linux' in an object that contains Windows Service information, like this:

$data = Get-Service

$data | ForEach-Object { $_.Displayname -replace ("Windows","Linux") }

but I still want to maintain the other fields in the object (Name, Status) whilst only the DisplayName field has the word Windows replaced with Linux

Upvotes: 0

Views: 836

Answers (2)

TripToBelize
TripToBelize

Reputation: 73

Yes I want to maintain all the properties not just Name,Status,DisplayName therefore I modified @Abraham Zinala suggestion (in the comments) with the following:

$data = Get-Service
$data | Select-Object *,@{n='DisplayName';e={$_.DisplayName -replace "Windows","Linux"}} -ExcludeProperty DisplayName

Which is actually something tried previously but without the -ExcludeProperty

Upvotes: 1

ZivkoK
ZivkoK

Reputation: 466

Your code never modifies the DisplayName property, it only displays it in your foreach loop.

The Get-Service command does return an array of System.ServiceProcess.ServiceController items, for which you can't modify only one property.

While the comment from (@Abraham Zinala) is correct and works perfectly well, it requires you to specify all the properties you need.

$data = Get-Service | Select Status,Name, @{n='DisplayName';e={$_.DisplayName -replace "windows","linux"}} -ExcludeProperty displayname

The example given takes care of three properties (Status, Name, DisplayName) but a ServiceController item has around 16 properties available.

If you want to keep all the properties (mostly) and use a simple method, you can convert the original object to something else (i.e. csv, json, etc) and convert it back to an array.

One example would be:

$data = Get-Service | ConvertTo-Csv | ConvertFrom-Csv
$data | ForEach-Object {$_.Displayname = $_.Displayname - Replace ("Windows","Linux")}

Note that this method will convert any property that is a collection, to a string (string: collection of 'object type'). If you want also to keep these, you will have to write a more complex command based on (@Abraham Zinala)'s example.

Upvotes: 0

Related Questions