How to search array of objects contains an item in another array? How to search array of objects contains an item in another array? powershell powershell

How to search array of objects contains an item in another array?


Use to -notin or -notcontains operator for that.

$importvms | ?{$_.Name -notin $vms.name} | %{ Do Stuff }

Alias ? used for Where, and % used for ForEach.

Ok, it that doesn't work we can try building a regex match string out of your array of current VM names, and matching each imported VM against that to see if it already exists. Try this script:

Connect-VIServer -Server vCenter -Protocol https -Force | out-null$importVms = Import-Csv vCenterVMs.csv$VMHost = "esxi"$currentVms = Get-VMWrite-Host "Current registered VMs" -ForeGroundColor Cyan$currentVMsWrite-Host "Saved VMs to import" -ForeGroundColor Yellow$importVms$registered = @()Write-Host "Importing VMs..." -ForeGroundColor White#$importVms | ?{$_.Name -notcontains $currentVms}$VMNameFilter = "($(($currentVms|%{[RegEx]::Escape($_.Name)}) -join "|"))"foreach ($vm in $importVms) {    if (! $vm.Name -match $VMNameFilter) {        Write-Host "Importing $($vm.Name)"        # put in a try block here        $registeredVM = New-VM -VMFilePath $vm.VmPathName -VMHost $VMHost -Location $vm.Location        $registeredList += $registeredVM.Name    }}$registeredListDisconnect-VIServer -Server * -Confirm:$false


Another way, which would be better used in a script:

Foreach ($ImportVm in $ImportVms.name) { if ($vms.name -notcontains $ImportVm) {DO STUFF }}

The Foreach is looping through the VM names in the array $ImportVMs, putting each individual VM name from $ImportVMs in the variable $ImportVM at each loop.

Then , the "if" statement checks if the array of names in $vms doesn't contain the $ImportVM currently in the loop.If this "if" statement evaluates to true, then the script will do whatever is inside the { }.I just put { DO STUFF } here, because you didn't mention what you want to do with these VMs.