Andrew Waters
Andrew Waters

Reputation: 51

Powershell : You cannot call a method on a null-valued expression

Currently in the process of building a script that gathers guests from AzureAD and gives us a breakdown of how many days since the last login.

When i run the [int]**** line solo it works fine, however when I run within the ForEach i get teh error

At line:8 char:5
+     [int]$LogonAge = [math]::Round(($Today - ($LastLogon.CreatedDateT ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The script is below:

$Users = Get-AzureADUser | Where-Object {$_.UserType -eq 'Guest' -and $_.AccountEnabled -eq 'True' } | Select AccountEnabled,DisplayName,ObjectID,UserType
$Today = Get-Date
$DaysOld = 30

    ForEach ($User in $Users) {
    $ObjectID = $User.ObjectId
    $LastLogon = Get-AzureADAuditSignInLogs -Top 1 -Filter "UserID eq '$ObjectID'" | select CreatedDateTime 
    [int]$LogonAge = [math]::Round(($Today - ($LastLogon.CreatedDateTime).ToDateTime($null)).TotalDays)
            if ($LogonAge -gt 30) {
            Set-AzureADUser -ObjectID $user.ObjectID -AccountEnabled $true
}
}

Any idea what im doing wrong?

Upvotes: 1

Views: 576

Answers (1)

Venkataraman R
Venkataraman R

Reputation: 12969

You can check for nullability and then operate.


$Users = Get-AzureADUser | Where-Object {$_.UserType -eq 'Guest' -and $_.AccountEnabled -eq 'True' } | Select AccountEnabled,DisplayName,ObjectID,UserType
$Today = Get-Date
$DaysOld = 30

    ForEach ($User in $Users) {
    $ObjectID = $User.ObjectId
    $LastLogon = Get-AzureADAuditSignInLogs -Top 1 -Filter "UserID eq '$ObjectID'" | select CreatedDateTime 
    if( $LastLogon -ne $null) # check for nullability 
    {
    [int]$LogonAge = [math]::Round(($Today - ($LastLogon.CreatedDateTime).ToDateTime($null)).TotalDays)
            if ($LogonAge -gt 30) {
            Set-AzureADUser -ObjectID $user.ObjectID -AccountEnabled $true
     }
  }
}

Upvotes: 0

Related Questions