powershellforeachtextchangedformattable

Change variable specific text with powershell and create a table


I'm trying to change some words inside a variable that contains a table.

I was able to do it using a foreach with -replace but then I can't form again the table.

1st try

$vms = Get-AZVm -status | Select-Object -Property Name, ResourceGroupName , PowerState 
$tabla = foreach ($item in $vms) {
$item.Name
$item.ResourceGroupName
$item.PowerState -replace 'VM Deallocated','Apagada' -replace 'VM running','Encendida' 
} | Format-Table

2nd try

$vms |foreach{$_.PowerState -replace 'VM Deallocated','Apagada' -replace 'VM running','Encendida'} | Select-Object -Property Name, ResourceGroupName , PowerState | format-table -autosize

I expect after the replacement of text inside the table to leave the same as a table and not text


Solution

  • I cannot test this myself, but I think using a calculated property would be easiest:

    $vms = Get-AzVM -status | 
           Select-Object -Property Name, ResourceGroupName, 
           @{Name = 'PowerState'; Expression = {($_.PowerState -replace 'VM Deallocated','Apagada') -replace 'VM running','Encendida'}} 
    
    $vms | Format-Table -AutoSize