Getting Scheduled Tasks Between Specific Times On Windows 10 Desktop - windows

I'm having some troubles using the PowerShell in windows 10 in order to get specific scheduled tasks. I need to get a list of scheduled task that run between 9:00 PM to 12 PM. I couldn’t figure out how to use the “Get-ScheduledTask “ and “Get-ScheduledTaskInfo” commands properly.
I will be so grateful if someone can help me writing the script the right way!

I think this is what you need:
Get-ScheduledTask | ForEach-Object {
$NextRunTimeHour = ($_ | Get-ScheduledTaskInfo).NextRunTime.Hour
If ($NextRunTimeHour -in 21..23) { $_ }
}
Gets the Scheduled Tasks, then iterates through them with ForEach-Object, piping each to Get-ScheduledTaskInfo to get the .NextRunTime property and it's .Hour subproperty and then returning the Scheduled task if the hour is 21, 22 or 23.

Other method, give you all necessary infos :
Get-ScheduledTask| %{$taskName=$_.TaskName; $_.Triggers |
where {$_ -ne $null -and $_.Enabled -eq $true -and $_.StartBoundary -ne $null -and ([System.DateTime]$_.StartBoundary).Hour -in 21..23} | %{
[pscustomobject]#{
Name=$taskName;
trigger=$_
Enabled=$_.Enabled
EndBoundary=$_.EndBoundary
ExecutionTimeLimit=$_.ExecutionTimeLimit
Id=$_.Id
Repetition=$_.Repetition
StartBoundary=$_.StartBoundary
DaysInterval=$_.DaysInterval
RandomDelay=$_.RandomDelay
PSComputerName=$_.PSComputerName
}
}
}

Related

Kill the process if start time is less than 2 hours

I need to kill the process if start time is less than 2 hours.
I have written the below cmdlet to find out the starttime but how to find out if is it less than 2 hours:
get-process process1 | select starttime
There is also a possibility that on some hosts process1 is not running. so I need to check first if the process1 is running
You can use a loop of your choice, in this example ForEach-Object in addition to an if condition to check if the StartTime value is lower than 2 hours.
If you need to check first is the process is running then you would need to get all processes and filter by the process name you're looking for. Then check if the returned value from Where-Object is $null or not.
$procName = 'myprocess'
$process = Get-Process | Where-Object Name -EQ $procName
if(-not $process) {
Write-Warning "$procName not found!"
}
else {
$process | ForEach-Object {
if($_.StartTime -lt [datetime]::Now.AddHours(-2)) {
try {
'Attempting to stop {0}' -f $_.Name
Stop-Process $_ -Force
'{0} successfully stopped.' -f $_.Name
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}

Running PowerShell Command Directly On CMD Gives Index Was Out Of Range Error

The command below is designed to list expired user accounts:
powershell -c "Get-LocalUser | Where-Object { $_.AccountExpires -le (Get-Date) -and $null -ne $_.AccountExpires } | Select-Object Name, AccountExpires"
Running directly on PowerShell seems to run fine, however, when I run the same command via CMD, it gives the error below:
Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index').
I believe the issue is related to the $null parameter but I need this to exclude blank matches from the output. Does anyone know a way of fixing this error? Or an alternative method to no match blank output?
You should make things clear when using operators:
powershell -c "Get-LocalUser | Where-Object { ($_.AccountExpires -le (Get-Date)) -and ($null -ne $_.AccountExpires) } | Select-Object Name, AccountExpires"
This works fine for me
It might not be $null, try an empty string instead:
("" -ne $_.AccountExpires)

Powershell: How do I continue running script after never-ending script line?

I have a line in my script that downloads a large video file. After the download starts I want to already open the file while is it downloading. The problem is, is that the download command hasn't finished yet so the script stays stuck on the same line.
(Download-File command)
$allFiles = Get-ChildItem | Select-Object -Property name,LastAccessTime | measure-object -Property LastAccessTime -Maximum
$videoFile = Get-ChildItem | Where-Object { $_.LastAccessTime -eq $allFiles.Maximum}
Start-Process $videoFile
(I want this to run in a loop while the download-file command is running)
That should be easy. All you need to do is make it run on a different thread. Use background jobs or Runspaces. Below example is Background Job.
$ScriptBlock = {(Download-File command)}
Start-Job -ScriptBlock $ScriptBlock
do
{
$allFiles = Get-ChildItem | Select-Object -Property name,LastAccessTime | measure-object -Property LastAccessTime -Maximum
$videoFile = Get-ChildItem | Where-Object { $_.LastAccessTime -eq $allFiles.Maximum}
Start-Process $videoFile
}
while (1 -gt 0)
Although, I am not sure if you would want to open the video file in a loop. If it does support opening an incomplete video file, you will have just as many instances of it. Better enclose it in an if (!(Get-Process -name $VideoFile)){} loop to prevent that.
Use the .waitforexit method.
Example:
$proc = Start-Process cmd.exe -PassThru
$proc.WaitForExit()
After the $proc.WaitForExit() line you can open your file.
Its look much better than a loop

Strange result from powershell script when executing via scheduled task

I'm running a powershell script, that when run from the ISE outputs one set of values but when the same task is run through task scheduler it seems to add a second value that doesn't display when run manually. The code that's being executed is as below:
import-module WebAdministration
$app_pool_name = <<app_pool_name_goes_here>>
$memused = ""
$cpuused = ""
$datetime = get-date -format s
$memused = Get-WmiObject Win32_process | where CommandLine -Match "$app_pool_name"
$id = dir IIS:\AppPools\$app_pool_name\WorkerProcesses\ | Select-Object -expand processId
$cpuUsed = Get-WmiObject Win32_PerfFormattedData_PerfProc_Process | where IDProcess -Match $id
Add-Content -path C:\Winsys\PSOutput\$app_pool_name-CPU-RAM_test.txt -value "$datetime,$($memUsed.workingsetsize),$($cpuUsed.PercentProcessorTime)"
When running the script manually the output returned is:
Date,Mem,CPU
2016-08-02T14:09:36,15062687744,0
2016-08-02T14:09:38,15062425600,0
When running the script through task scheduler the output returned is:
Date,Mem,CPU
2016-08-02T13:58:25,15065047040 624189440,0
2016-08-02T14:05:01,15061901312 624713728,0
The difference being the Mem, for some reason it's adding an extra value. Does anyone know why this is?
Turns out this was my own error, there are two app pools with very similar names, the -match was catching both. But it still didn't explain why it was only showing both in task scheduler and not ISE. Ah well, resolved now by adding a -and -notmatch "text" section.
E.g.
Get-WmiObject Win32_process | where {$_.CommandLine -Match "$app_pool_name" -and $_.CommandLine -notmatch "<<text in other command line>>"}
Add Comment

Powershell, How to get date of last Windows update install or at least checked for an update?

I am trying to find a way of retrieving the date/time of which the last windows update was either installed, or checked for.
So far I have found a function that allows to list recent Windows Updates, but it is far too much data and too bloated for such a simple function. Secondly I have tried to access the registry although I am having no luck in retriving the value I am after.
I am testing this on a Windows 10 Machine although the software will probably reside on Windows Server 2012 R2.
Here is an example of some of the code I have tried:
$key = “SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install”
$keytype = [Microsoft.Win32.RegistryHive]::LocalMachine
$RemoteBase = [Microsoft.Win32.RegistryKey]::OpenBaseKey($keytype,"My Machine")
$regKey = $RemoteBase.OpenSubKey($key)
$KeyValue = $regkey.GetValue(”LastSuccessTime”)
$System = (Get-Date -Format "yyyy-MM-dd hh:mm:ss")
Also, just trying the Get-ChildItem
$hello = Get-ChildItem -Path “hkcu:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\”
foreach ($a in $hello) {
$a
}
I've checked in regedit and this key does not exist. Going to the "Windows Update" path shows only App Updates and not Windows updates.
EDIT
I seem to be closer to my goal with this line:
Get-HotFix | Where {$_.InstallDate -gt 30}
However how to I only retrive those of which have been installed in the last 30 days? And this doesnt show many results, even using Select $_.InstallDate
an option :
gwmi win32_quickfixengineering |sort installedon -desc
Another alternative, using the com object Microsoft.Update.Session can be find here : https://p0w3rsh3ll.wordpress.com/2012/10/25/getting-windows-updates-installation-history/
in short :
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
$HistoryCount = $Searcher.GetTotalHistoryCount()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa386532%28v=vs.85%29.aspx
$Searcher.QueryHistory(0,$HistoryCount) | ForEach-Object {$_}
Here you have how to know the date and time of the last Windows update in a single line of Powershell:
(New-Object -com "Microsoft.Update.AutoUpdate"). Results | fl
You also have the following script to check it massively in Windows Server:
$ servers = Get-ADComputer -Filter {(OperatingSystem-like "* windows * server *") -and (Enabled -eq "True")} -Properties OperatingSystem | Sort Name | select -Unique Name
foreach ($ server in $ servers) {
write-host $ server.Name
Invoke-Command -ComputerName $ server.Name -ScriptBlock {
(New-Object -com "Microsoft.Update.AutoUpdate"). Results}
}
Extracted from: https://www.sysadmit.com/2019/03/windows-update-ver-fecha-powershell.html
Get-HotFix |?{$_.InstalledOn -gt ((Get-Date).AddDays(-30))}
Using PowerShell, you can get the date of the las Windows update like this:
$lastWindowsUpdate = (Get-Hotfix | Sort-Object -Property InstalledOn -Descending | Select-Object -First 1).InstalledOn

Resources