locked
Populating variable fails - INTERMITTENTLY! RRS feed

  • Question

  • I hate when computers act sporadically for no apparent reason.  It just means I'm not smart enough to find the reason.

    So... I have a script that requires I populate a variable with data from a Get-ADComputer statement.

    $OldADComputers = Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate | ? {$_.LastLogonDate -le $ValidationDate.DateTime}

    The query runs, but does not populate $OldADComputers.  It used to, but now, it does not.  I am in an administrative host ISE console, Powershell v5.  However, when I run it in plain old user context it runs fine.  Until it doesn't.  Because I am iterating through testing, I noticed the variable stop populating.  Now it is all I am focused on.

    One last thing.  I wanted to create a message to user while this query runs (takes about 49 seconds) so I am running it in a JOB and WHILE the job is RUNNING, it puts up a message to user.

    #  The "Job" below starts an AD Query outside the scope of this script so a Progress Bar can be called up for the user while the job is running.
    $Job = Start-Job -ScriptBlock {
      $OldADComputers = Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate | ? {$_.LastLogonDate -le $ValidationDate.DateTime}
      $OldADComputers.count | Export-csv "\\<Servername>\<path>\AD_Removal_Logs\MasterADRemovalLists\OldADComps$($Date).csv" -NoTypeInformation
      }
    while((get-job $Job.Id ).state -eq "Running"){
      Write-Progress -Activity "please wait while we search AD for Valid Computers..." 
    }
     Write-Progress -Activity "please wait while we search AD for Valid Computers..." -Completed
    

    Again, this all worked, then it didn't.  I have tried:

    • Saving script and re-opening.
    • Closing ISE and re-opening
    • Clearing out the variable
    • Changing variable name
    • Running command by itself without passing into variable (works just fine, always)
    • Opening ISE in non-administrative context.  (Works just fine) (Then it doesn't)
    • Re-running in Administrative context.  Not fine.  ACK!

    Thoughts?

    Tuesday, April 3, 2018 2:19 PM

Answers

  • This is how you have to get variables I to a job script.

    $sb = {
        Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate |
            Where{$_.LastLogonDate -le $args[0]} | 
            Export-csv "\\<Servername>\<path>\AD_Removal_Logs\MasterADRemovalLists\OldADComps$($args[1]).csv" -NoTypeInformation
    }
    $Job = Start-Job -ScriptBlock $sb -ArgumentList $ValidationDate.DateTime, $date

    Please read the documentation link I posted carefully to understand why your code cannot work.

    By separating out the script as a block it makes the code easier to format in a readable way and makes it easier to check the commands and parameters.

    Variables defined outside of a job cannot be directly used in a job.  A job runs in a separate instance of PowerShell.  If you do not believe me use task manager to see the number of PowerShell programs running when a job is active.


    \_(ツ)_/


    • Edited by jrv Tuesday, April 3, 2018 4:44 PM
    • Proposed as answer by jrv Tuesday, April 3, 2018 4:47 PM
    • Marked as answer by clenh20 Thursday, April 12, 2018 7:36 PM
    Tuesday, April 3, 2018 3:53 PM

All replies

  • Where is $validationdate.datetime coming from? running it without this returns results so I think you should check that variable.

    Learn PowerShell                     Script Requests

    -Remember to mark the correct response as the answer-

    Tuesday, April 3, 2018 2:45 PM
  • I.T,

    Thanks for the reply.

    Sorry, that variable is populated earlier in the script with a simple question to the engineer running the script.

    $NumberofDays = Read-Host "Enter a value for 'X' greater than 30 days (EX: 30, 60, 90, 120)"
    $ValidationDate = (Get-Date).AddDays(-$($NumberofDays))

    I have also tried running the command with an actual date in place of the $ValidationDate.DateTime in that query with the same combination of success/failure.  It works when just running the query, it fails to populate the variable.  Vexing.

    Tuesday, April 3, 2018 3:01 PM
  • Variables defined outside of a job script block are no available in the script block.  You must pas them as arguments.

    See: "help about_jobs"


    \_(ツ)_/

    Tuesday, April 3, 2018 3:12 PM
  • Hi Clenh,

    some bad news, after running the below code around 20-30 times using a combination of 30 and 60 days, I got the same results each time. I even restarted the ISE a few times and tried in a PowerShell console window.

    $NumberofDays = Read-Host "Enter a value for 'X' greater than 30 days (EX: 30, 60, 90, 120)"
    $ValidationDate = (Get-Date).AddDays(-$($NumberofDays))
    
    $OldADComputers = Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate | where {$_.lastlogondate -le (Get-Date) } | Out-GridView

    No luck for me when trying to replicate you issues, unfortunately. There may be an issue with your PowerShell or Windows install. Sorry I couldn't be more helpful :)


    Learn PowerShell                     Script Requests

    -Remember to mark the correct response as the answer-

    Tuesday, April 3, 2018 3:15 PM
  • Hi Clenh,

    some bad news, after running the below code around 20-30 times using a combination of 30 and 60 days, I got the same results each time. I even restarted the ISE a few times and tried in a PowerShell console window.

    $NumberofDays = Read-Host "Enter a value for 'X' greater than 30 days (EX: 30, 60, 90, 120)"
    $ValidationDate = (Get-Date).AddDays(-$($NumberofDays))
    
    $OldADComputers = Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate | where {$_.lastlogondate -le (Get-Date) } | Out-GridView

    No luck for me when trying to replicate you issues, unfortunately. There may be an issue with your PowerShell or Windows install. Sorry I couldn't be more helpful :)


    Learn PowerShell                     Script Requests

    -Remember to mark the correct response as the answer-

    The code I being run as a job.  The variable does not exist in the job script.


    \_(ツ)_/

    Tuesday, April 3, 2018 3:17 PM
  • jrv,

    I appreciate your input.  However, it doesn't fit my findings.  The Job is only working with variables $NumberofDays, $ValidationDate, and $OldADComputers.  I am then exporting $OldADComputers to a csv file for later use during a comparison.  I don't try to call $OldADComputers outside the context of the job during the balance of the running script.  

    Because my testing of the issue has been inconsistent and I can't reasonably expect anyone to be able to replicate my "failed" findings, I am going to withdraw the question.  For now, I will remove the job, create a second script altogether which does the AD query and outputs a log file. 

    Tuesday, April 3, 2018 3:41 PM
  • This is how you have to get variables I to a job script.

    $sb = {
        Get-ADComputer -filter "OperatingSystem -notlike '*Server*' -and OperatingSystem -notlike 'Mac*'" -Properties LastLogonDate |
            Where{$_.LastLogonDate -le $args[0]} | 
            Export-csv "\\<Servername>\<path>\AD_Removal_Logs\MasterADRemovalLists\OldADComps$($args[1]).csv" -NoTypeInformation
    }
    $Job = Start-Job -ScriptBlock $sb -ArgumentList $ValidationDate.DateTime, $date

    Please read the documentation link I posted carefully to understand why your code cannot work.

    By separating out the script as a block it makes the code easier to format in a readable way and makes it easier to check the commands and parameters.

    Variables defined outside of a job cannot be directly used in a job.  A job runs in a separate instance of PowerShell.  If you do not believe me use task manager to see the number of PowerShell programs running when a job is active.


    \_(ツ)_/


    • Edited by jrv Tuesday, April 3, 2018 4:44 PM
    • Proposed as answer by jrv Tuesday, April 3, 2018 4:47 PM
    • Marked as answer by clenh20 Thursday, April 12, 2018 7:36 PM
    Tuesday, April 3, 2018 3:53 PM