locked
If statement not working RRS feed

  • Question

  • Hi,

    Trying to get a script to rung through a CSV and if a condition is met, take an action. 

    CSV:

    "SAMAccountName","DaysSinceLastLogon"
    "NorteyJ","9"
    "PlavaL","90"
    "PleasantL","900"

    What I am trying to accomplish is to update the description of the user object if the "DaysSinceLastLogon" is greater than or equal to 90 days 

    Script:

    Import-Module ActiveDirectory
    
    $CSV_Export = "C:\temp\file.csv"
    $Description = "*Disabled due to 90 days inactivity"
    $DaysInactive = 90
    
    $Users = Import-Csv -Path $CSV_Export
    
    foreach ($User in $Users)
    {
        if($User.DaysSinceLastLogon -ge $DaysInactive)
        { 
            Set-ADUser -Identity $User.SAMAccountName -description $Description
        }
    }

    No matter what value I assign the $DaysInactive variable, it updates all users.  If I replace the variable in the IF statement with a value, the same thing happens. (EDIT: I thought this was different, but wasn't allowing for replication/changes to take effect; all users appear to update no matter what...) 

    Any ideas what I am doing wrong here?? 


    • Edited by Andy-Lee-1892 Monday, October 23, 2017 1:13 PM Mistake
    Monday, October 23, 2017 1:10 PM

Answers

  • You are trying to compare a string to a number.

    Switch the order:

     if($DaysInactive -gt $User.DaysSinceLastLogon)



    \_(ツ)_/

    • Marked as answer by Andy-Lee-1892 Monday, October 23, 2017 1:32 PM
    Monday, October 23, 2017 1:19 PM

All replies

  • You are trying to compare a string to a number.

    Switch the order:

     if($DaysInactive -gt $User.DaysSinceLastLogon)



    \_(ツ)_/

    • Marked as answer by Andy-Lee-1892 Monday, October 23, 2017 1:32 PM
    Monday, October 23, 2017 1:19 PM
  • Works!! But why?  I guess by having the integer first it expects an integer in the second part??   

    Thanks very much! 

    Monday, October 23, 2017 1:33 PM
  • That is called "precedence".  It is a fundamental concept in programming and tells us how things of different types will be managed.  With an expression the expression is evaluated from left to right.  Leftmost sets the type when comparing.  

    start here: help about_operator* and read all.


    \_(ツ)_/

    Monday, October 23, 2017 1:39 PM
  • Thanks very much :)
    Monday, October 23, 2017 1:48 PM