I have got a need to check ISS Service status whether running or stopped. So I am using
Get-Service AppHostSVC,FTPSVC,IISAdmin,MSFTPSVC,W3SVC,WAS,WMSVC
I need to run this for command for every 5 minutes, so I am using this script
Import-Module TaskScheduler $task = New-Task
$task.Settings.Hidden = $true
Add-TaskAction -Task $task -Path C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe –Arguments “Get-Service AppHostSVC,FTPSVC,IISAdmin,MSFTPSVC,W3SVC,WAS,WMSVC”
Add-TaskTrigger -Task $task -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)
Register-ScheduledJob –Name ”Monitor IIS Service” -Task $task
I need to show the status of those services as a Web page in c:\IISServiceChecker.html which will be refreshed every 5 minutes. This part I am struggling on how to put the status in a web page. Any help would be much appreciated
Thank you
Related
I have a script which launches an app on the VM and logs some data for the app. As Powershell script does not allow me to run the app in foreground I decided to schedule a task after 2 mins and then keep polling for the task completion.
I was using this command to register my task
$password= "password" | ConvertTo-SecureString -asPlainText -Force;
$username = "name";
$credential = New-Object System.Management.Automation.PSCredential($username,$password);
Invoke-Command -VMName INSTANCE_ID -Credential $credential -ScriptBlock
{
$gettime = (Get-Date).AddMinutes(2);
$run = $gettime.ToString('HH:mm');
$action = New-ScheduledTaskAction -Execute 'C:\logging.bat';
$trigger = New-ScheduledTaskTrigger -Once -At $run;
$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -RunLevel Highest;
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName "ID_Logging_Task" -Description "my description"
}
It was working fine but it had a problem that it ran well only when the user was logged in. More context - https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskprincipal?view=windowsserver2022-ps (Example 2)
So I looked at the documentation of Register-ScheduledTask and saw that I can provide username and password to the command while registering the task. So I took the username of the account with Administrator privileges and ran the new command:
$password= "password" | ConvertTo-SecureString -asPlainText -Force;
$username = "name";
$credential = New-Object System.Management.Automation.PSCredential($username,$password);
Invoke-Command -VMName INSTANCE_ID -Credential $credential -ScriptBlock
{
$gettime = (Get-Date).AddMinutes(2);
$run = $gettime.ToString('HH:mm');
$action = New-ScheduledTaskAction -Execute 'C:\logging.bat';
$trigger = New-ScheduledTaskTrigger -Once -At $run;
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ID_Logging_Task" -RunLevel Highest -User "myUser" -Password "myPassword" -Description "my description"
}
"myUser" is an administrator on this machine. This solved the problem of running the task without manually logging in but now my app is getting launched in the background instead of foreground which was the whole point of running these scheduled tasks.
My question is what is the difference between BUILTIN\Administrators and an Administrator account. And how do I solve my problem? I want to run my task with the privilege of -GroupID "BUILTIN\Administrators" without actually logging into the machine.
Difference between the group and account
BuiltIn\Administrators is a group you can be a member of.
Administrator is a default account that comes, normally disabled, on new Windows installations.
There is a way of fixing this problem, maybe easier than it seems.
Achieving what you want
I have a script which launches an app on the VM and logs some data for the app
Let's break doing this into three pieces
Launching the VM
If you want your VM to always be running, you can set it to 'Always Start'. This option is great because it will start the VM with the host, and you can even specify a startup delay, which is great because this lessens the pressure on disk and cpu, as starting a vm will incur a spike to both those resources.
If you do this, this takes care of starting the VM.
Launching the app
For the next piece this is as simple as the syntax you already have for running a scheduled task. If you want to run as a domain account and run as an administrator, just make the domain account a member of the 'Administrators' group on the system.
Running in Foreground
Here is the wrinkle, but I don't understand why this is an issue. Scheduled Tasks will only run in the Foreground when a user is logged into the machine.
This option is there so that you can make an app appear in the user's session when they log onto a computer, for things like Kiosk apps, or Point-Of-sale systems, dashboard displays and that sort of thing.
If you set an app to run whether or not a user is logged in, then it always will run in the background.
Are you sure this matters?
Making an app run in the foreground on boot
If you want an app to run without having to login, it will run in the background.
If you really want it to run in the foreground, then just set the machine to automatically log in. If it automatically log's in, then it will login and show the desktop, and then the scheduled task can be changed to 'Run only when a user is logged in', which will make it run in the foreground.
But why would someone need an App within a VM, which is by nature headless to run in the foreground?
I'm at my wits end trying to get a scheduled task to persist after a Windows Server 2019 reboot. I'm using powershell to create the scheduled task.
It triggers just fine and I can see it running before the reboot. Then the Server adds the ADDS component and Forest and reboots. After the reboot, no matter what I try, I can't get the scheduled task to start properly again.
Note that this exact code below works just fine on Windows 10 for adding a scheduled task to restart itself after a reboot. Any help appreciated. Are there some settings that need to be here for Windows Server that differ for Win10?
Here is the error description: After the reboot, in the task summary, it says "The last run of the task was terminated by the user" with last run time right before the reboot. The next run time keeps on incrementing every minute. In the History the error is, "Task Scheduler Failed to Start" with "Additional Data: Error Value: 2147943726."
# Create a scheduled task action
$sta = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "C:\Terraform\ImportUsers.ps1"'
# Create a schedule task trigger
$stt = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 1)
# Create a new scheduled task setting
$sts = New-ScheduledTaskSettingsSet -StartWhenAvailable -RestartInterval (New-TimeSpan -Minutes 1) -RestartCount 3
# Set it to Stop the existing instance (for proper startup after reboot)
$sts.CimInstanceProperties.Item('MultipleInstances').Value = 3
# Register new scheduled task
Register-ScheduledTask ImportDomainUser01 -Action $sta -Settings $sts -Trigger $stt -User "LocalAdmin" -Password "LocalAdminPassword"
I was able to get this working using powershell scheduled jobs instead of a traditional scheduled task. This solution below persists across a reboot on Windows Server 2019:
$jt = New-JobTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-Timespan -Hours 48)
Register-ScheduledJob -Name ImportUsers01 -ScriptBlock { C:\script.ps1 } -Trigger $jt
I created a new service in Powershell (as administrator) PSVersion 5.1.17763.1007. The new service exists, but fails to run in either Powershell or Services.
In Powershell:
PS C:\Windows\system32> Get-Service ztest|Start-Service
Start-Service : Service 'ztest (zTest)' cannot be started due to the
following error: Cannot start service zTest on computer '.'. At
line:1 char:19
+ Get-Service ztest|Start-Service
\ ~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController)
[Start-Service], ServiceCommandException + FullyQualifiedErrorId
:
CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
In Services:
I receive a 1053 error The service did not respond to the start or control request in a timely fashion.
What Has Been Done:
I used a powershell script that I have converted to a .exe file via Win-PS2Exe. When I run the .exe file, the program works as expected.
Creating New Service:
New-Service -Name zTest1 -BinaryPathName $filepath -DisplayName zTest1 -Description $description -StartupType Automatic -Credential $cred
I have changed Timeout settings in Regedit, added both files and folders to trusted locations, granted ownership and full access to the service account for .exe files and folders, I have written PS Scripts and converted it to a .exe (Win-PS2Exe) powershell.exe -executionpolicy bypass -file 'C:\users\...\desktop\RunTESTNoCommentsReview.exe'
About the .exe file:
The .exe file does not end. It is in an infinite while loop pausing 1 minute at a time.
I have read people saying potential issues with the name not being what it is expected to be in Windows Service Manager, but I couldn't find any additional documentation past their comments.
My Machine:
I am currently running Windows Server 2019 Standard that is up to date.
I am unsure if I am supposed to register the service somewhere, or what else I could be missing.
Continuing from my comment.
You are not showing any of your code that you say is being used as your service.
There are many examples of how to do this all over the web.
For Example:
$serviceName = "MyService"
if (Get-Service $serviceName -ErrorAction SilentlyContinue)
{
$serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name='$serviceName'"
$serviceToRemove.delete()
"service removed"
}
else
{
"service does not exists"
}
"installing service"
$secpasswd = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (".\MYUser", $secpasswd)
$binaryPath = "c:\servicebinaries\MyService.exe"
New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $mycreds
"installation completed"
So, without MRE stuff like the above, you force us to assume.
I'm automating builds of windows servers in AWS (via packer and terraform). I have a userdata script that changes the hostname when host is started and reboots after.
My problem is that, after the system reboots, I need a software installation to happen (because it relies on the changed name.)
I've tried something like this:
$RunOnceKey = "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
set-itemproperty $RunOnceKey "NextRun" ('C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -executionPolicy Unrestricted -File ' + "C:\mydir\after-boot\install_mysoftware.ps1")
The problem with this is that it only runs after a user login, which is unacceptable.
So I read about RunServiceOnce, but when I try to use that in place of RunOnce, I get an error:
set-itemproperty : Cannot find path 'C:\Users\Administrator\HKLM\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce'
because it does not exist
How can I ensure my program runs once on system boot without waiting for a user login? Point/click won't work. I need a powershell solution to set this up.
Since it is windows server, you can also schedule task in Windows Task Scheduler.
EXAMPLE:
$destination = "C:\Windows\Tasks\InstallSoftware.ps1"
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $destination
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName 'RemoveAppLogs' -TaskPath '\CustomTasks\' -Action $action -Trigger $trigger -Principal $principal -Description 'The task will run script to install software.' -ErrorAction Stop
I've registered a new startup job as follows
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
$option = New-ScheduledJobOption -RunElevated –ContinueIfGoingOnBattery
Register-ScheduledJob -Name startup_test -FilePath C:\startup.ps1 -Trigger $trigger -ScheduledJobOption $option
My startup.ps1 script is as follows
New-Item c:\test_startup_success.txt -type file
When I restart the windows server 2012 R2 core, it doesn't create the file. Have restarted using
shutdown /r
But if I use test it using, it created the file
Start-Job -DefinitionName startup_test
Is there anything that I'm missing which needs to be done specifically for startup jobs?
Update:
I executed the following command to see if the job failed, but the output was empty.
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational | Where {$_.Message -like "*fail*"}
My wild guess is that the job itself is not getting executed. Some condition is probably not getting satisfied. Even the Job trigger is enabled
PS C:\Windows\System32\WindowsPowerShell\v1.0> Get-ScheduledJob | Get-JobTrigger
Id Frequency Time DaysOfWeek Enabled
-- --------- ---- ---------- -------
1 AtStartup True