Welcome Forums General PowerShell Q&A Trouble with match operator

Viewing 3 reply threads
  • Author
    Posts
    • #31011
      Participant
      Topics: 1
      Replies: 3
      Points: 0
      Rank: Member

      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
      Member
      Topics: 9
      Replies: 2322
      Points: 0
      Rank: Member

      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
      Participant
      Topics: 1
      Replies: 3
      Points: 0
      Rank: Member

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

      Appreciate the help.

    • #31019
      Participant
      Topics: 1
      Replies: 3
      Points: 0
      Rank: Member

      Issue resolved. Thanks again to Dave for the help.

Viewing 3 reply threads
  • The topic ‘Trouble with match operator’ is closed to new replies.