Automate start/stop of NiceHash Miner

Motivation

NiceHash Miner is an incredibly simple program to use and I've been wanting to start and stop the program using the Windows Task Scheduler. I initially tried stop the task by using the "Stop task if running more than x" option in the settings section but quickly found that NiceHash Miner 2.exe actually launches another process named excavator.exe (and not as a child process) which doesn't get stopped even though NiceHash Miner 2.exe was stopped by the Windows Task Scheduler.

The work around was to create a helper in the form of a powershell script to start and stop the individual processes. You'll see the end result below.

Note : You'll also need to enable the "Autostart mining" within NiceHash Miner for this to work.



Set execution policy to remote signed

Set-ExecutionPolicy RemoteSigned

Creating a powershell script to start/stop NiceHash Miner processes

NiceHashHelper.ps1

# usage : e.g. "powershell .\NiceHashHelper.ps1 -action start" 

param ([string]$action = "Start")

if($action -eq "Start")
{
    Write-Host "Starting.."
    Start-Process "$env:LOCALAPPDATA\Programs\NiceHash Miner 2\NiceHash Miner 2.exe"
} 
elseif ($action -eq "Stop")
{
    Write-Host "Stopping.."
    Stop-Process -Name *NiceHash*            # The main program
    Stop-Process -Name *excavator*           # The GPU miner
    Stop-Process -Name *xmr-stak-cpu*        # The CPU miner
}
else {
    Write-Host "Invalid action : Please choose either Start or Stop with the action param"
}

Creating a task in Task Scheduler

# Variables
$cmd = "$env:USERPROFILE\Desktop\NiceHash\NiceHashHelper.ps1"
$argumentPrefix =  '-command "& {0} -action "' -f ($cmd)
$startTrigger =  New-ScheduledTaskTrigger -Daily -At 6pm
$stopTrigger =  New-ScheduledTaskTrigger -Daily -At 7am
$taskFolderName = '\NiceHash Tasks'
$executable = "Powershell.exe"

# The "Start" task
$startActionArgument = '{0} {1}' -f ($argumentPrefix, "Start")
$startAction = New-ScheduledTaskAction -Execute $executable -Argument $startActionArgument
Register-ScheduledTask -Action $startAction -Trigger $startTrigger -TaskName "Start NiceHash Miner" -TaskPath $taskFolderName

# The "Stop" task
$stopActionArgument = '{0} {1}' -f ($argumentPrefix, "Stop")
$stopAction = New-ScheduledTaskAction -Execute $executable -Argument $stopActionArgument
Register-ScheduledTask -Action $stopAction -Trigger $stopTrigger -TaskName "Stop NiceHash Miner" -TaskPath $taskFolderName

# Unregister-ScheduledTask -TaskName "Start NiceHash Miner"
# Unregister-ScheduledTask -TaskName "Stop NiceHash Miner"