Inputting name of variable RRS feed

  • Question

  • I am creating a script which ask to enter name of a Machine however I want to ensure that when I do a Get-VM with the name of Virtual Machine , it should only match the name.

    code is as below 

    $VM_Name=Read-host "Enter name of VM"

    get-vm "$VM_name*"

    Output of above is like below 

    VMName                                                                 MemoryGB 
    ------                                                                -------------------- 
    abcd-xyz (0d006048-705a-4134-8e8e-3c7f1ef65461)                0.5   

    example :

    Enter Name of VM : ABCD

    If I do a get-vm with above name "ABCD" , it will take into account ABCD1,ABCD2,ABCD34, etc..etc 

    What I want is to ensure that my variable $VM_name should only consider ABCD and not anything after that.

    Also every name as per output will have name as  below 

    abcd-xyz (0d006048-705a-4134-8e8e-3c7f1ef65461)

    abcd-xyz (0d006048-705a-4134-8e8e-3c7f1ef65461) - the part in bold is always available within braces , can someone help me in ensuring that if I enter name as ABCD it should only contain ABCD and not ABCDxyz,etc ...

    In the script I had added name as "$VM_name*" to ensure that any space in name is accounted and the part in bold is ignored.


    • Moved by Bill_Stewart Monday, May 7, 2018 10:02 PM Abandoned
    Monday, March 5, 2018 2:19 PM

All replies

  • get-vm $VM_name

    Don't use quotes and don't add a *.


    Monday, March 5, 2018 2:24 PM
  • If I don't use quote it will not take space in Name and if I don't add * at end it will fail because the string in braces will not match.

    Monday, March 5, 2018 2:28 PM
  • In PS we don't need to quote variables with spaces.  That is an old command shell issue.

    If you use the * you will get all partial matches.  You can't have it both ways.


    Monday, March 5, 2018 3:14 PM
  • I am using * just to ensure that the user doesn't have to input the stuff available inside braces , as shown below 

    abcd-xyz (0d006048-705a-4134-8e8e-3c7f1ef65461) 

    My question is if its possible to match only the string as abcd-xyz and ignoring the string in (). 

    Monday, March 5, 2018 3:28 PM
  • Not in the command parameter.  It does not support regular expressions.  You can use:

    Get-VM * | ForEach-Object { if($_.Name -match '(abcf-xyz)'){$matches})


    Monday, March 5, 2018 3:32 PM