Author Posts

May 17, 2018 at 3:31 pm

hello all,

My initial goal was to retrieve a set of specific strings (virtual machine names) out of txt file.
Because I wanted only the VM name, I used the -replace operator to remove the unnecessary string ("Display Name:") in a calculated property.
Thus, my final command would be:
get-content vm-process.txt | select-string "Display Name:" | Select @{l='VM Name'; e={$_.line -replace 'Display Name: ',' ' }} | sort -Property 'VM Name'

Whilst my output (shown below) is the anticipated, I would like to polish it by eliminating this which space prior to each 'vmnumber'. Any ideas? if there is a "faster" way to do it is also welcome.

VM Name
-------
    vmnumber1
    vmnumber2
    vmnumber3
    vmnumber4
    vmnumber5
    vmnumber6

May 18, 2018 at 7:02 pm

\s* is any amount of whitespace. You can replace it with the empty string ". You can try out regex interactively at https://regex101.com.

PS /Users/js> 'Display Name:     VM1' -replace 'Display Name:\s*',''                                                              

VM1

May 18, 2018 at 7:27 pm

You could use the .trimStart() – method to remove leading withespace ... if there is trailing withespace as well you could use the .trimEnd() – method. ... like this

get-content vm-process.txt  |
    ForEach-Object {
        $_.trimStart().trimEnd()
    }

May 19, 2018 at 6:11 pm

thank you both