I don't understand this behavior

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Adam Bertram Adam Bertram 2 years, 12 months ago.

  • Author
    Posts
  • #16569
    Profile photo of Adam Bertram
    Adam Bertram
    Moderator

    In a module, I have the following function snippet:

    function Get-InstalledSoftware {
    	
    	[CmdletBinding()]
    	param (
    		[string[]]$Name,
    		[string[]]$Publisher,
    		[string[]]$Computername = 'localhost'
    	)
    	begin {
    		Write-Verbose "Initiating the $($MyInvocation.MyCommand.Name) function...";
    		if ($Name) {
    			## Allow asterisks in cmdlet but WQL requires percentage
    			$Operator = @{ $true = 'LIKE'; $false = '=' }[$Name -match '\*']
    			$Name = $Name | foreach { $_.Replace('*', '%') }
    			$WhereQuery += "(ARPDisplayName $Operator '$($Name -join "' OR ARPDisplayName $Operator '")') "
    		}
    		
    	}
    }

    I am passing the strings 'name*' and 'name' to the $Name param and $Operator is always null. I can recreate this in the console and it works as expected. If $Name has a * in it, $Operator is LIKE. If $name doesn't have a * in it, $Operator is =.

    Can anyone shed some light on this?

  • #16572
    Profile photo of Jason Hofferle
    Jason Hofferle
    Participant

    It looks like it has to do with your $Name parameter being a string array, while in the assignment of the $Operator variable it's being treated as a string. If I change the param block to [string]$Name I get the correct result.

    I'm guessing when you tested it in the console, you tried $Name = 'name' and not [string[]]$Name = 'name'.

  • #16576
    Profile photo of Adam Bertram
    Adam Bertram
    Moderator

    Yep, that was it. Thanks! Amazing how a couple of characters can screw you up. 🙂

  • #16585
    Profile photo of Bob McCoy
    Bob McCoy
    Participant

    At least it didn't cost you millions.
    [url]http://gizmodo.com/the-typo-that-destroyed-a-nasa-rocket-1596004226?utm_campaign=socialflow_gizmodo_facebook&utm_source=gizmodo_facebook&utm_medium=socialflow[/url]

  • #16587
    Profile photo of Adam Bertram
    Adam Bertram
    Moderator

    Ha, good point!

You must be logged in to reply to this topic.