[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 284
  • Last Modified:

PowerShell + VMM + RegEx match

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.
0
JWeb Admin
Asked:
JWeb Admin
  • 2
  • 2
1 Solution
 
käµfm³d 👽Commented:
Why do you need a regex?

### 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) 
{
    If ($VM.Name.Contains("_Replica"))
    {
      $vmNameNew = $VM.Name.REplace("_Replica", "")
      Write-Host "Virtual Machine:" $vmNameNew
      $vmNameNew
      #Set-SCVirtualMachine -VM $VM -Name $vmNameNew
    }
}

Open in new window

0
 
JWeb AdminAuthor Commented:
Doesn't have to be a regex  - is this more efficient?
0
 
käµfm³d 👽Commented:
Did you see my proposed code snippet?
0
 
Terry WoodsIT GuruCommented:
It's generally more efficient not to use a regex when no pattern wildcards are needed in a value to be matched or replaced.
0
 
JWeb AdminAuthor Commented:
Excellent  thank you!  It works great.  I was over thinking it I suppose.
0

Featured Post

 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now