We help IT Professionals succeed at work.
Get Started

PowerShell + VMM + RegEx match

328 Views
Last Modified: 2014-08-21
I wrote up a PowerShell snippet that connects to VMM 2012 R2, and searches through all VMs.  What I'd like this script to do is match any VM's that have _Replica in their name, and rename them.  

Right now, the script works, however it goes through the renaming process for EVERY VM.  I'd only like it to perform this function on the VM's that have "_Replica" in them.  For instance:

testing123_Replica needs to rename to testing123.  VMtest123 should be ignored.  

Experimenting with Write-Host - I only want it to affect VMs with _Replica in the name - I was under the impression that Match would display a match, vs replacing.

Thank you for help!  


### This should rename the VM if it contains the string _Replica ###

$VMs = Get-VM -VMMServer "vmmserver01.domain.com" | Sort-Object Name
ForEach ($VM in $VMs) 
{
    $vmNameNew = [RegEx]::Match($VM.Name,"^[^_]+")
    Write-Host "Virtual Machine:" $vmNameNew
    $vmNameNew
    #Set-SCVirtualMachine -VM $VM -Name $vmNameNew
}

Open in new window


This currently enumerates and renames only VM's with _Replica, but I'd like it to skip over the VMs that do NOT have _Replica.
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE