VMware Cloud Community
DZ1
Hot Shot
Hot Shot

Regex match for a VM name.



I don't know why I can't find this online, I am trying to match some VM names, but I only want to pull VMs that have 2 or more underscores "_" in their name, but the underscores are not going to be consecutive.  I have been searching but I can't find what I want online, everything seems to have repeating characters.


 Get-VM | where { $_.name -match "_" } # I just need that extra code for 2 underscores, that are not repeating


I would want to be able to find the first VM, but not the second. 


VM_1_3

VM_1-3

7 Replies
kunaludapi
Expert
Expert

Get-VM | where-object {$_.name -match "_" -and $_.name -notmatch "-"}

--------------------------------------------------------------- Kunal Udapi Sr. System Architect (Virtualization, Networking And Storage) http://vcloud-lab.com http://kunaludapi.blogspot.com VMWare vExpert 2014, 2015, 2016 If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
Reply
0 Kudos
DZ1
Hot Shot
Hot Shot


Thanks, but that was just an example I gave with the two VMs.  The names may or may not have a dash, the main part is getting VMs with 2 or more underscores that are not repeating underscores. 

Reply
0 Kudos
kunaludapi
Expert
Expert

This one is tricky Smiley Happy

get-vm | where-object {$_.name -match "_" -and $_.name -notmatch "-" -and $([char[]]($_.Name) -match "_").count -gt 1}

--------------------------------------------------------------- Kunal Udapi Sr. System Architect (Virtualization, Networking And Storage) http://vcloud-lab.com http://kunaludapi.blogspot.com VMWare vExpert 2014, 2015, 2016 If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
Reply
0 Kudos
DZ1
Hot Shot
Hot Shot



Thank you, thank you.  The 

Reply
0 Kudos
DZ1
Hot Shot
Hot Shot


It looks like my post was cut off.  Thanks again, I was writing that I knew that it had to be something with the "_" being greater than 1, but I could not, and I see that I would not have figured this one out.  Not even searching online would have produced these results since most sites just dealt with regex use that all were similar.  Thanks again for this, it really helps.

Reply
0 Kudos
LucD
Leadership
Leadership

And since you asked for a RegEx, try this one :smileygrin:

$names = "VM_1_3","VM_1-3","VM__1","VM1"
$names | where {$_ -match [regex]"\w+_[^_]+_\w+"}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

DZ1
Hot Shot
Hot Shot


Thanks LucD, I think I messed up in my original post.  I did want VMs with 1 or more underscores in their names, but the example I gave was just an arbitrary one.  I like both methods, so I'll add them to my snippets of code to use.  Thanks again for the replies.  

Reply
0 Kudos