overflowed
overflowed

Reputation: 1243

Powershell - expression in properties

I don't know how to add expressions in property declaration. I created a script to get local admin members on servers and it works fine. Now i want to add another property which should check if user specified in "Administrators" property is enabled or not, so i added property, "User Enabled" but it doesn't show anything

Foreach ($server in $servers){

 Try{
       $admins = Gwmi win32_groupuser –computer $server -Erroraction Stop
       $admins = $admins |? {$_.groupcomponent –like '*"Administrators"'}
       $admins = $admins |% { $_.partcomponent –match “.+Domain\=(.+)\,Name\=(.+)$” > $nul 
       $matches[1].trim('"') + “\” + $matches[2].trim('"') | Where-Object {$_ -like "$domain*" -and $_ -notlike "*Domain Admins*"}}
       
      

        foreach ($admin in $admins){
           # remove domain name
           $username = $admin.Split('\')[1]
           # Create properties
           $administratorProperties = @{
           "Administrators" = $admin
           "Local Admin type" = "Domain users"
           "Machine name" = $server
            # check if local admin is enabled or not in AD
           Label ="User Enabled" ; expression = {(Get-AdUser -Filter "SamAccountName -eq '$userName'").Enabled}  

           }
           $adm += New-Object psobject -Property $administratorProperties
        }

         $adm | Select "Machine Name", "Administrators", "Local Admin type", "User Enabled" | Export-CSV "C:\Temp\LOcalAdmins.CSV" –NoTypeInformation
           

 }
 catch [Exception]
{
    if ($_.Exception.GetType().Name -like "*COMException*") {
         Write-Verbose -Message ('{0} is unreachable' -f $server) -Verbose
    }
    else{
         Write-Warning $Error[0]
    }
 }
} 
  

Machine name     : MACHINE
Administrators   : DOMAIN\User1
Label            : User Enabled
Local Admin type : Domain users
expression       : (Get-AdUser -Filter "SamAccountName -eq '$userName'").Enabled

Is it possible to check if user in $username variable is enabled or not.

Upvotes: 0

Views: 280

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174920

Property expressions are for calculating a property value dynamically - you don't need that since you're constructing the object with all its property values known up front, so all you need to do is assign the property value to the relevant key in the hashtable as-is:

    $administratorProperties = @{
        "Administrators" = $admin
        "Local Admin type" = "Domain users"
        "Machine name" = $server
        # check if local admin is enabled or not in AD
        "User Enabled" = (Get-AdUser -Filter "SamAccountName -eq '$userName'").Enabled
    }
    $adm += New-Object psobject -Property $administratorProperties

Upvotes: 1

Related Questions