I found how to create and start a background process, how to add it to startup and so on. Quite simple.
The only step I need is how to increase the priority of the process I created at startup.
I saw that, from PowerShell, I can type:
$prog = Get-Process -Name backgroundTaskHost
$prog.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::High
and this works nice, I can check it running the command:
Get-Process | Format-Table -View priority
How to start the process with an higher priority? Is there any setting, command, or another method that allow to create at startup an higher priority background process?
There are 11 levels of the task. RealTime has the highest priority, its value is 0, is higher than High. You can start the process with an higher priority by running a PowerShell Script on Startup. You can follow these steps:
First, create a new file, name it StartupScript.ps1 and add the following lines of PowerShell code:
$prog = Get-Process -Name backgroundTaskHost
$prog.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::RealTime
Second, create a simple batch (*.bat) file that will execute the PowerShell script. Create a new file, name it “Startup.bat” and populate it with the following code:
powershell -command "C:\StartupScript.ps1"
Third, move the script and batch file to the IoT device. You can access IoT disk by File Explorer, enter following line in address bar(use your Raspberry Pi's name or IP address instead of here "minwinpc"):
\\minwinpc\C$
After that, you will see it like this picture shows:
Fourth, establish a PowerShell session with your IoT Core device and add the “C:\Windows\System32” folder permanently to your path by executing the following command:
setx PATH "%PATH%;C:\Windows\System32"
Add a startup scheduled task by executing the following command:
schtasks /create /tn "Startup PowerShell" /tr c:\Startup.bat /sc onstart /ru SYSTEM
Finally, reboot your device. When your device comes back online you can check the result by running the following command:
Get-Process | Format-Table -View priority
Related
I have a PowerShell script that can be started either by
running a shortcut on the desktop, OR
as a scheduled job from the windows Task Scheduler.
Is there any way within the script itself of identifying how it was started? In practice each method produces a slowly scrolling command window on screen, and once it's running I have no way of knowing how it was initiated. The script already logs some data about itself (name, date, time and $PID) but so far I've not found how to test the launch method i.e. task scheduler or manual run.
A script that is run by Task Scheduler has a parent process whose name is svchost, so you can use the following code in your script to detect this:
'svchost' -eq (Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessID = $pid").ParentProcessId).Name
I have windows 2012 server with LSI Megaraid controller. I am able to get raid status using below command in powershell and redirect output to a file.
C:\> MegaCli64.exe -LDInfo -Lall -aALL | Out-File raid.txt
However I tried to run same command using task scheduler and it is not working. I want to send the output of raid command or send raid.txt to a mail using task scheduler.
Some piece of advise for sceduled jobs :
1) Always set the working directory if you work with local files.
2) Always use the full path (not the relative one) for the programs you call and the files you manipulate. Do not expect the exe you call being in the paths pointed by $env:path.
3) Put your commands into a script file and make sure that a log (any type), with a time stamp, is composed each time your script is called.
4) Here is one way, but it exits multiples ways, to register your script in the scheduler :
# First set a Trigger
$SixInTheMorning = New-JobTrigger -Daily -At "06:00 AM"
# Second set your script
$scriptPath1 = 'C:\Batchs\WS_PowerShell\Myscript.PS1'
# Third register you job
Register-ScheduledJob -Name "AJobName" -FilePath $scriptPath1 -Trigger $scriptPath1
I am trying to have a power shell script resume after a reboot. (I am rebooting to "apply" registry changes I have made") I believe I can accomplish what I want by making a registry edit to the Run Once key. I have looked at this question, but I can't get my similar code to execute at boot. The registry edit is made and at boot something runs because it disappears but it is not finishing the install.
$part2 = Get-ChildItem C:\Windows\ccmcache\ -Recurse -Force -Filter Full_Druva_Reinstall_part2.ps1
$FullPath = $part2.FullName
$KeyPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
new-itemproperty -Path $KeyPath -Name !Install-Druva -propertytype String -value "Powershell -executionPolicy Unrestricted -File $FullPath"
Edit
This scrpit is inside a SCCM Package and any solution needs to automatic and require no user input.
Open task scheduler on general give a name> run wheter user logged in or not> trigger at startup>
action
program/script will be powershell.exe
arguments
-ExecutionPolicy Bypass -File "C:\myscripts.ps1"
I wasn't able to make the Run Once Registry work, plus it wouldn't tun with admin cred if a non admin logged in. I also wasn't able to make a schedule task in power shell because my environment is all Win7 and power shell v4.
The solution i used was making a task sequence in SCCM that ran part 1 of my script, restarted, and then ran part 2.
I need to run a powershell script whenever the server is rebooted/shutdown (whether graceful or disgraceful reboot).
The script will stop 4 application services at an interval of 1 minute and then finally reboots the system.(This is a business requirement, don't ask why)
How can I make server to invoke the .ps1 script whenever a reboot or a shutdown is initiated.
My test results:
I tried to create a test script which will generate a text file with current date/time and added it to the scheduled task on the trigger of event log 6006 (which is created whenever a system reboot/shutdown is initiated.)
I checked the box -"Run with highest privileges" but after system restart no text file was generated as it was supposed to, although it generates when ran manually.
Do we have any better approach to implement this?
(My final expectation should look like this-
On a random day a random user initiated reboot after a monthly patch when a command prompt window opens before him with message something like:
Stopping service abc...
Stopped.
Waiting for 60 seconds.
Stopping service xyz...
Stopped
EDIT: I've been successfully able to invoke the .ps1 file by adding it to the gpedit as suggested by Kory and Alroc but the script runs only in background when computer restart is initiated. It doesn't opens a regular cmd window to show the progress.
I'm adding the .ps1 script as well below which stops 2 services(chosen for testing purpose) at an interval of 10 seconds and will show the timer as well, only when ran manually.When invoked by the shutdown command it'll stop services only in the background without showing the progress to the user. Kindly assist to achieve this?
Write-Host "Shutdown script invoked"
stop-service W32Time -force -PassThru
for($i = 10 ; $i -gt 0 ; $i--)
{
Write-Progress -Activity "`n Waiting for" -status "`$i equals $i seconds"
sleep 1
}
stop-service wuauserv -force -PassThru
You can use GPO to configure a shutdown script for systems.
You might be able to to it via a Win32_ComputerShutdownEvent watcher as well.
After deep digging, I've finally figured out how to make the cmd window visible while system shutdown in progress.
Here is the complete steps of performing above mentioned expectation:
Open gpedit.msc
Navigate to Computer Configuration->Windows
Settings->Scripts(Startup/Shutdown)->Shutdown.
Go to Shutdown properties. In the powershell scripts tab add your
script and select 'Run Windows Powershell script first'
Above steps will enable the invoke of script at every system shutdown. Now to make the script visible and show progress:
Navigate to Computer Configuration->Administrative
Templates->System->Scripts
Among the policies showing in the right pane enable below
properties:
Run Windows Powershell scripts first at computer start,shutdown
Run shutdown scripts visible
Current PS script:
Invoke-Command -ComputerName RemoteServer007.FQDN.com -ScriptBlock {
Set-Variable -Name WOWCONFIG -value "d:\ABCs\WOWzers" `
| Start-Process "d:\da-folder\Do-It-NOW-Pleez.cmd"
}
If I log on locally to the server(RemoteServer007.FQDN.com) and execute the cmd file, it runs through all of the lines(commands) within the cmd file.
When I execute it remotely, it gets about 30% of the way through the commands within the cmd file, the PS execution ends without error, but not all of the lines/commands in the cmd file had been executed.
This was discovered by simply configuring each line of the cmd file to output to txt files.
I even tried re-ranging the commands in the cmd file, thinking that perhaps there was a specific command that was causing it to exit, but that is not the case.
I'm wondering if there is some timeout or response that PowerShell is not getting? and just quitting almost immediately after starting?
Any ideas or help would be greatly appreciated.
There are a couple of things you can do here:
You may have a memory issue. Increasing the value of MaxMemoryPerShellMB might help
set-item WSMan:\$target\Shell\MaxMemoryPerShellMB -Value 0 -Force
You'd need to run this once on the remote machine before you execute your commands again.
You can also see possible error logs in the windows event viewer. There are categories for powershell and for Windows Remote Management which you should look at.
Finally, you can just run this process asynchronously, using the task scheduler for instance. I had a similar problem with windows in the past, and running the process from the task scheduler, outside the powershell session, fixed it. There's an example of how we did this in Cloudify here:
https://github.com/CloudifySource/cloudify/blob/master/esc/src/main/resources/clouds/ec2-win/upload/bootstrap-management.ps1#L220