Script to close program that's causing CPU overheat - c#

You see i use CoreTemp program to monitor CPU heat, this program allows you to run a script or a program when the CPU temp reaches a specified value..
What i want is that when the CPU temp reaches a certain value, the process that has the most CPU usage is to be closed!!
In other words, I need a Script/program that automatically scans the processes and force close the process that has the highest CPU usage..
Thanks!

Try this :
Check the prog with the higher Memory Use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=4 tokens=1-5 delims= " %%a in ('tasklist') do (
set $Size=00000000%%e
set $Size=!$size:.=!
set #!$size:~-10!=%%a
)
for /f "tokens=2 delims==" %%a in ('set #') do (set $Bigger=%%a)
echo taskkill /IM !$Bigger!
Check the process with the higher CPU use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=2 tokens=1-2 delims= " %%a in ('"wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime"') do (
if "%%a"=="_Total" goto:next
set #%%b=%%a
)
:next
for /f "tokens=1-2 delims==" %%a in ('set #') do (
set $Bigger=%%b
set $Value=%%a
)
if "!$Value!"=="#0" goto:nothing
echo taskkill /IM !$Bigger!.exe [!$Value:#=!%%]
goto:eof
:nothing
Echo CPU IS INACTIVE
If the output is OK for you remove the ECHO on the last line
You can ameliorate the script. In case you have two processus with the same name you have to work with th PID of the process in place of the name. Because the programm will return program#1, program#2, etc.. That's just the base script.
And Like #09stephenb commented you have to go carrefully with such a script....

I started working on this for you but I have to leave. It's mostly complete so I'm just gonna give you what I have so far and let you take it from there.
#echo off
setlocal
set proc=Win32_PerfFormattedData_PerfProc_Process
set "wmi=wmic path %proc% get Name^,PercentProcessorTime"
for /f "skip=1 tokens=*" %%a in ('"%wmi%"^|findstr /i /v /g:Excludes.txt') do (
for /f "tokens=2 delims= " %%b in ( "%%a" ) do if %%b NEQ 0 echo %%a
)
Create a file called Excludes.txt and make sure it's in the same dir of your script.
"System Idle Process"
Idle
explorer.exe
taskmgr.exe
lsass.exe
csrss.exe
smss.exe
winlogon.exe
svchost.exe
services.exe
Core Temp
_Total

Related

Batch file getting syntax error

I am trying to write a batch file that checks if your computer name is a certain name, and then if it matches the exe file will run.
#echo off
echo adidas shoe cop bot console...
echo by sam
pause
echo checking for computer name...
If %computername%=="DESKTOP-HQPDA76"
then echo %computername% found
echo user confirmed
echo starting file
pause
start /B "" "C:\Users\Sam Marriott\Desktop\Adidas Shoe Cop Bot\Package\Adidas Shoe Cop Bot\bin\Debug\Adidas Shoe Cop Bot.exe"
pause
Else NOT %computername%=="DESKTOP-HQPDA76"
then echo user access denied
pause
I am getting some error about (something) was not expected here, or syntax error, but I can't really read it because the command prompt closes too quickly. Any help?
Your syntax for the IF statement is wrong. Try this:
#echo off
echo adidas shoe cop bot console...
echo by sam
pause
echo checking for computer name...
if "%computername%"=="DESKTOP-HQPDA76" (
echo %computername% found
echo user confirmed
echo starting file
pause
start /B "" "C:\Users\Sam Marriott\Desktop\Adidas Shoe Cop Bot\Package\Adidas Shoe Cop Bot\bin\Debug\Adidas Shoe Cop Bot.exe"
pause
) else (
echo user access denied
pause
)

How to create a batch file to backup Mysql database?

I have been trying to create a batch file to backup MySQL database. All worked fine but the backup is just empty. I don't know where have gone wrong. Here is my code
set year=%DATE:~10,4%
set day=%DATE:~7,2%
set mnt=%DATE:~4,2%
set hr=%TIME:~0,2%
set min=%TIME:~3,2%
IF %day% LSS 10 SET day=0%day:~1,1%
IF %mnt% LSS 10 SET mnt=0%mnt:~1,1%
IF %hr% LSS 10 SET hr=0%hr:~1,1%
IF %min% LSS 10 SET min=0%min:~1,1%
set backuptime=%year%-%day%-%mnt%-%hr%-%min%
echo %backuptime%
set dbuser=root
set dbpass=vsplabs
set mysqldumpexe="C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe"
set backupfldr="C:\Users\sowmya\Desktop\Mysqlbackups"
set datafldr="C:\ProgramData\MySQL\MySQL Server 5.6\data"
set zipper="c:\MySQLBackups\zip\7za.exe"
pushd %datafldr%
echo "Pass each name to mysqldump.exe and output an individual .sql file for each"
#echo off
FOR /D %%F IN (*) DO (
IF NOT [%%F]==[performance_schema] (
SET %%F=!%%F:#002d=-!
%mysqldumpexe% --user=%dbuser% --password=%dbpass% --databases --routines --log-error=%errorLogPath% %%F > "%backupfldr%%%F.%backuptime%.sql"
) ELSE (
echo Skipping DB backup for performance_schema
)
)
echo "Zipping all files ending in .sql in the folder"
%zipper% a -tzip "%backupfldr%FullBackup.%backuptime%.zip" "%backupfldr%*.sql
echo "done"
popd
And another issue I just wanted only one database its being retrieving all the databases from database..How to modify that and And i have been getting an extra database named as "mysql"
This can be run directly in cmd (I wrapped the line but it should not be wrapped):
You should give the root access.
mysql.exe -uroot -p1234 -s -N -e "SHOW DATABASES" |
for /F "usebackq" %D in (`findstr /V "information_schema performance_schema"`)
do mysqldump %D -uroot -p1234 > S:\Backup\MySQL\%D.sql
In a batch file you will need to escape % with an additional %, that is use %%D.

Run bat file in c# throws not recognized error

I wan to add some DNS records in c# program via a bat file so I have written these lines in bat file:
set servername=%1
set siteaddress=%2
"C:\Windows\System32\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
and I have written these lines in C#:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.FileName = General.DnsBatPath;
p.StartInfo.Arguments = string.Format("{0} {1}", General.DnsServerName, txtSiteAddress.Text);
p.Start();
p.WaitForExit();
I get this error "dnscmd.exe is not recognized as internal or external command..." but when I run bat file manually (outside of C#) all things are OK.
I changed my C# code to check what happened
Process.Start(#"C:\Windows\System32\dnscmd.exe");
I still get "not recognized ..." error.but I can see dnscmd.exe in "C:\Windows\System32".
I changed my C# code again to check another thing:
Process.Start(#"C:\Windows\System32\cmd.exe");
and after that CMD windows will be opened???
any idea?
In answer to your second question, you can always check the environmental variable PROCESSOR_ARCHITECTURE to see if it contains the number 64.
set servername=%1
set siteaddress=%2
if "%PROCESSOR_ARCHITECTURE%" equ "%PROCESSOR_ARCHITECTURE:64=%" (
REM 32bit
"C:\Windows\System32\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
) else (
REM 64bit
"%windir%\Sysnative\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
)
Possibly a more reliable method is to get it from the registry:
set servername=%1
set siteaddress=%2
for /f "tokens=3" %%x in ('reg Query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier') do (
set arch=%%x
)
if %!arch:~-2!%==64 (
set dnsPath=%windir%\Sysnative
) else (
SET dnsPath=C:\Windows\System32
)
"%dnsPath%\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
In my case I created a console application to run a batch file with some java command but was getting 'java' not recognized as an internal command error.
Took me few hours but the solution is straight forward. My server had JVM running on 64 bit so I changed the platform target to 64 bit.
x86 is 32 bit and x64 is 64 bit. Project properties are below:
Try this code:
ProcessInfo psi= new ProcessStartInfo("cmd.exe", string.Format("/c {0} {1} {2}", General.DnsBatPath, General.DnsServerName, txtSiteAddress.Text);
psi.UseShellExecute = false;
process = Process.Start(psi);
process.WaitForExit();
The /c parameter says that the given command should run and then cmd.exe should exit. For details, run cmd /? in windows console.
You can also try what happens when you set ShellExecute to true. Then the process should start the same way like a file is double-clicked in explorer. The disadvantage of shell execution is that if the user changed the .BAT file default application to (for example ) notepad, the file will not be executed but opened in notepad.
If you also want to redirect the console output, look here: Executing Batch File in C#

Extract All gz files inside a folder in C#

I am working on a application and need to extract the gz files inside a folder.
what I need is a c# script that can loop all gz files in a given folder and extract them into the same folder.
I know there are some libraries for this, But I could not able to get them work for gz, I got them working for zip though.
Or if there are any other solution for the same i.e if batch script can be created that can use WinRar command line utility to achieve the same. I don't know just an Idea if possible.
Note: I think I have to drop that second option- WinRar command is able to handle only RAR files.
Thanks
Try this as a batch file with winrar's "unrar" commandline freeware:
#REM ------- BEGIN demo.cmd ----------------
#setlocal
#echo off
set path="C:\Program Files\WinRAR\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
goto :eof
:do_extract
echo %1
mkdir %~1.extracted
pushd %~1.extracted
unrar e %1
popd
REM ------- END demo.cmd ------------------
Courtesy of: http://www.respower.com/page_tutorial_unrar
I can suggest something like below:
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
try
{
var files = from file in Directory.EnumerateFiles(#"c:\something",
"*.gz", SearchOption.AllDirectories)
select new
{
File = file,
};
foreach (var f in files)
{
Process.Start("c:\winrar.exe", f.File);
}
Console.WriteLine("{0} files found and extracted!",
files.Count().ToString());
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
NOTE: Please replace paths and winrar.exe parameters yourself with
correct one.
I got it solved. Thanks MichelZ for showing the way to go. I got the 7-zip command line version to done the trick for me.
#REM ------- BEGIN demo.cmd ----------------
#setlocal
#echo off
set path="C:\Program Files\7-Zip\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
for /F %%i in ('dir /s/b *.zip') do call :do_extract "%%i"
goto :eof
:do_extract
pushd %~dp1
7z e %1 -y
popd
REM ------- END demo.cmd ------------------
#setlocal
#echo off
set path="C:\Program Files\WinRAR\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
goto :eof
:do_extract
echo %1
mkdir %~1.extracted
pushd %~1.extracted
Winrar e %1
popd

Batch to copy files to another folder with breaks

I need a script, prefferably a windows batch or C# to do as following:
Show a prompt that first ask for the source folder,
then it should ask for the destination folder. At last, it shall ask how many files it should copy to the destination, from the source.
// We talk about aprox 100.000 files and they can be moved in random order.
After the process has been run, the program shall make a break of 10 minutes, then loop the process it was told to earlier, by previous answers to the prompt.
I've tried a little, but haven't found a solution. As far as i can see, XCOPY is unable to work around all these criterias.
Thanks in advance,
Mark
RoboCopy (the See also section might interest you as well) or
(more recent:) RichCopy (download)
You can use something like this:
string source = Console.ReadLine();
string destination = Console.ReadLine();
int numberOfFilesToCopy = int.Parse(Console.ReadLine());
DirectoryInfo di = new DirectoryInfo(source);
var files = di.GetFiles();
for(i=0;i < math.Max(files.Length, numberOfFilesToCopy);i++)
{
files[i].CopyTo(destination);
}
In C# using System.IO.File.Copy(sourceFileName,destFileName) followed by a System.IO.File.Delete(path) will do the "move" for you. You can create a simple console app that takes in the information you need and then does the work.
Have a look at the docs for System.IO.File for more info on File operations.
I'm not sure this fulfills all your requirements, but it may be useful to have a look at robocopy (robocopy /? in the command line).
Don't think I missed anything =D
#ECHO OFF
::User Prompts
SET /p source=Source Folder? Use format DRIVE:\PATH\ :
SET /p destination=Destination Folder? Use format DRIVE:\PATH\ :
SET /p count=How many files to copy? :
::Setup the Batch file to schedule
DIR /B "%source%">>"%userprofile%\batchtemp\source.BAT"
SET batchfile=%userprofile%\batchtemp\source.BAT
ECHO SETLOCAL ENABLEDELAYEDEXPANSION>>"%batchfile%"
ECHO FOR /F "USEBACKQ tokens=*" %%A IN ("%batchfile%") DO ( >>"%batchfile%"
ECHO COPY /Y "%%~fA" "%destination%\%%~nxA">>"%batchfile%"
ECHO SET /a count=!count!-1>>"%batchfile%"
ECHO IF %count% EQU 0 GOTO CLEANUP>>"%batchfile%"
ECHO )>>"%batchfile%"
ECHO :CLEANUP>>"%batchfile%"
ECHO ENDLOCAL>>"%batchfile%"
::Setup the scheduled task based on a future time in minutes.
REM Given that the job will run on the same day not overlapping a 24 hour day
FOR /F "tokens=1-3 delims=: " %%F IN ('time /t') DO (
SET hours=%%F
SET minutes=%%G
)
FOR /F "tokens=1-4 delims=/ " %%F IN ('date /t') DO (
SET day=%%F
SET thedate=%%G/%%H/%%I
)
SET /a minutes=%minutes%+10
IF %minutes% GRT 60 SET /a minutes=%minutes%-60 & SET /a hours=%hours%+1
SCHTASKS /Create /TR "%batchfile%" /ST %hours%:%minutes%:00 /MO ONCE /D %day% /SD "%thedate%" /ED "%thedate%" /TN "Copy Files"

Categories

Resources