How to test what started a powershell script - windows

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

Related

How to check in PowerShell if the script was run in background (e.g. Windows Task Scheduler) or in user session

How to check in PowerShell if the script was run in background (e.g. via Windows Task Scheduler) or in user session
Inside the script (When the script is running) you can use $host.name
if ($host.name -match 'ise') {"Do not send mail.."}
if ($host.name -match 'console') {Send-mail...}

Powershell script scheduled using Task scheduler doesn't run...script runs fine

I am using windows 8.
I have the following script file (that spits our all services to a CSV file). When I run this as follows from powershell editor, it works fine.
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe C:\Powershell\SchedulingaScript.ps1
When I schedule this script from windows task scheduler it won't kick off.
I have "Unrestricted" execution policy set on that session. Following is the code in the script file and 2 images are the setting on the task scheduler.
#Trying out scheduling powershell scripts
Get-Service | Export-CSV "C:\ExportingServicestoaCSVFile.CSV"
You have to use the -file Parameter. Simply enter powershell -? and you will see all possible options to launch powershell.
Hope this helps -tom
In the Edit Action dialog Program box simply put PowerShell. In Arguments put -file "C:\sciptlocation\scriptname.ps1"

Windows Power Shell & Console Windows Host processes will keep running after windows task schduler's task ends

I have windows server 2012 R2 , and i have defined a task inside windows task scheduler, as follow:-
-i create a .ps file, which mainly calls a remote URL:-
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$request = [System.Net.WebRequest]::Create("https://ipAddress/")
$response = $request.GetResponse()
$response.Close()
-then i create a .bat file to call the power-shell script, as follow:-
"%SYSTEMROOT%\system32\windowspowershell\v1.0\powershell.exe" -Command Start-Process "$PSHOME\powershell.exe" -Verb RunAs -ArgumentList "'-NoExit %~dp0\AppPoolActivation.ps1'"
-i define the task to run daily on each 30 minutes for a duration of day.
-the task will be calling the .bat file.
now i am facing a problem is that when the task runs successfully, two processes will keep running 1)Windows Power Shell & 2)Console Windows host. which will cause my server to became very slow and will stop responding after around 12 hours,, now here is how my task manager will looks like when the task runs for around 5 times-
where many instances of Windows Power Shell & Console Windows host are running,, so can anyone adivce on this please ? i though the related processes will end as soon as the windows task ends..
-NoExit means no exit... So if you want it to close after the script is executed, then don't use it.

Run powershell script whenever a server reboot is initiated and show the script progress in cmd

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

kill remote job initiated by invoke-command

what is the easy way to kill remote job initiated by invoke-command with background processes?
I kick remote PS script to run legacy exe file and need a way to kill that process.
I was going to use stop-job first but as I am reading it works only for local processes.
Then I was going to use Remove-job -force command but if I understood right, it cannot kill running process until it completes (again my remote ps script will start another process to run exe file).
I am reading I can kill a process using wmi terminate command but I do not know how to get PID of remote process (I cannot use name because I can kill processes from other users)
what is the best way to achieve my goal?
my script looks like that:
invoke-command -computername server1,server2,server3..etc -script-block {my.exe} -asjob
loop to wait for all processes to complete and report progress
check for CTRL-C press and kill all remote instances on {my.exe}
ok checked this morning from work and this works fine from a calling script:
get-job | remove-job -force
I was confused by MSDN doc which says:
When you stop a background job, Windows PowerShell **completes** all tasks that are pending in that job queue and then ends the job
Check out this answer, you can add the start process command to your script block and return the pid or save it to a text file to be reference later.
PowerShell - get process ID of called application

Resources