GetScheduledTaskInfo NextRunTime is wrong - windows

I'm trying to use Powershell to get the NextRunTime for some scheduled tasks. I'm retrieving the values but they don't match up to what I'm seeing in the Task Scheduler Management Console.
For example, in the Task Scheduler console my "TestTask" has a Next Run Time value of "1/9/2018 12:52:30 PM". But when I do the following call in Powershell it shows "12:52:52 PM" for the NextRunTime.
Get-ScheduledTask -TaskName "TestTask" | Get-ScheduledTaskInfo
From what I've seen the seconds value is always the same value as the minutes when returned from the PowerShell Get-ScheduledTaskInfo cmdlet. I'm wondering if there's a time formatting error (hh:mm:mm instead of hh:mm:ss) in that cmdlet but I have no idea how to look for that.
The task is running at the exact time shown in the console so that makes me think that it's an issue with the powershell call.
Has anyone seen this issue before and know how to get the correct NextRunTime value in PowerShell? I'm also seeing the same issue with the LastRunTime value.
I've tried this on Windows Server 2016 and Windows 10 and get the same results on both operating systems.

I can confirm that I see the same issue on Server 2012R2 as well. You can get the correct information by using the task scheduler COM object, getting the root folder (or whatever folder your task is stored in, but most likely its in the root folder), and then getting the task info from that. Here's how you'd do it:
$Scheduler = New-Object -ComObject Schedule.Service
$Scheduler.Connect()
$RootFolder = $Scheduler.GetFolder("\")
$Task = $RootFolder.GetTask("TestTask")
$Task.NextRunTime
Probably also worth noting that you can use the Connect() method to connect to the task scheduler on other computers (if you have rights to access their task scheduler), and get information about their tasks, stop or start their tasks, make new tasks... lots of good stuff here if you don't mind not using the *-ScheduledTask* cmdlets.

Related

How to use PowerShell to run some code upon system shutdown?

I'm provisioning a Windows VM that needs to run some PowerShell code when it boots. It also needs to run some different code when it shuts down.
To do the former, I can use New-JobTrigger and Register-ScheduledJob in my initial provisioning script like so:
$StartupTrigger = New-JobTrigger -AtStartup
Register-ScheduledJob -Name "Startup Job" -Trigger $StartupTrigger -Credential $DesiredCredentials -ScriptBlock {
Do-InterestingThings $using:ExternalResource
}
Doesn't even have to be a separate script file, it can just be a script block. Any variables from an outer scope will be serialized and used when the job runs. Pretty neat.
The real problem I'm solving involves creating an external resource whose lifetime is tied to the VM's uptime. When the VM is created, this resource will be created. When the VM is shut down, this resource needs to be cleaned up. How can I use PowerShell to run some code just before the VM is scheduled to shut down (regardless of how it got the order)? It doesn't need to be a script block, it can be a separate script file.
There are two reasonable ways to do this:
Local Group Policy:
This can be done in the local group policy editor: gpedit.msc. Navigate to Computer Configuration/Windows Settings/Scripts (Startup/Shutdown)/Shutdown. You can add 'Scripts' and/or 'PowerShell Scripts' here which get executed before other shutdown processes.
Event-Based Scheduled Task:
From this answer:
scheduled task as follows:
Type : On Event (Basic)
Log : System
Source : User32
EventID : 1074
When a user or command initiates a shutdown or restart as a logged on
user or on a user's behalf, event ID 1074 will fire. By creating a
task to use this to trigger a script, it will start the script and
allow it to finish
Note that this does not delay the shutdown (so has to be quick) and can sometimes fail to trigger before the task scheduler service stops.
Final Note:
Always make sure that your code can handle a dirty shutdown. After all, the fastest way to call a reboot is the power button...

What can I query to see if Windows is booted and done with updates?

My goal is to remotely check a group of computers (extensive list) not only to see if the server has rebooted (usually when it was last rebooting), but if Windows is fully up and running at the login screen, and it won't restart for further updates or still be installing updates.
I did find a service called AppReadiness, which stopped it until the server rebooted. I am concerned that if it is set to manual, it may not always start. Could somebody please confirm if this is a reliable service?
EDIT: As I'm writing this, I did find out that it was stopped until it says "Working on updates, 100% complete, Don't turn off your computer" but as the server hung on that message, the AppReadiness service started. Is there anything better to watch? I've read other answers on different questions say to check if C$ is available, but that is available sooner than AppReadiness is available.
The code that is being used to check the service:
$creds = Get-Credential -Message "Enter server credentials:" -UserName "SERVERNAME\Administrator"
Get-WmiObject Win32_Service -ComputerName "SERVERIPADDRESS" -Credential $creds | Where-Object {$_.Name -eq "AppReadiness"}
EDIT 2: Also, instead of monitoring services, I have also tried looking for processes like winlogon.exe and loginui.exe for guidance on the server's condition but I'm not receiving the results I'm looking to record. These processes show when the server is getting ready when I was hoping they would only show once the login GUI was visible.
EDIT 3:
This edit is for the answer by #Kelv.Gonzales who stated to check for the Windows Event Log "DHCPv4 client service is started" log entry. That doesn't work and is on par with other services and events that I monitored. It shows valid before the login screen.
My code was:
$creds = Get-Credential -Message "Enter server credentials:" -UserName "SERVERNAME\Administrator"
$server = "IPADDRESSOFSERVER"
while($true)
{
$event = Get-WmiObject Win32_NTLogEvent -ComputerName $server -Credential $creds -Filter "(logfile='System' AND eventcode = '50036')" | select -First 1
$event.ConvertToDateTime($event.TimeWritten)
Start-Sleep -Seconds 5
}
That one liner will just fire off once of course. Any reason why you are using WMI, instead of the built-in PowerShell cmdlet - Get-Service?
My suggestion is use an WMI Event watcher, using what you already have in place but target the service and any dependent services and have that event notify you when the state is running.
Use PowerShell to Monitor and Respond to Events on Your Server
This article is using PowerShell and VBScript to do this, but you can do this with all PowerShell.
You can have a temporary or permanent watcher.
PowerShell and Events: WMI Temporary Event Subscriptions
Those can get a bit deep, so, if they aren't for you, you can just use your one line in a Do Loop that stops after the service comes online.
Basic example:
$TargetHost = $env:COMPUTERNAME
do {
$TargetOperation = Get-WmiObject Win32_Service -ComputerName $TargetHost |
Where-Object {$_.Name -eq "AppReadiness"}
"Checking host $TargetHost for service/process $($TargetOperation.Name)"
Start-Sleep -Seconds 3
} until (($TargetOperation).State -eq 'Running')
"Validation of host $TargetHost for service/process $($TargetOperation.Name) complete"
# Results
Checking host WS70 for service/process AppReadiness
Checking host WS70 for service/process AppReadiness
Checking host WS70 for service/process AppReadiness
Validation of host WS70 for service/process AppReadiness complete
You can of course add as many services or processes as you'd like using operation logic.
All the above applies to almost whatever you'd like to watch. Services, process, file-folder.
Or just use this script in the loop.
Get Remote Logon Status - Powershell
This script will return the logon status of the local or a remote
machine. Return types include "Not logged on", "Locked", "Logged
on", and "Offline.
The most useful part of this is to check whether a computer is in the
locked state, although the other return types could also be useful.
This is a simple function, and can easily be included in a larger
script. The return types could be changed to numbers for the calling
script to more easily parse the return value.
Download: GetRemoteLogonStatus.ps1
Would finding 0 updates queued accomplish what you need then? This arcticle goes into detail on how to accomplish it.
To check if windows is ready to log in, can you query for the event log for 'DHCPv4 client service is started' - Event ID 50036 satisfy if windows is ready.
I spent a week searching for a solution for this issue. I wanted to share what is currently my best solution, hopefully it helps someone.
#kelv-gonzales pointed me in the right direction with his comment about the Windows Modules Installer and TrustedInstaller.
Breakdown of my solution
There exists a process called TiWorker.exe that is the Windows Modules Installer Worker process. This is the process responsible for actually installing the Windows Update. This process (from what I've observed) reliably runs throughout the duration of a Windows Update being installed. Once the update has been installed and a pending reboot is required, this process stops and goes away.
When you reboot the machine to satisfy the pending reboot, the TiWorker.exe process is one of the very first processes to start while the machine is coming back up. In some cases, depending on the nature of the update, will finish the installation of an update (that's the increasing percentage you see during boot-up) while the computer comes back up. Once the login screen is available, this process typically remains running four roughly 2 minutes (from what I've observed). After which, it stops and goes away. I found that waiting these few minutes was a small price to pay for reliably knowing when updates have finished processing.
My scripts logic
I was able to write a script that keys off of the existence of this service. For example, below is a high-level flow of my script.
Initiate the installation of Windows Updates.
Wait for updates to finishing installing and for a pending reboot.
Once a pending reboot exists, wait until TiWorker.exe is no longer running and then trigger a reboot.
While the machine is rebooting, repeatedly check the status of the machine during the reboot. While the machine is coming back up, TiWorker.exe will start back up to finish the update. Keep waiting until TiWorker.exe is no longer running (typically, the update will finish and the OS will wait at the lock screen for about 2 minutes before this process stops).
Code
I modified the code posted by #gabriel-graves to check for the TiWorker.exe process.
$creds = Get-Credential -Message "Enter server credentials:" -UserName "SERVERNAME\Administrator"
Get-WmiObject Win32_Process -ComputerName "SERVERIPADDRESS" -Credential $creds | Where-Object {$_.Name -eq "TiWorker.exe"}

Discrepancy in timezone between timestamps for lastlogon using WMI commands

I'm trying to get the user's last logon in some Windows machines using WMI, but for some reason, this information is different for different commands when I think they should be the same.
The first command that I'm using is : PATH Win32_NetworkLoginProfile WHERE "Name='DOMAIN\\fakeuser'" GET LastLogon. The result for it is like below:
LastLogon
20181206093540.000000-480
The second command is: PATH Win32_NTLogEvent WHERE "(EventIdentifier =4648 OR EventIdentifier = 4647 OR EventIdentifier = 4634)" GET CategoryString, TimeGenerated, InsertionStrings
The result is like below (after some processing to find the last entry of category "Logon" linked to the "fakeuser", since the command returns a lot of information):
CategoryString
Logon
InsertionStrings
{"S-1-5-21-3457937927-2839227994-823803824-1104","DOMAIN$","DOMAIN","0x3e6","{00000000-0000-0000-0000-000000000000}","fakeuser","DOMAIN","{00000000-0000-0000-0000-000000000000}","localhost","localhost","0x64c","C:\Windows\System32\svchost.exe","999.999.99.999","0"}
TimeGenerated
20181206173540.580545-000
For what I understand for these two commands, the LastLogon in the first result should be the same of TimeGenerated in the second one. Am I misunderstood something?
In my preliminary research, I found a possible bug in the WMI Timestamps, but I don't know if it is the same problem.
Some additional information:
These commands are executed using a script that make a remote connection using WinRM connection (ports 5985 and 5986) and then executes the commands to get the info, but I also tried to connect in the machine using RDP and execute it in Powershell with wmic PATH.... The result is the same.
I tested it in Windows 10 and also in Windows Server 2012, but the scripted will be used in some other Windows versions.
To get the Event numbers for the log class, I used this link
After first comment, I noticed that the problem is in time zones. Are there any way to set timezone direct in these commands or convert timezones between them?

Powershell Remoting performance

I am managing a lab for a technology conference, and I have a PowerShell script that does some cleanup between sessions, deleting leftover cruft from the desktop, resetting links in the Taskbar, etc. When I run this script "locally", meaning I use a shortcut while logged in as the generic lab user, it takes about 5 seconds to complete. However, when I run the same script using Remoting it takes nearly 10 minutes to complete. And this on a single machine. My worry is that I have 40 machines that need to refresh, and sometimes only 15 minutes total between sessions. The code I am testing with is pretty simple
Invoke-Command -computerName:$machine -argumentList: $file, $context –scriptblock {
param (
[String]$file,
[string]$context
)
& powershell.exe -noProfile -noLogo -executionPolicy bypass -file $file -context:$context
} -credential:$credential -authentication:CredSSP –asJob -jobName:$machine > $null
So, my question is, is this "normal", or is there some indication of a problem and I should really expect this to work at something closer to "local" speeds? FWIW, I am testing this on a VM.
Additionally, I am using a BallonTip to alert anyone who is sitting at the machine that a reset is happening. This works great when "manually" launching the script. However, when using Remoting the Ballon Tip never shows up. Of course neither does the console, so perhaps this is just a limitation of Remoting, that no UI can be triggered?
Any insights greatly appreciated. Thanks!
You won't be able to get a UI to show up like that since the script won't be running in the interactive user's session.
As for performance, I'm not entirely sure why would it take such a drastically longer time.
First, I would say try to remote into your local machine (instead of just running it locally), by passing either localhost, ., or the actual local computer name to the -ComputerName parameter of Invoke-Command. See if the performance is still as bad, or how it differs.
I'm also wondering if it has to do with spawning another powershell.exe process on the remote side. In theory it shouldn't, but what if you do this instead:
Invoke-Command -computerName:$machine -argumentList: $file, $context –scriptblock {
param (
[String]$file,
[string]$context
)
$sb = [ScriptBlock]::Create((Get-Content $file -Raw))
& $sb -context:$context
} -credential:$credential -authentication:CredSSP –asJob -jobName:$machine > $null

Check if a scheduled task is running using vbscript

Is it possible to determine if a scheduled task is running on a local or remote machine using vbscript?
There's a WMI class called Win32_ScheduledJob that has some status fields that might be useful. Especially the ElapsedTime field looks like it might be what you're looking for, assuming that it gets reset when the task stops.
Here's some sample code for looking at the statuses. Just set strComputer to the name of the computer you want to look at (. means the local computer).
Otherwise, if that doesn't work, you might be able to just look at the Schedlgu.txt file in the Windows directory and see if it's started but not yet stopped.
You might be able to get this information with the command-line command schtasks /query... but you'd probably have to grep the output to find only the jobs with a status of "Running".
Details on usage can be found here.

Resources