Automation

 View Only
  • 1.  avoid splitting a string if it starts with..

    Posted May 08, 2020 01:32 AM

    Hi all,

    I have the below command:

    Get-VM | Select Name,PowerState,

            @{N="IP";E={@($_.guest.IPAddress[2])}},

            @{N="OS";E={$_.ExtensionData.Config.GuestFullname}},

            @{N='VMHost';E={$_.VMHost.Name}},

            @{N="code";E={$_.name.Split('')[0].Split('-')[0]}}

    And I have these VMs fo example:

    abc-vm-01

    abc-vm-02

    abc-vm-03

    def-vm-01

    def-vm-02

    ghi-vm-01

    The last part "@{N="code";E={$_.name.Split('')[0].Split('-')[0]}}" will split the VM names and get:

    abc

    abc

    abc

    cde

    cde

    fgh

    what can I do to get the command to split only the ones starting with "abc" and avoiding the ones that are not starting with "abc"? Like:

    abc

    abc

    abc



  • 2.  RE: avoid splitting a string if it starts with..
    Best Answer

    Posted May 08, 2020 06:33 AM

    Try like this.
    I'm not sure why you have that 1st Split (.split('')[0]) in there?

    Get-VM |

    Select @{N="code";E={

       if($_.Name -match "^abc"){

          $_.Name.Split('-')[0]

       }

       else{$_.Name}

    }}



  • 3.  RE: avoid splitting a string if it starts with..

    Posted May 08, 2020 05:59 PM

    I had the Split (.split('')[0]) there for other VMs with other naming convention.

    Thank you it worked perfect, it's completely different from what I was thinking :smileyhappy: