Trouble with match operator

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Paul Johnston Paul Johnston 1 year, 5 months ago.

  • Author
    Posts
  • #31011
    Profile photo of Paul Johnston
    Paul Johnston
    Participant

    I've written a script using the match operator to find the string '^net use h: \\\\' within logon scripts. This works for the majority of our scripts (batch files) but I'm having trouble with some of them. For example, if the string appears on the first line of the logon script, the result I get for $Path is a Boolean object type when I expect it to be a String. If the string appears on any other line of the script, I get my String object, as expected. I've verified this with Get-Member. Can anyone shed some light on this for me? Here's an extract of my code :

    
    $Users = Get-ADUser -Filter {Enabled -eq $EnabledUsersOnly} -Properties ScriptPath, HomeDirectory -SearchBase $SearchBase
    
    foreach ($user in $users) {
    $Path = $Null
    $LogonScript = $Null
        
        if ($user.ScriptPath) {
            try{
                $LogonScript = Get-Content ("\\MyDomain\netlogon\" + $User.ScriptPath)
                $Path = $LogonScript -match '^net use h: \\\\'
            }
            catch{
                Write-Warning "There was an issue accessing the logon script for $($user.name)"
            }
        }
    
        if ($Path) {
            try{     
                    $Path = $Path -replace ".*:" , ""
                    $Path = $Path.Trim()               
            }
            catch{
                Write-Warning "Unable to trim path"
            }
        }
    
  • #31014
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    The -match operator (and all other comparison operators in PowerShell) will return a boolean value if the value on the left is a scalar (single value), and will act as filters if the value on the left is an array. In this case, I would assume that when you're having trouble, you're dealing with a script file that only contains a single line.

    To force the array behavior, use the array subexpression operator around your call to Get-Content. That way, even if the file only contains a single line, you'll still get back an array in your $LogonScript variable:

    $LogonScript = @(Get-Content ("\\MyDomain\netlogon\" + $User.ScriptPath))
    
  • #31018
    Profile photo of Paul Johnston
    Paul Johnston
    Participant

    Dave, you are the man! That worked a treat.

    Appreciate the help.

  • #31019
    Profile photo of Paul Johnston
    Paul Johnston
    Participant

    Issue resolved. Thanks again to Dave for the help.

You must be logged in to reply to this topic.