Search code examples
powershellcase

powershell case insensitive condition


$so= Read-Host -Prompt 'Input the OS'
$vm= Read-Host -Prompt 'Input the name'

##Querty
 Get-VM | Where-Object { $_.Name.Contains($vm.ToLower()) -or $_.Name.Contains($vm.ToUpper()) -and $_.Guest.OSFullName.Contains($so) } | Select Name |ft

Input the SO: red
Input the VMname: pprd

Gets "Name" if the variable $so contains "red" and the name contains the value $vm. But, into the object, the SO is in Sentence Case (Red), so the condition is not working.

How can I make the query without distinguishing between upper and lower case letters?

Into the object $_.Guest.OSFullName, exists more strings: SUSE, Red, Ubuntu, Microsoft, etc.


Solution

  • You can use PowerShell string matching operators, which are case-insensitive by default, as opposed to .NET string methods.

    Get-VM | 
        Where-Object { $_.Name -like "*$vm*" -and $_.Guest.OSFullName -like "*$so*" } | 
        Format-Table -Property Name
    

    Table format doesn't make much sense for a single property. To output just the names:

    Get-VM | 
        Where-Object { $_.Name -like "*$vm*" -and $_.Guest.OSFullName -like "*$so*" } | 
        ForEach-Object Name