0

I am having code where I am searching VM details using Get-VM -Name $VM_Name.

It is not giving any output in below case where I have 2 entries for same VM name like below

001_MBM1P
001_MBM1P_Clone_Prj_Win

was trying something like blow but getting error

get-vm $VM_Name | where {($_.Name -match $VM_Name) -and ($VM_Name  -notcontains 'Clone*')}
get-vm : 1/10/2022 11:36:52 AM  Get-VM      VM with name '001_MBM1P' was not found using the specified filter(s).

Please let me know how can I filter the search which will work in both cases.

Empty Coder
  • 589
  • 6
  • 19

1 Answers1

2

The -contains and -notcontains operators work on arrays only, they are not string operations.

You may use the efficient String::Contains() method:

get-vm | where {($_.Name -match $VM_Name) -and (-not $_.Name.Contains('Clone'))} 

Alternatively use the -notlike operator:

get-vm | where {($_.Name -match $VM_Name) -and ($_.Name -notlike '*Clone*')} 

Note that Contains() is case-sensitive whereas -like and -notlike are not. This Q/A shows some ways for case-insensitive "contains" operation using String methods.

zett42
  • 25,437
  • 3
  • 35
  • 72
  • Thanks for your response. wanted to know one thing. for few VM's I am able to get the data using this. but for few I am getting error which I mentioned in my post. Do you know what can be the reason? any access/restrictions? – Empty Coder Jan 10 '22 at 11:47
  • 1
    @EmptyCoder I have edited my answer to remove `$VM_Name` argument from `get-vm` call. This way it returns all VMs without complaining about VM name not found and we filter the result afterwards. Also you have to check `$_.Name` in the "contains" condition as well. – zett42 Jan 10 '22 at 11:52