title: Powershell passing variable as a filter string
body: <p>I'm trying to write a script to retrieve the username of logged in users from servers, (This is an exercise in working with unformatted string data I'm aware of other methods to get this data so please don't suggest them)</p>
  
  <p>I'm trying to pass a numeric string from a WMI query into a where-object filter
  This is reading the WMI output from the Win32_LoggedOnUser class</p>
  
  <pre><code>$Name | where {$_.Dependent -like $ID } | select Antecedent
  </code></pre>
  
  <p>the problem seems to be in reading the ID variable, I've tried several variations which is a value concatenated with some wildcards for the filter format, I was tipped off to this when I converted the string to CSV format so I could more easily do a [regex]::Split, I get an error that the InputObject is null, If I run the above line alone I just get back a null result, if I manually enter the filter string I get the output I want.</p>
  
  <pre><code>[String]$ID = "'*"+$UserSessions.LogonId+"*'"
  </code></pre>
  
  <p>If I do a write-host I just get back '<em>146771</em>' which is what I seem to want,and get-member shows it to be a [System.String]</p>
  
  <p>then I'm throwing this to a split that grabs the last token which is the username the whole script works fine if I manually enter the filter string just not with the variable in any format I've tried</p>
  
  <pre><code>${ID}   ($ID)   ""$ID""  $($ID)
  </code></pre>
  
  <p>Here's the full script for reference</p>
  
  <pre><code>$UserSessions = GWMI Win32_LogonSession | where { $_.LogonType -eq 2}
  
  [String]$ID = "'*"+$UserSessions.LogonId+"*'"
  
  $Name = GWMI Win32_LoggedOnUser
  
  $Results = $Name | where {$_.Dependent -like $ID } | select Antecedent
  
  $Split = $Results | ConvertTo-Csv
  
  $Splat =  [regex]::Split($Split, """")[9]
  
  Write-Host "User = $Splat"
  </code></pre>