Automation

 View Only
  • 1.  Getting VM by name

    Posted Jun 26, 2019 12:22 PM

    I apologize for the very basic question.

    I created a script by copying parts from forum and blogs.

    I need to get a VM object by the name.

    I used two different syntaxes

    $Nome_VM = "MyServer"

    $vm = Get-VM -Name $Nome_VM

    $vm.name

    If I ussue following commands using $vm it looks that some data are missing.

    A different syntax is:

    $Nome_VM = "MyServer"

    $vm = Get-View -ViewType VirtualMachine -Filter @{"Name"=$Nome_VM}

    $vm.name

    It looks to work better and following commands work fine.

    However if there are more VMs with similar names I get all of them:

    $vm.name

    MyServer

    MyServer_001

    Myserver_002

    How can I use the second syntax and get only one VM?

    Even better, what is the best syntax to get a VM from the name?

    Regards

    marius



  • 2.  RE: Getting VM by name
    Best Answer

    Posted Jun 26, 2019 12:48 PM

    The Filter parameter on the Get-View cmdlet interprets the righthand side operator as a Regular Expression (RegEx).

    So you will have to use RegEx syntax to get an exact match.

    The ^ indicates that the match should start at the beginning of the string in Name, and the $ indicates that the match should stop at the end.

    For example like this

    $Nome_VM = "MyServer"

    $vm = Get-View -ViewType VirtualMachine -Filter @{"Name"="^$Nome_VM$"}

    $vm.name