CircusDad

JJs_HashMonitor.ps1

Dec 23rd, 2017
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.20 KB | None | 0 0
  1. <#
  2. .NOTES
  3. JJ's XMR-STAK HashRate Monitor and Restart Tool
  4.  
  5. Based on an idea by @CircusDad on SupportXMR Chat
  6. His Vega Mining Guide for XMR --> http://vega.miningguides.com/
  7.  
  8. How many times have you walked away for your computer to come back
  9. and notice that your hash rate dropped by HUNDREDS of hashes?
  10. How many times did you wake up to that scenario and wonder how long it had been going on?
  11.  
  12. What happens when you go away for a few days with your lady/gentleman or some other sexy creature?
  13. If you're like me you stress over your rig! It really kills the mood.
  14.  
  15. How much potential profit have you lost to this terror!
  16.  
  17. Well, I have felt your pain and decided to sit down and come up with a solution and here it is.
  18. How much is your peace of mind worth? If you find that your daily hash rate has now increased
  19. because this is no longer happening to you I'd appreciate it if you would consider a donation
  20. toward my hard work.
  21.  
  22. No amount is too small! I'm not greedy! :-)
  23.  
  24. XMR: 42JFvWHSSGCFUBSwTz522zXrkSuhZ6WnwCFv1mFaokDS7LqfT2MyHW32QbmH3CL94xjXUW8UsQMAj8NFDxaVR8Y1TNqY54W
  25. ETH: 0x7f0d537408658221d28e48Cf305581B29963d5f8
  26.  
  27. Purpose: To monitor the STAK hashrate. If it drops below the threshold,
  28. the script is restarted.
  29.  
  30. Features: Script elevates itself if not run in Admin context.
  31. Logging
  32. The Radeon RX Vega driver is disabled/enabled.
  33. Any tools defined in the "Start Video Card Management Tools Definitions"
  34. section below are executed in order.
  35. Sets developer suggested environment variables
  36. Miner is started.
  37. Hash rate is monitored.
  38. If hash rate falls below the target as defined in the $hdiff variable (default is 100 hashes)
  39. or STAK stops responding the miner process is killed.
  40. Script re-starts itself.
  41.  
  42. *** IMPORTANT NOTE ***: If the script cannot kill the miner it will stop and wait for input.
  43. Otherwise it would invoke the miner over and over until the PC ran out of memory.
  44. In testing I have not seen it fail to kill the miner but I need to account for it.
  45.  
  46. Requirements: Elevated privilege (Run as Administrator)
  47. Enable Powershell scripts to run.
  48.  
  49. Software Requirements: XMR-STAK.EXE - Other STAK implementations are no longer supported.
  50. By default the script is configured to use the following software:
  51.  
  52. XMR-STAK.EXE <-- Don't remark out this one. That would be bad.
  53. OverdriveNTool.exe
  54. nvidiasetp0state.exe
  55. nvidiaInspector.exe
  56.  
  57. If you do not wish to use some or all of them just REMARK (use a #)
  58. out the lines below where they are defined in the USER VARIABLES SECTION.
  59. All executable files must be in the same folder as the script.
  60.  
  61.  
  62. Configuration: See below in the script for configuration items.
  63.  
  64. Usage: Powershell.exe -ExecutionPolicy Bypass -File JJs_HashMonitor.ps1
  65.  
  66. Future enhancements under consideration: SMS/email alerts
  67. Move settings out of the script and into a simple
  68. txt file to make it easier to manage them.
  69.  
  70. Author: TheJerichoJones at the Google Monster mail system
  71.  
  72. Version: 3.1fe
  73.  
  74. Release Date: 2017-01-09
  75.  
  76. Copyright 2017, TheJerichoJones
  77.  
  78. License:
  79. This program is free software: you can redistribute it and/or modify
  80. it under the terms of the GNU General Public License version 3 as
  81. published by the Free Software Foundation.
  82.  
  83. This program is distributed in the hope that it will be useful,
  84. but WITHOUT ANY WARRANTY; without even the implied warranty of
  85. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  86. GNU General Public License for more details.
  87.  
  88. You should have received a copy of the GNU General Public License
  89. along with this program. If not, see <http://www.gnu.org/licenses/>.
  90. #>
  91.  
  92. ######################################################################################
  93. # !! Scroll down to "USER VARIABLES SECTION"
  94. # !! There are variables you want to review/modify for your setup
  95. ######################################################################################
  96. $ver = "3.1fe"
  97. $Host.UI.RawUI.WindowTitle = "JJ's XMR-STAK HashRate Monitor and Restart Tool v $ver"
  98. $Host.UI.RawUI.BackgroundColor = "DarkBlue"
  99.  
  100. Clear-Host
  101. Write-Host "Starting the Hash Monitor Script..."
  102.  
  103. Push-Location $PSScriptRoot
  104. ######################################################################################
  105. ############# STATIC Variables - DO NOT CHANGE ##########################
  106. $ScriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
  107. $ScriptName = $MyInvocation.MyCommand.Name
  108. $global:runDays = $null
  109. $global:runHours = $null
  110. $global:runMinutes = $null
  111. $global:web = New-Object System.Net.WebClient
  112. $global:maxhash = 0
  113. $global:currHash = 0
  114. $vidTool = @()
  115. ########## END STATIC Variables - MAKE NO CHANGES ABOVE THIS LINE #######
  116.  
  117. ######################################################################################
  118. ########################### USER VARIABLES SECTION ###################################
  119. ######################################################################################
  120.  
  121. #########################################################################
  122. # Set the REQUIRED variables for your Mining Configuration
  123. #########################################################################
  124. # Read this section carefully or you may end up overclocking your video
  125. # card when you don't want to!! YOU HAVE BEEN WARNED
  126. #########################################################################
  127. $Logfile = "XMR_Restart_$(get-date -f yyyy-MM-dd).log" # Log what we do, delete or REMARK if you don't want logging
  128. $global:STAKexe = "XMR-STAK.EXE" # The miner. Expects to be in same folder as this script
  129. #$global:STAKcmdline = "--noNVIDIA" # STAK arguments. Not required, REMARK out if not needed
  130. $stakIP = '127.0.0.1' # IP or hostname of the machine running STAK (ALWAYS LOCAL) Remote start/restart of the miner is UNSUPPORTED.
  131. # !! DON'T FORGET TO ENABLE THE WEBSERVER IN YOUR CONFIG FILE !!
  132. $stakPort = '420' # Port STAK is listening on
  133. ##### Start Video Card Management Tools Definitions
  134. # These will be executed in order prior to the miner
  135. # Create as many as needed
  136. #### Vid Tool 1
  137. $vidTool += 'OverdriveNTool.exe -p1XMR' # Expects to be in same folder as this script
  138. # Delete or REMARK if you don't want use it
  139. #### Vid Tool 2
  140. $vidTool += 'nvidiasetp0state.exe' # Expects to be in same folder as this script
  141. # Delete or REMARK if you don't want use it
  142. #### Vid Tool 3
  143. $vidTool += 'nvidiaInspector.exe -setBaseClockOffset:0,0,65 -setMemoryClockOffset:0,0,495 -setOverVoltage:0,0 -setPowerTarget:0,110 -setTempTarget:0,0,79' # Expects to be in same folder as this script
  144. # Delete or REMARK if you don't want use it
  145. ##### End VidTools
  146. $global:Url = "http://$stakIP`:$stakPort/api.json" # <-- DO NOT CHANGE THIS !!
  147. #########################################################################
  148. # Set drop trigger and startup timeout
  149. #########################################################################
  150. $hdiff = 100 # This is the drop in total hash rate where we
  151. # trigger a restart (Starting HASHRATE-$hdiff)
  152. #
  153. $timeout = 60 # (STARTUP ONLY)How long to wait for STAK to
  154. # return a hashrate before we fail out and
  155. # restart. There is no limiter on the number of restarts.
  156. # Press CTRL-C to EXIT
  157. #
  158. $STAKstable = 120 # How long to wait for the hashrate to stabilize.
  159. #
  160. #########################################################################
  161. ###################### END USER DEFINED VARIABLES #######################
  162. #################### MAKE NO CHANGES BELOW THIS LINE ####################
  163.  
  164. ##### BEGIN FUNCTIONS #####
  165.  
  166. function call-self
  167. {
  168. Start-Process -FilePath "C:\WINDOWS\system32\WindowsPowerShell\v1.0\Powershell.exe" -ArgumentList .\$ScriptName -WorkingDirectory $PSScriptRoot -NoNewWindow
  169. EXIT
  170. }
  171.  
  172. Function log-Write
  173. {
  174. Param ([string]$logstring)
  175. If ($Logfile)
  176. {
  177. Add-content $Logfile -value $logstring
  178. }
  179. }
  180.  
  181. function chk-STAKEXE
  182. {
  183. ##### Look for STAK #####
  184. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  185. log-Write ("$timeStamp $ver Looking for STAK...")
  186. Write-Host "Looking for STAK..."
  187. If (Test-Path $global:STAKexe)
  188. {
  189. Write-Host "STAK found! Continuing..."
  190. log-Write ("$timeStamp $ver STAK found! Continuing...")
  191. }
  192. Else
  193. {
  194. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  195. log-Write ("$timeStamp $ver $global:STAKexe NOT FOUND.. EXITING")
  196. Clear-Host
  197. Write-Host -fore Red `n`n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  198. Write-Host -fore Red " $global:STAKexe NOT found. "
  199. Write-Host -fore Red " Can't do much without the miner now can you!"
  200. Write-Host -fore Red " Now exploding... buh bye!"
  201. Write-Host -fore Red !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  202. wait-ForF12
  203. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  204. log-Write ("$timeStamp $ver === Script Ended ===")
  205. Exit
  206. }
  207. }
  208.  
  209. function reset-VideoCard {
  210. ###################################
  211. ##### Reset Video Card(s) #####
  212. ##### No error checking
  213. Write-host "Resetting Video Card(s)..."
  214. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  215. log-Write ("$timeStamp $ver Running Video Card Reset")
  216. $d = Get-PnpDevice| where {$_.friendlyname -like 'Radeon RX Vega'}
  217. $vCTR = 0
  218. foreach ($dev in $d) {
  219. $vCTR = $vCTR + 1
  220. Write-host -fore Green "Disabling "$dev.Name '#'$vCTR
  221. Disable-PnpDevice -DeviceId $dev.DeviceID -ErrorAction Ignore -Confirm:$false | Out-Null
  222. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  223. log-Write ("$timeStamp $ver Disabled $vCTR $dev")
  224. Start-Sleep -s 3
  225. Write-host -fore Green "Enabling "$dev.Name '#' $vCTR
  226. Enable-PnpDevice -DeviceId $dev.DeviceID -ErrorAction Ignore -Confirm:$false | Out-Null
  227. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  228. log-Write ("$timeStamp $ver Enabled $vCTR $dev")
  229. Start-Sleep -s 3
  230. }
  231. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  232. log-Write ("$timeStamp $ver $vCTR Video Card(s) Reset")
  233. Write-host -fore Green $vCTR "Video Card(s) Reset"
  234. }
  235.  
  236. Function Run-Tools ($app)
  237. {
  238. foreach ($item in $app)
  239. {
  240. $prog = ($item -split "\s", 2)
  241. if (Test-Path $prog[0])
  242. {
  243. Write-host -fore Green "Starting " $prog[0]
  244. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  245. log-Write ("$timeStamp $ver Starting $item ")
  246. If ($prog[1]) {
  247. Start-Process -FilePath $prog[0] -ArgumentList $prog[1] | Out-Null
  248. }
  249. Else
  250. {
  251. Start-Process -FilePath $prog[0] | Out-Null
  252. }
  253. Start-Sleep -s 1
  254. }
  255. Else
  256. {
  257. Write-Host -fore Red $prog[0] NOT found. This is not fatal. Continuing...
  258. }
  259. }
  260. }
  261.  
  262. function start-Mining
  263. {
  264. ##### Start STAK #####
  265. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  266. log-Write ("$timeStamp $ver Starting STAK...")
  267. If (Test-Path $global:STAKexe)
  268. {
  269. Write-Host "Starting STAK..."
  270. If ($STAKcmdline)
  271. {
  272. Start-Process -FilePath $ScriptDir\$STAKexe -ArgumentList $STAKcmdline -WindowStyle Minimized
  273. }
  274. Else
  275. {
  276. Start-Process -FilePath $ScriptDir\$STAKexe
  277. }
  278. }
  279. Else
  280. {
  281. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  282. log-Write ("$timeStamp $ver $global:STAKexe NOT FOUND.. EXITING")
  283. Clear-Host
  284. Write-Host -fore Red `n`n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  285. Write-Host -fore Red " $global:STAKexe NOT found. "
  286. Write-Host -fore Red " Can't do much without the miner now can you!"
  287. Write-Host -fore Red " Now exploding... buh bye!"
  288. Write-Host -fore Red !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  289. wait-ForF12
  290. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  291. log-Write ("$timeStamp $ver === Script Ended ===")
  292. Exit
  293. }
  294. }
  295.  
  296. Function chk-STAK($global:Url) {
  297. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  298. log-Write ("$timeStamp $ver Waiting for STAK HTTP daemon to start")
  299. Write-host "Waiting for STAK HTTP daemon to start"
  300.  
  301. $flag = "False"
  302. $web = New-Object System.Net.WebClient
  303. $TimeStart = Get-Date -format HH:mm:ss
  304. $timer = $timeout
  305. DO {
  306. Try {
  307. $result = $web.DownloadString($global:Url)
  308. $flag = "True"
  309. }
  310. Catch {
  311. $timeEnd = Get-Date -format HH:mm:ss
  312. $timeDiff = (New-TimeSpan -Start $timeStart -End (Get-Date -format HH:mm:ss)).TotalSeconds
  313. If ($timeDiff -lt $timeout)
  314. {
  315. Write-host -fore Red "STAK not ready... Waiting up to $timer seconds."
  316. Write-host -fore Red "Press CTRL-C to EXIT NOW"
  317. }
  318. If ($timeDiff -gt $timeout)
  319. {
  320. $timeout = 0
  321. }
  322. Start-Sleep -s 10
  323. $timer = $timer - 10
  324. }
  325. } While (($timeout -gt 1) -And ($flag -eq "False"))
  326. If ($flag -eq "True")
  327. {
  328. Clear-Host
  329. set-ForegroundWindow | Out-Null
  330. Write-host -fore Green "`n`n`n## STAK HTTP daemon has started ##`n"
  331. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  332. log-Write ("$timeStamp $ver STAK started successfully")
  333.  
  334. }
  335. ElseIf ($flag -eq "False")
  336. {
  337. Clear-Host
  338. Write-host -fore Red "`n`n`n!! Timed out waiting for STAK HTTP daemon to start !!`n"
  339. start-sleep -s 10
  340. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  341. log-Write ("$timeStamp $ver Timed out waiting for STAK HTTP daemon to start")
  342. Start-Sleep -s 10
  343. #Write-Host -NoNewLine "Press any key to EXIT..."
  344. #$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  345. call-Self
  346. EXIT
  347. }
  348. Else
  349. {
  350. Clear-Host
  351. Write-host -fore Red "`n`n`n*** Unknown failure (Daemon failed to start?)... EXITING ***`n"
  352. start-sleep -s 10
  353. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  354. log-Write ("$timeStamp $ver Unknown failure starting STAK (Daemon failed to start?)")
  355. Start-Sleep -s 10
  356. #Write-Host -NoNewLine "Press any key to EXIT..."
  357. #$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  358. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  359. log-Write ("$timeStamp $ver === Script Ended ===")
  360. call-Self
  361. EXIT
  362. }
  363.  
  364. }
  365.  
  366. function starting-Hash
  367. {
  368. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  369. log-Write ("$timeStamp $ver Waiting for hash rate to stabilize")
  370. #Write-host -fore Green "Waiting for hash rate to stabilize"
  371.  
  372. #$startTestHash = 1
  373. $global:currTestHash = 0
  374.  
  375. $sCTR = 0
  376. # Wait x seconds for hash rate to stabilize
  377. while ($STAKstable -gt 0)
  378. {
  379. $data = $null
  380. $total = $null
  381. $global:currTestHash = $null
  382. $data = @{}
  383. $total = @{}
  384. $rawdata = Invoke-WebRequest -UseBasicParsing -Uri $global:Url -TimeoutSec 60
  385. If ($rawdata)
  386. {
  387. $data = $rawdata | ConvertFrom-Json
  388. $rawtotal = ($data.hashrate).total
  389. $total = $rawtotal | foreach {$_}
  390. $global:currTestHash = $total[0]
  391. If (!$global:currTestHash -eq [int] -And $sCTR -gt 20)
  392. {
  393. Clear-Host
  394. Write-host -fore Red "`nSTAK is not returning good hash data"
  395. Write-host -fore Red "`nCurrent Hash = $global:currTestHash"
  396. Write-host -fore Red "Restarting in 10 seconds"
  397. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  398. log-Write ("$timeStamp $ver Hash Mon Phase: STAK is not returning good data. Current Hash = $global:currTestHash")
  399. Start-Sleep -s 10
  400. $flag = "False"
  401. #Break
  402. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  403. log-Write ("$timeStamp $ver === Script Ended ===")
  404. call-Self
  405. Exit
  406. }
  407. ElseIf ($global:currTestHash -eq 0 -And $sCTR -gt 20)
  408. {
  409. Clear-Host
  410. Write-host -fore Red "`nSTAK seems to have stopped hashing"
  411. Write-host -fore Red "`nCurrent Hash = $global:currTestHash"
  412. Write-host -fore Red "Restarting in 10 seconds"
  413. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  414. log-Write ("$timeStamp $ver Hash Mon Phase: STAK seems to have stopped hashing. Current Hash = $global:currTestHash")
  415. Start-Sleep -s 10
  416. $flag = "False"
  417. #Break
  418. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  419. log-Write ("$timeStamp $ver === Script Ended ===")
  420. call-Self
  421. Exit
  422. }
  423. If (!$startTestHash)
  424. {
  425. $startTestHash = $global:currTestHash
  426. }
  427.  
  428. Clear-Host
  429. If ($global:currTestHash)
  430. {
  431. Write-host -fore Green "`n`nCurrent Hash Rate: $global:currTestHash H/s"
  432. }
  433. Write-host -fore Green "`n`nWaiting $STAKstable seconds for hashrate to stabilize."
  434. Write-host -fore Green "Press CTRL-C to EXIT NOW"
  435. Start-Sleep -s 1
  436. $STAKstable = $STAKstable - 1
  437. $sCTR = $sCTR + 1
  438. }
  439. Else
  440. {
  441. Clear-Host
  442. Write-host -fore Red "`nSTAK is not returning array data"
  443. Write-host -fore Red "Restarting in 10 seconds"
  444. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  445. log-Write ("$timeStamp $ver Stabilization Phase: STAK is not returning array data.")
  446. Start-Sleep -s 10
  447. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  448. log-Write ("$timeStamp $ver === Script Ended ===")
  449. call-Self
  450. Exit
  451. }
  452. }
  453. If (!$global:currTestHash)
  454. {
  455. Clear-Host
  456. Write-host -fore Green `nCould not get hashrate... restarting
  457. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  458. log-Write ("$timeStamp $ver Stabilization Phase: Could not get hashrate... restarting")
  459. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  460. log-Write ("$timeStamp $ver === Script Ended ===")
  461. call-Self
  462. Exit
  463. }
  464. ElseIf ($global:currTestHash -gt $startTestHash)
  465. {
  466. $global:maxhash = $global:currTestHash
  467. }
  468. Else
  469. {
  470. $global:maxhash = $startTestHash
  471. }
  472.  
  473. $global:currHash = $global:currTestHash
  474. $global:rTarget = ($global:maxhash - $hdiff)
  475. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  476. log-Write ("$timeStamp $ver Hash rate stabilized")
  477. log-Write ("$timeStamp $ver Starting Hashrate: $global:maxhash H/s Drop Target Hashrate: $global:rTarget H/s hDiff: $hdiff")
  478. }
  479.  
  480. function current-Hash
  481. {
  482. # Check our current hashrate against low target every 60 seconds
  483. Clear-Host
  484. Write-host -fore Green `nHash monitoring has begun.
  485. $timer = 0
  486. $runTime = 0
  487. $flag = "False"
  488. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  489. log-Write ("$timeStamp $ver Hash monitoring has begun")
  490.  
  491. DO
  492. {
  493. Try {
  494. $data = $null
  495. $total = $null
  496. $global:currHash = $null
  497. $data = @{}
  498. $total = @{}
  499. Write-host -fore Green `nQuerying STAK...this can take a minute.
  500. $rawdata = Invoke-WebRequest -UseBasicParsing -Uri $global:Url -TimeoutSec 60
  501. $flag = "True"
  502. }
  503. Catch
  504. {
  505. Clear-Host
  506. Write-host -fore Red "`nWe seem to have lost connectivity to STAK"
  507. Write-host -fore Red "Restarting in 10 seconds"
  508. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  509. log-Write ("$timeStamp $ver Restarting - Lost connectivity to STAK")
  510. Start-Sleep -s 10
  511. $flag = "False"
  512. #Break
  513. }
  514. If ($flag -eq "False")
  515. {
  516. Break
  517. }
  518. If ($rawdata)
  519. {
  520. # Parse JSON data
  521. $data = $rawdata | ConvertFrom-Json
  522. # Total Hash
  523. $rawtotal = ($data.hashrate).total
  524. $total = $rawtotal | foreach {$_}
  525. $global:currHash = $total[0]
  526. If (!$global:currHash -eq [int])
  527. {
  528. Clear-Host
  529. Write-host -fore Red "`nSTAK is not returning good hash data"
  530. Write-host -fore Red "`nCurrent Hash = $global:currHash"
  531. Write-host -fore Red "Restarting in 10 seconds"
  532. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  533. log-Write ("$timeStamp $ver Hash Mon Phase: STAK is not returning good data. Current Hash = $global:currHash")
  534. Start-Sleep -s 10
  535. $flag = "False"
  536. Break
  537. # Falls through to call-Self
  538. }
  539. ElseIf ($global:currHash -eq 0)
  540. {
  541. Clear-Host
  542. Write-host -fore Red "`nSTAK seems to have stopped hashing"
  543. Write-host -fore Red "`nCurrent Hash = $global:currHash"
  544. Write-host -fore Red "Restarting in 10 seconds"
  545. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  546. log-Write ("$timeStamp $ver Hash Mon Phase: STAK seems to have stopped hashing. Current Hash = $global:currHash")
  547. Start-Sleep -s 10
  548. $flag = "False"
  549. Break
  550. # Falls through to call-Self
  551. }
  552. }
  553. Else
  554. {
  555. Clear-Host
  556. Write-host -fore Red "`nSTAK is not returning array data"
  557. Write-host -fore Red "Restarting in 10 seconds"
  558. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  559. log-Write ("$timeStamp $ver Hash Mon Phase: STAK is not returning array data. $rawdata")
  560. Start-Sleep -s 10
  561. $flag = "False"
  562. Break
  563. # Falls through to call-Self
  564. }
  565. # Current difficulty
  566. $rawdiff = ($data.results).diff_current
  567. $currDiff = $rawdiff | foreach {$_}
  568. $global:currDiff = $currDiff[0]
  569. # Good shares processed
  570. $rawSharesGood = ($data.results).shares_good
  571. $SharesGood = $rawSharesGood | foreach {$_}
  572. $global:GoodShares = $SharesGood[0]
  573. # Total shares processed
  574. $rawSharesTotal = ($data.results).shares_total
  575. $SharesTotal = $rawSharesTotal | foreach {$_}
  576. $global:TotalShares = $SharesTotal[0]
  577. # Shares processed time
  578. $rawSharesTime = ($data.results).avg_time
  579. $SharesTime = $rawSharesTime | foreach {$_}
  580. $global:TimeShares = $SharesTime[0]
  581. # Current Pool
  582. $global:ConnectedPool = ($data.connection).pool
  583. # Pool connected uptime
  584. $rawTimeUp = ($data.connection).uptime
  585. $rawUpTime = $rawTimeUp | foreach {$_}
  586. $global:UpTime = $rawUpTime[0]
  587.  
  588. refresh-Screen
  589.  
  590. Start-Sleep -s 60
  591. $timer = ($timer + 60)
  592. $runTime = ($timer)
  593. } while ($global:currHash -gt $global:rTarget)
  594.  
  595. If ($flag -eq "True")
  596. {
  597. Clear-Host
  598. Write-host -fore Red "`n`nHash rate dropped from $global:maxhash H/s to $global:currHash H/s"
  599. Write-host -fore Red "`nRestarting in 10 seconds"
  600. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  601. $tFormat = get-RunTime ($runTime)
  602. log-Write ("$timeStamp $ver Restarting after $tFormat - Hash rate dropped from $global:maxhash H/s to $global:currHash H/s")
  603. Start-Sleep -s 10
  604. }
  605. }
  606.  
  607. function kill-Process ($STAKexe) {
  608. try
  609. {
  610. $prog = ($STAKexe -split "\.", 2)
  611. $prog = $prog[0]
  612. # get STAK process
  613. $stakPROC = Get-Process $prog -ErrorAction SilentlyContinue
  614. if ($stakPROC) {
  615. Write-host -fore Red "$prog is running... killing $prog process."
  616. # try gracefully first
  617. $stakPROC.CloseMainWindow() | Out-Null
  618. # kill after five seconds
  619. Sleep 5
  620. if (!$stakPROC.HasExited) {
  621. $stakPROC | Stop-Process -Force | Out-Null
  622. }
  623. if (!$stakPROC.HasExited) {
  624. Write-host -fore Red "Failed to kill the $prog process"
  625. Write-host -fore Red "`nIf we don't stop here STAK would be invoked"
  626. Write-host -fore Red "`nover and over until the PC crashed."
  627. Write-host -fore Red "`n`n That would be very bad."
  628. Write-host -fore Red 'Press any key to EXIT...';
  629. $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
  630. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  631. log-Write ("$timeStamp $ver Failed to kill $prog")
  632. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  633. log-Write ("$timeStamp $ver === Script Ended ===")
  634. EXIT
  635. }
  636. Else
  637. {
  638. Write-host -fore Green "Successfully killed the $prog process"
  639. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  640. log-Write ("$timeStamp $ver STAK closed successfully")
  641. }
  642. }
  643. Else
  644. {
  645. #Write-host -fore Green "`n$prog process was not found"
  646. #$timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  647. #log-Write ("$timeStamp $ver $prog process was not found")
  648. }
  649. }
  650. Catch
  651. {
  652. Write-host -fore Red "Failed to kill the process $prog"
  653. Write-host -fore Red "`nIf we don't stop here STAK would be invoked"
  654. Write-host -fore Red "`nover and over until the PC crashed."
  655. Write-host -fore Red "`n`n That would be very bad.`n`n"
  656. wait-ForF12
  657. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  658. log-Write ("$timeStamp $ver Failed to kill $prog")
  659. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  660. log-Write ("$timeStamp $ver === Script Ended ===")
  661. EXIT
  662. }
  663. }
  664.  
  665. Function refresh-Screen
  666. {
  667. Clear-Host
  668. $tmRunTime = get-RunTime ($runTime)
  669. $tpUpTime = get-RunTime ($global:UpTime)
  670. #Write-Host "=================================================="
  671. Write-host -fore Green `nStarting Hash Rate: $global:maxhash H/s
  672. Write-host -fore Green `nRestart Target Hash Rate: $global:rTarget H/s
  673. Write-host -fore Green `nCurrent Hash Rate: $global:currHash H/s
  674. Write-host -fore Green `nMonitoring Uptime: $tmRunTime `n
  675. Write-Host "=================================================="
  676. Write-host -fore Green `nPool: $global:ConnectedPool
  677. Write-host -fore Green `nPool Uptime: $tpUpTime
  678. Write-host -fore Green `nPool Difficulty: $global:currDiff
  679. Write-host -fore Green `nTotal Shares: $global:TotalShares
  680. Write-host -fore Green `nGood Shares: $global:GoodShares
  681. Write-host -fore Green `nGood Shares %: (($global:GoodShares / $global:TotalShares) * 100)
  682. Write-Host -fore Green `nShare Time: $global:TimeShares
  683. Write-Host "`nThis software is supported by donations."
  684. Write-Host "`nhttps://pastebin.com/raw/aDcjBxCE"
  685. Write-Host "`nIf you can't do a direct donation then mining a"
  686. Write-Host "`nfew minutes a day for me at pool.SupportXMR.com"
  687. Write-Host "`nwould be greatly appreciated."
  688. #Write-Host "=================================================="
  689. }
  690.  
  691. function set-STAKVars
  692. {
  693. Write-host -fore Green "Setting Env Variables for STAK"
  694. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  695. log-Write ("$timeStamp $ver Setting Env Variables for STAK")
  696.  
  697. [System.Environment]::SetEnvironmentVariable("GPU_FORCE_64BIT_PTR", "1", "User")
  698. [System.Environment]::SetEnvironmentVariable("GPU_MAX_HEAP_SIZE", "99", "User")
  699. [System.Environment]::SetEnvironmentVariable("GPU_MAX_ALLOC_PERCENT", "99", "User")
  700. [System.Environment]::SetEnvironmentVariable("GPU_SINGLE_ALLOC_PERCENT", "99", "User")
  701.  
  702. Write-host -fore Green "Env Variables for STAK have been set"
  703. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  704. log-Write ("$timeStamp $ver Env Variables for STAK have been set")
  705. }
  706.  
  707. function get-RunTime ($sec)
  708. {
  709. $myTimeSpan = (new-timespan -seconds $sec)
  710. If ($sec -ge 3600 -And $sec -lt 86400)
  711. {
  712. $global:runHours = $myTimeSpan.Hours
  713. $global:runMinutes = $myTimeSpan.Minutes
  714. Return "$global:runHours Hours $global:runMinutes Min"
  715. }
  716. ElseIf ($sec -ge 86400)
  717. {
  718. $global:runDays = $myTimeSpan.Days
  719. $global:runHours = $myTimeSpan.Hours
  720. $global:runMinutes = $myTimeSpan.Minutes
  721. Return "$global:runDays Days $global:runHours Hours $global:runMinutes Min"
  722. }
  723. Elseif ($sec -ge 60 -And $sec -lt 3600)
  724. {
  725. $global:runMinutes = $myTimeSpan.Minutes
  726. Return "$global:runMinutes Min"
  727. }
  728. Elseif ($sec -lt 60)
  729. {
  730. Return "Less than 1 minute"
  731. }
  732. }
  733.  
  734. ############################## BEGIN ELEVATION #######################################
  735. # If you can't Elevate you're going to have a bad time...
  736. # Elevation code written by: Jonathan Bennett
  737. # License: Not specified
  738. # https://www.autoitscript.com/forum/topic/174609-powershell-script-to-self-elevate/
  739. #
  740. # Test if admin
  741. function Test-IsAdmin()
  742. {
  743. # Get the current ID and its security principal
  744. $windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  745. $windowsPrincipal = new-object System.Security.Principal.WindowsPrincipal($windowsID)
  746.  
  747. # Get the Admin role security principal
  748. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  749.  
  750. # Are we an admin role?
  751. if ($windowsPrincipal.IsInRole($adminRole))
  752. {
  753. $true
  754. }
  755. else
  756. {
  757. $false
  758. }
  759. }
  760.  
  761. # Get UNC path from mapped drive
  762. function Get-UNCFromPath
  763. {
  764. Param(
  765. [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
  766. [String]
  767. $Path)
  768.  
  769. if ($Path.Contains([io.path]::VolumeSeparatorChar))
  770. {
  771. $psdrive = Get-PSDrive -Name $Path.Substring(0, 1) -PSProvider 'FileSystem'
  772.  
  773. # Is it a mapped drive?
  774. if ($psdrive.DisplayRoot)
  775. {
  776. $Path = $Path.Replace($psdrive.Name + [io.path]::VolumeSeparatorChar, $psdrive.DisplayRoot)
  777. }
  778. }
  779.  
  780. return $Path
  781. }
  782.  
  783. function Resize-Console
  784. {
  785. #
  786. # .Synopsis
  787. # Resets the size of the current console window
  788. # .Description
  789. # Set-myConSize resets the size of the current console window. By default, it
  790. # sets the windows to a height of 40 lines, with a 3000 line buffer, and sets the
  791. # the width and width buffer to 120 characters.
  792. # .Example
  793. # Set-myConSize
  794. # Restores the console window to 120x40
  795. # .Example
  796. # Set-myConSize -Height 30 -Width 180
  797. # Changes the current console to a height of 30 lines and a width of 180 characters.
  798. # .Parameter Height
  799. # The number of lines to which to set the current console. The default is 40 lines.
  800. # .Parameter Width
  801. # The number of characters to which to set the current console. Default is 120. Also sets the buffer to the same value
  802. # .Inputs
  803. # [int]
  804. # [int]
  805. # .Notes
  806. # Author: Charlie Russel
  807. # Modified by: TheJerichoJones
  808. # Copyright: 2017 by Charlie Russel
  809. # : Permission to use is granted but attribution is appreciated
  810. # Initial: 28 April, 2017 (cpr)
  811. # ModHist:
  812. #
  813. [CmdletBinding()]
  814. Param(
  815. [Parameter(Mandatory=$False,Position=0)]
  816. [int]
  817. $Height = 35,
  818. [Parameter(Mandatory=$False,Position=1)]
  819. [int]
  820. $Width = 55
  821. )
  822. $Console = $host.ui.rawui
  823. $Buffer = $Console.BufferSize
  824. $ConSize = $Console.WindowSize
  825.  
  826. # If the Buffer is wider than the new console setting, first reduce the buffer, then do the resize
  827. If ($Buffer.Width -gt $Width -or $Buffer.Height -gt $Height) {
  828. If ($Buffer.Width -gt $Width ) {
  829. $ConSize.Width = $Width
  830. }
  831. If ($Buffer.Height -gt $Height ) {
  832. $ConSize.Height = $Height
  833. }
  834. $Console.WindowSize = $ConSize
  835. }
  836. $Buffer.Width = $Width
  837. $ConSize.Width = $Width
  838. $Buffer.Height = $Height
  839. $Console.BufferSize = $Buffer
  840. $ConSize = $Console.WindowSize
  841. $ConSize.Width = $Width
  842. $ConSize.Height = $Height
  843. $Console.WindowSize = $ConSize
  844. }
  845.  
  846. # Relaunch the script if not admin
  847. function Invoke-RequireAdmin
  848. {
  849. Param(
  850. [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
  851. [System.Management.Automation.InvocationInfo]
  852. $MyInvocation)
  853.  
  854. if (-not (Test-IsAdmin))
  855. {
  856. # Get the script path
  857. $scriptPath = $MyInvocation.MyCommand.Path
  858. $scriptPath = Get-UNCFromPath -Path $scriptPath
  859.  
  860. # Need to quote the paths in case of spaces
  861. $scriptPath = '"' + $scriptPath + '"'
  862.  
  863. # Build base arguments for powershell.exe
  864. [string[]]$argList = @('-NoLogo -NoProfile', '-ExecutionPolicy Bypass', '-File', $scriptPath)
  865.  
  866. # Add
  867. $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
  868. $argList += $MyInvocation.UnboundArguments
  869.  
  870. try
  871. {
  872. $process = Start-Process PowerShell.exe -PassThru -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList
  873. exit $process.ExitCode
  874. }
  875. catch {}
  876.  
  877. # Generic failure code
  878. exit 1
  879. }
  880. }
  881.  
  882.  
  883. function set-ForegroundWindow
  884. {
  885. $user32DLL = @"
  886. using System;
  887. using System.Runtime.InteropServices;
  888. public class Tricks
  889. {
  890. [DllImport("user32.dll")]
  891. [return: MarshalAs(UnmanagedType.Bool)]
  892. public static extern bool SetForegroundWindow(IntPtr hWnd);
  893. }
  894. "@
  895.  
  896. Add-Type -TypeDefinition $user32DLL
  897.  
  898. $wHandle = (Get-Process -id $pid).MainWindowHandle
  899. [Tricks]::SetForegroundWindow($wHandle)
  900. }
  901.  
  902. function wait-ForF12
  903. {
  904. $continue = $true
  905. Write-Host "Press F12 to EXIT."
  906. while($continue)
  907. {
  908.  
  909. if ([console]::KeyAvailable)
  910. {
  911. #echo "Press F12";
  912. $x = [System.Console]::ReadKey()
  913.  
  914. switch ( $x.key)
  915. {
  916. F12 { $continue = $false }
  917. }
  918. Start-Sleep -s 1
  919. }
  920. }
  921. }
  922.  
  923.  
  924. ##### END FUNCTIONS #####
  925.  
  926. ##### MAIN - or The Fun Starts Here #####
  927. $ProgressPreference = 'SilentlyContinue'
  928. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  929. log-Write ("$timeStamp $ver === Script Started ===")
  930.  
  931. # Relaunch if not admin
  932. Invoke-RequireAdmin $script:MyInvocation
  933.  
  934. Resize-Console
  935.  
  936. set-ForegroundWindow | Out-Null
  937.  
  938. kill-Process ($STAKexe)
  939.  
  940. chk-STAKEXE
  941.  
  942. reset-VideoCard
  943.  
  944. If ($vidTool) # If $vidTool is defined
  945. {
  946. Run-Tools ($vidTool) # Run your tools
  947. }
  948.  
  949. set-STAKVars # Set suggested environment variables
  950.  
  951. start-Mining # Start mining software
  952.  
  953. chk-STAK($global:Url) # Wait for STAK to return a hash rate
  954.  
  955. starting-Hash # Get the starting hash rate
  956.  
  957. current-Hash # Gather the current hash rate every 60 seconds until it drops beneath the threshold
  958.  
  959. $timeStamp = "{0:yyyy-MM-dd_HH:mm}" -f (Get-Date)
  960. log-Write ("$timeStamp $ver === Script Ended ===")
  961.  
  962. $ProgressPreference = 'Continue'
  963.  
  964. call-Self # Restart the script
  965.  
  966. ##### The End of the World as we know it #####
  967. EXIT
Add Comment
Please, Sign In to add comment