ScheduledJob scriptblock failing - powershell

I'm writing a script involving scheduledjob cmdlets which opens files that users want at a specific time. I'm able to schedule a job to run a scriptblock which opens .bat and .mp3 but I couldn't use the scriptblock to open other extension file (.txt, .doc, .mp4, .ps1). It's like this:
These commands worked fine:
register-scheduledjob -name abc -trigger $abc -scriptblock {start "d:\folder\a.mp3"}
register-scheduledjob -name abc -trigger $abc -scriptblock {start "d:\folder\a.bat"}
But these commands failed:
register-scheduledjob -name abc -trigger $abc -scriptblock {start "d:\folder\b.txt"}
register-scheduledjob -name abc -trigger $abc -scriptblock {start "d:\folder\b.doc"}
register-scheduledjob -name abc -trigger $abc -scriptblock {start notepad}
In the scriptblock I have tried using invoke-item and invoke-command but none of those succeeded. I then checked task manager to file running process, it turned out that those files I have failed to open were running in the background with no windows opened
Why does it happen? Do you guys have any solution? Please help me. It took me very long time trying to fix that problem! Thanks in advance

You need to change the default security/run behavior from "run whether user is logged in or not" to "run only when user is logged in". You can do this with the ScheduledTask commands. Note that the Register-ScheduledJob creates a scheduled task in the Task Schedulers\Microsoft\Windows\PowerShell\ScheduledJobs folder. You can make the change like so:
$principal = (Get-ScheduledTask abc \Microsoft\Windows\PowerShell\ScheduledJobs\).Principal
$principal.LogonType = 'Interactive'
Set-ScheduledTask abc \Microsoft\Windows\PowerShell\ScheduledJobs\ -Principal $principal

Related

Powershell from batch file not working as expected

Let me start with some background. I work in a school district with about 300 laptops using win 10 pro. We are getting ready for our annual standardized testing which uses a lockdown browser. For whatever reason, the company created a new lockdown browser that does not close MSEdge that is running in the background. If you start the lockdown browser as soon as you log in, MSEdge is not an issue.
The provided solution by the software company is to change the registry entries for the test then change it back after the test. That seems like way too much work to me.
My first choice was to use kiosk mode, but it seems it does not work on win 10 pro. The solution I am working on now is to create a user specifically for the testing and use scheduled task at logon with a command to log off at exit. The basic concept seems to work for this situation, as long as the Laptops are plugged in. I can not seem to get the
New-ScheduledTaskSettingsSet –AllowStartIfOnBatteries –DontStopIfGoingOnBatteries
to take effect. I suspect it has to do with the a missing argument, but I can not find any leads with Google searches.
I am using a batch file to call PowerShell and run the .PS1 file
.bat file
:: this Batch file which is run by double clicking in SMACS_IT account. calls powershell to
start the task_kiosk.ps1. Which starts the proccess of creating the scheduled task for the
user STAAR TEST to run TXSecureBrowser.
Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-ExecutionPolicy
Bypass -File C:\1kiosk\task_kiosk_ps1.ps1' -Verb RunAs}"
.PS1 file
$User = "STAAR TEST"
$Description = "A task created to launch the txsecurebrowser using the kiosk_bat.bat file when
the user STAAR TEST logs in"
$taskName = "Launch TXSecureBrowser"
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }
$action = New-ScheduledTaskAction -Execute 'C:\1kiosk\kiosk_bat.bat'
$trigger = New-ScheduledTaskTrigger -AtLogOn -User "STAAR TEST"
$settings = New-ScheduledTaskSettingsSet –AllowStartIfOnBatteries –DontStopIfGoingOnBatteries
if($taskExists) {
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -Description
$Description -User $User
Set-ScheduledTask -TaskName $taskName -Settings $settings
Using this code I can log in as the test account and the task starts the staar test as long as the laptop is plugged in. The task does not work if laptop is not plugged in. However, If I enter the command manually in PowerShell running as administrator the task will work if the laptop is not plugged in. Which is what leads me to believe that the .bat file needs another argument.
It's been too many years since I worked with Task Scheduler, so I can't help you directly. But, I still have my working script from the time. We needed a webpage updated with a gate counter every couple of minutes and the script below is how I automated the configuring of the scheduled task.
Strip out everything you don't want, insert a few things you do want, and you should pretty much have it.
.CMD file
<# : BATCH Bootstrap for PowerShell
#ECHO OFF
SETLOCAL
PowerShell -executionpolicy remotesigned -Command "Invoke-Command -ScriptBlock ([scriptblock]::Create($([System.IO.File]::ReadAllText('%~f0')))) -ArgumentList ([string]'%*').split()"
ENDLOCAL
GOTO :EOF
#>
# https://blog.netnerds.net/2015/01/create-scheduled-task-or-scheduled-job-to-indefinitely-run-a-powershell-script-every-5-minutes/
# Change these three variables to whatever you want
$jobname = "Gate Count Web Updater"
$script = "C:\Users\Public\GateCountWebUpdater.cmd"
$repeat = (New-TimeSpan -Minutes 2)
# The script below will run as the specified user (you will be prompted for credentials)
# and is set to be elevated to use the highest privileges.
# In addition, the task will run every 5 minutes or however long specified in $repeat.
$action = New-ScheduledTaskAction –Execute $script
$duration = (New-TimeSpan -Days (365 * 20))
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat -RepetitionDuration $duration
$msg = "Enter the username and password that will run the task";
$credential = $Host.UI.PromptForCredential("Task username and password",$msg,"$env:userdomain\$env:username",$env:userdomain)
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $trigger -RunLevel Highest -User $username -Password $password -Settings $settings

How to create working Powershell task to stop process hung Firefox process?

I tried to script code to stop hung Firefox process, I want the script to stop all Firefox browser processes periodically.
$trigger = New-JobTrigger -Daily -At 14:20
$options = New-ScheduledJobOption -WakeToRun
Register-ScheduledJob -Name StopFirefox -ScriptBlock {Stop-Process -Name "Firefox" -Force} -Trigger $trigger -ScheduledJobOption $options
But I get Task Scheduled answer that 2147942402 which translates to "File not Found" for both:
{Stop-Process -Name "Firefox" -Force} and {Get-Process -Name "Firefox" | Stop-Process}
You have to add the permission to the job to by adding a user under which the Job runs and who can stop your process, because the process was launched unter a certain user.
If I you add -Credential (Get-Credential) to the Register-ScheduledJob Cmdlet then you should be prompted once for entering your credentials and after that your code should run fine and stop your Firefox process.

Scheduled powershell script invoke-expression not calling another script

I want to schedule a powershell script. It's okay but the powershell script contains an invoke-expression command and it's not calling another script.
Has anybody experienced a similar problem?
As I remember, there are limitations of scheduled jobs. Try to move your code with Invoke-Command to separated script file and schedule Job as follows:
$trigger = New-JobTrigger -Daily -At '6 am'
$options = New-ScheduledJobOption -WakeToRun -RequireNetwork
Register-ScheduledJob -FilePath .\ScriptWithInvokeCommand.ps1 -Name SampleJobName -Trigger $trigger -ScheduledJobOption $options -RunNow
You can also use Scheduled Task instead of Scheduled Job.

Schedule a Job in Powershell 3.0

I am working on PS script that will run a task once the computer has been logged in. Here is how I schedule the task:
$trigger = New-JobTrigger -AtLogOn
Register-ScheduledJob -Name TestSchedule -FilePath <filepath> -Trigger $trigger
The script scheduled to run does nothing but launch the command prompt, however nothing is being run once I log in to the computer. I have tried tinkering with it all I could but I get nothing.
Maybe not the best best solution but you could try putting the other script into this "job-script". Like This. Works Fine for me.
$jobname = "xyz"
$JobTrigger = New-JobTrigger -Weekly -At "03:00 AM" -DaysOfWeek Saturday
$MyOptions = New-ScheduledJobOption -ContinueIfGoingOnBattery -HideInTaskScheduler
Register-ScheduledJob -name "$jobname" -scriptblock {$myscript} -trigger $JobTrigger –ScheduledJobOption $MyOptions
I think your code lacks this command:
Set-ScheduledTask -TaskName $name -TaskPath Microsoft\Windows\PowerShell\ScheduledJobs -Principal (New-ScheduledTaskPrincipal -L Interactive -U $env:USERNAME)
$name is the name of your scheduledjob, this command makes the job interactive to the user, if your code still doesn't work, check out this script:
https://gallery.technet.microsoft.com/scriptcenter/PC-Utilities-Downloader-355e5bfe

Running remote GUI app in Powershell

We have a custom comonent that wraps some of the functionality of powershell so it can be used frim BizTalk 2006. For most operations (checking a file path, copy or move a file) this works fine. However we have the need to fire up a GUI app remotely to do some processing. The component itself handles the connection to the remote box, all we have to do is set some parameters and then tell it to execute a command
Start-Process -FilePath "path to exe" -ArgumentList "arguments for exe" -WorkingDirectory "workingdir for exe"
The issue is this: If we run this from a powershell command line on the box itself, this works fine. However when we fire it up remotely (from BizTalk, from a test harness, even using a remote Powershell command line and connection via Start-PSSession), this app will run briefly then exit without actually doing anything. My suspicion is that because the exe in question requires a GUI to load to run the process, that it is this that is causing an issue. I've tried everything I can think of, including -NoNewWindow and -WindowStyle but to no avail. Any help getting this working would be very much appreciated.
Note: We do not have access to the source for the application we are trying to run as it is an older win32 application, and no batch or command line version of this application has been supplied.
Using standard PowerShell methods (WinRM, WMI) you can't launch applications with GUI. The only solution I know about is to use PsExec from SysInternals (or similar tools). It can launch applications which present GUI to the user. Your command line will look like this:
& ".\psexec" -accepteula -i "\\computername" -u "domain\username" -p "password" "command line"
-accepteula — silently accept EULA.
-i — allow GUI.
Other solutions are more hacky, including remote adding of tasks to the scheduler.
Since I came across this recently, here is my solution using Discord's suggestion of adding a remote task. I preferred the "hack" over having to setup a separate tool.
function Start-Process-Active
{
param
(
[System.Management.Automation.Runspaces.PSSession]$Session,
[string]$Executable,
[string]$Argument,
[string]$WorkingDirectory,
[string]$UserID,
[switch]$Verbose = $false
)
if (($Session -eq $null) -or ($Session.Availability -ne [System.Management.Automation.Runspaces.RunspaceAvailability]::Available))
{
$Session.Availability
throw [System.Exception] "Session is not availabile"
}
Invoke-Command -Session $Session -ArgumentList $Executable,$Argument,$WorkingDirectory,$UserID -ScriptBlock {
param($Executable, $Argument, $WorkingDirectory, $UserID)
$action = New-ScheduledTaskAction -Execute $Executable -Argument $Argument -WorkingDirectory $WorkingDirectory
$principal = New-ScheduledTaskPrincipal -userid $UserID
$task = New-ScheduledTask -Action $action -Principal $principal
$taskname = "_StartProcessActiveTask"
try
{
$registeredTask = Get-ScheduledTask $taskname -ErrorAction SilentlyContinue
}
catch
{
$registeredTask = $null
}
if ($registeredTask)
{
Unregister-ScheduledTask -InputObject $registeredTask -Confirm:$false
}
$registeredTask = Register-ScheduledTask $taskname -InputObject $task
Start-ScheduledTask -InputObject $registeredTask
Unregister-ScheduledTask -InputObject $registeredTask -Confirm:$false
}
}