0

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

3
  • 2
    so: Get-Service | Select Status,Name, @{n='DisplayName';e={$_.DisplayName -replace "windows","linux"}} -ExcludeProperty displayname ? Commented Jan 25, 2022 at 18:51
  • 2
    @AbrahamZinala please post it as an answer Abe Commented Jan 25, 2022 at 18:55
  • @Santi, not on my computer:( feel free to do so tho lol Commented Jan 25, 2022 at 19:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.