I am trying to write a batch script to configure the recovery options (First failure, second failure, subsequent failure) i.e. SC failure for a custom server installed as a Windows service.
The problem is the Service Name of the Windows service will be different for each installation. The Service Name will be in format ProductName_ServerName_Version where the ProductName and Version will keep changing and ServerName will be constant. So I wanted to find the installed Windows Service and configure the Recovery options via a batch file which I can use for all installations since the ServerName part is constant and I want to lookup using that. I use the below script.
#echo off
set "service=TestSrv"
for /f "tokens=2 delims=: " %%# in ('sc query type^= service^|find /i "SERVICE_NAME:"^|findstr /i /b /c:"SERVICE_NAME: %service%"') do (
set "nservice=%%#"
)
echo %nservice%
sc failure "%nservice%" reset= 60000 actions= restart/60000/restart/60000/restart/60000
Here TestSrv is the ServerName and the above script only returns the Service Name correctly if it is starting with TestSrv. I want a %ServerName% lookup and how to achieve that.
Thanks in Advance.
If you're happy to accept that you will not have any other services within the system which have a name containing _TestSrv_ then you could use WMI to retrieve the service name.
For example, (please change TestSrv on line 1 and complete the last line as necessary):
#Set "ServerName=TestSrv"&Set "nservice="
#For /F Delims^= %%G In ('%__AppDir__%where.exe /R %__AppDir__% mof.xsl 2^>NUL'
)Do #For /F Tokens^=6Delims^=^" %%H In ('%__AppDir__%wbem\WMIC.exe Service^
Where "Name Like '%%[_]%ServerName%[_]%%'" Get Name /Format:"%%G" 2^>NUL'
)Do #Set "nservice=%%H"
#If Not Defined nservice Exit /B 1
#Echo %nservice%
#%__APPDIR__%sc.exe failure "%nservice%" etc…
Related
Trying to record a user client IP for a remote session. Currently have a little batch file recording logon times, and hostname. Need to also include the client IP address;
Currently using this;
reg query "HKEY_CURRENT_USER\Volatile Environment" /s > %temp%\IPINFO.txt
findstr /L ViewClient_IP_Address %temp%\IPINFO.txt > %temp%\IPRESULTS.txt
FOR /F “tokens=* delims= ” %%a in (%temp%\IPRESULTS.txt) do set IP=%%a
del %temp%\IPRESULTS.txt
set IP=%IP%
echo Login ,%Date%,%Time%,%computername%,%clientname%,%IP% >> Y:\%username%.csv
The registry key viewclient_ip_Address has the information I need, but the registry folder it sits within changes name each time so I'm having to export the whole directory and then filter for the key itself.
I just need to add the information from that IPRESULTS.txt into my end .csv file but struggling with writing it up.
Any help appreciated.
Is this what you're looking for? (The for-loop runs the command and parses it's output in memory)
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query "HKCU\Volatile Environment" /V ViewClient_IP_Address 2^>NUL^"')Do Set "IP=%%~I"
To find out more about how to use reg.exe with query, open up a Command Prompt window and enter reg query /?
If, as you've stated in your question, the required value and data is located under HKEY_CURRENT_USER\Volatile Environment but within a variable/unknown, subkey name, the help information should show you that you can use the /F option to locate your known value name, ViewClient_IP_Address, if you specify that the search is to locate a value using /V, it should retrieve the line you need.
For example, at the Command Prompt:
Reg Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V
Returns:
C:\Users\smith_ll>Reg Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Add
ress" /V
HKEY_CURRENT_USER\Volatile Environment\UnknownSubKey
ViewClient_IP_Address REG_SZ 192.168.1.15
End of search: 1 match(es) found.
You can then put that command into your for-loop, and pass its output through find.exe to isolate the line you need to parse. The underscore, for instance, looks unique to just the line you need. As we're already excluding any line beginning with H ,(with EOL=H), it will not match the End of search: 1 match(es) found. line:
Example:
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V 2^>NUL^|"%__AppDir__%find.exe" "_"^"')Do #Set "IP=%%~I"
If you don't like the super long line, you can split into more using the caret:
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query^
"HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V 2^>NUL^
^|"%__AppDir__%find.exe" "_"^"')Do #Set "IP=%%~I"
I have created a .cmd script that runs an uninstall on a specific piece of software as follows:
Title LEAP Office Accounting Client for 64-Bit Operating Systems
Echo LEAP Office Accounting Client for 64-Bit Operating Systems
WMIC Product Where "Name='LEAP Office Accounting Client for 64-Bit Operating Systems'" Call Uninstall /NoInteractive
This results in a remaining entry in the uninstall control panel and I have linked this to a registry key still remaining after the uninstall is called:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\InstallShield_{7BF4C2E2-96B9-4E84-B0FC-0C084B4068F1}
What can I add to my script, so it ensures this is removed either via the uninstall command or a separate delete command?
The last part of the registry key {7BF4C2E2-96B9-4E84-B0FC-0C084B4068F1} is unique (GUID). So I would need to find the correct registry key each time as the script is made to remove this software more than once.
Since {7BF4C2E2-96B9-4E84-B0FC-0C084B4068F1} is dynamic and will change based on installation, we can use /s /f "Key value data" to search the \Uninstall\ directory and its sub-keys for the key-values based on the value data of the DisplayName. To do this we can use a for statement along with REG QUERY to set a string with the path of the sub-directory the key belongs to.
To remove a key, we will want to use REG DELETE - reg delete /?
The Parameter /f will remove the entry without asking for confirmation.
#echo off
setlocal enableextensions disabledelayedexpansion
for /f "tokens=2 delims={}" %%a in ('
REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s /f "Put your programs DisplayName's value here"
') do REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{%%a}" /f
pause
This script will remove your key based off the value of DisplayName. You will want to search your registry for this value and insert it in the script. Be sure to run this script as administrator.
#echo off
setlocal
call :del_uninstall_key "LEAP Office Accounting Client for 64-Bit Operating Systems"
exit /b
:del_uninstall_key
setlocal
set "key="
for /f "tokens=*" %%A in ('
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
/s /f "%~1"
^|find "HKEY_LOCAL_MACHINE"
') do if not defined key set "key=%%~A"
if not defined key (
>&2 echo Reg key not found.
exit /b 1
)
reg delete "%key%" /f
exit /b
The label :del_uninstall_key is called with the displayname value.
reg query searches for the value and gets the 1st line of the
returned text which is expected to be the key. Use of find
limits the returned value to those with HKEY_LOCAL_MACHINE.
If the variable key is defined, the reg delete command will execute.
Use for /?, reg /? and exit /? for command help.
Here's an idea, based of the assumption that you can also determine the unique GUID from the same Win32_Product result.
#Echo Off
Set "GUID="
Set "RKEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
Set "PROD=LEAP Office Accounting Client for 64-Bit Operating Systems"
For /F "Tokens=2Delims==}" %%A In ('WMIC Product Where "Name='%PROD%'" Get IdentifyingNumber /Value 2^>Nul') Do Set "GUID=%%A}"
If Not Defined GUID Exit /B
WMIC Product Where "Name='%PROD%'" Call Uninstall
Reg Delete "%RKEY%\InstallShield_%GUID%" /F>Nul
I do think however that if you're accessing the registry, you could probably uninstall the software using the UnistallString value data from that location.You may even be able to parse the data for the switches it uses and optionally add you own to make the process less interactive.
I have found a solution to the issue avoiding the registry key removal
#Echo Off
Set "GUID="
Set "PROD=LEAP Office Accounting Client for 64-Bit Operating Systems"
For /F "Tokens=2Delims==}" %%A In ('WMIC Product Where "Name='%PROD%'" Get
IdentifyingNumber /Value 2^>Nul') Do Set "GUID=%%A}"
If Not Defined GUID Exit /B
WMIC Product Where "Name='%PROD%'">
"C:\Program Files (x86)\InstallShield Installation
Information\%GUID%\setup.exe" /m:uninstall
Running this installer correctly removes the key unlike the WMIC command although it does prompt the user. Is it possible to run the uninstall silently? I have attempted to add /quiet but that didn't work.
I have a .bat that I use to quickly query basic information from servers. After it gets the FQDN from DNS, I need to insert a "-r" (minus quotes) after the servername, but before the ".domain.com". The area that it will be added to the script is below -
for /f "delims=[] tokens=2" %%b in ('ping %servername% -n 1 ^| findstr "["') do (set thisip=%%b)
for /f "tokens=2" %%a in ('nslookup %thisip% ^| find /i "Name: "') do (set fqdnstat=%%a)
so how can I take the FQDN, which is set to fqdnstat, and modify it from -
server.domain.com
to server-r.domain.com ?
Edit - I guess I didn't really explain very well. I just need to insert text into a line of text, before a period. I need to take the following name: server.domain.com and edit it to read server-r.domain.com, using a command. The rest of the script above is context for the issue. The fqdnstat is the variable that I use to for the Fully Qualified Domain Name.
I am afraid I don't really understand your concern, but this Batch file may help you:
#echo off
set fqdnstat=server.domain.com
echo Before: "%fqdnstat%"
for /F "tokens=1* delims=." %%a in ("%fqdnstat%") do set "fqdnstat=%%a-r.%%b"
echo After: "%fqdnstat%"
set servername=%servername:.domain.com=-r.domain.com%
Presumably above the two lines you've put, but I'm not sure what the goal is, so maybe not.
I've got a script I'm working on that checks a text file to match pc name, then match a port number. That then info gets injected into an ini file for specific settings. I'm using this in a Citrix setup.
Here's a piece of my test script:
:Set_Client_Name
for /f "tokens=1-3" %%1 in ('query session %USERNAME% ^| find ">"') do set ses_num=%%3
for /f "tokens=1-3" %%1 in ('reg query "HKCU\Volatile Environment\%ses_num%" /v CLIENTNAME') do set client_name=%%3
:CHECK
findstr /i /c:%client_name% "C:\star.txt"
IF ERRORLEVEL 1 goto end
:CREATE
set port=
set parse=findstr /i /c:%client_name% "C:\star.txt"
for /f "tokens=2 delims=," %%a in ('"%parse%"') do (set port=%%a)
for /F %%G IN C:\hbowem32.ini DO (
findstr /i /c:"[0_Network Def.]"
echo Local Port=%port% >> C:\hbowem32.ini
)
:END
`
The :Set_Client_Name, :Check, and :Create portions work correctly.
I'm just doing something wrong with the next piece, and I'm not sure what it is.
I need to find the string [0_Network Def.] in the hbowem32.ini, and right after that, inject the %port% variable. I can get it to add to the ini file at the bottom, but I need it to be able to inject this in the correct section of the ini.
I'm also wanting to add a section that pulls the client IP address (this is a Terminal Services/Citrix server) so it can be injected into a different ini/section. I can't seem to get it to pull the user's workstation IP address. It only pulls the IP address of the Citrix server. I no longer have this section in my test script above, but figured I'd go ahead and ask since I'm here and already stuck.
Thanks for any insight and advice.
Add the /L switch to the FINDSTR so that you are dealing with Literals not (default) Regular expressions.
Is there a way for using a batch file to find the default browser on my computer?
Simply use
start www.google.com
See here
If you're looking for a Windows .bat solution, this should work on Windows 2000 and later:
reg QUERY HKEY_CLASSES_ROOT\htmlfile\shell\open\command /ve
Result (on my Windows machine)
HKEY_CLASSES_ROOT\htmlfile\shell\open\command
(Default) REG_SZ "C:\Program Files (x86)\Internet Explorer\iexplore.exe" -nohome
See the REG.EXE help for more information:
REG /?
It is impossible to do this 100% correct in a batch file since the default command could come from a COM object and not a string in the registry (MayChangeDefaultMenu will force IContextMenu to be called for double-clicks and could change the default action)
Here is some code that tries to do the right thing (The fallback verb is open, it really should be the first subkey, but I did not feel like dealing with that)
#echo off
setlocal ENABLEEXTENSIONS
set progid=htmlfile&set verb=open&set browsercmd=
FOR /F "skip=2 tokens=2 delims=_" %%a IN ('2^>nul REG QUERY "HKCR\.html" /ve^|find /V ""^|find /V "HKEY_"') DO FOR /F "tokens=1,*" %%b IN ("%%~a") DO if not "%%~c"=="" set progid=%%~c
FOR /F "skip=2 tokens=2 delims=_" %%a IN ('2^>nul REG QUERY "HKCR\%progid%\shell" /ve^|find /V ""^|find /V "HKEY_"') DO FOR /F "tokens=1,*" %%b IN ("%%~a") DO if not "%%~c"=="" set verb=%%~c
FOR /F "skip=2 tokens=2 delims=_" %%a IN ('2^>nul REG QUERY "HKCR\%progid%\shell\%verb%\command" /ve^|find /V ""^|find /V "HKEY_"') DO FOR /F "tokens=1,*" %%b IN ("%%~a") DO if not "%%~c"=="" set browsercmd=%%c
echo.DefaultBrowser=%browsercmd%
This code probably has problems, but at least it tries to find the correct verb. You also have to deal with the fact that the returned string could contain "%1".
If all you really want to do is open a URL, all you need is start http://example.com
If you want to open the browser, but not a specific URL, a ugly hack like start "" http://about:blank might just work.
I hope this helps someone. I needed to start the default browser with a html file.
#echo off
setlocal
rem setup a default browser in case we fail
set default_browser=C:\Program Files\Internet Explorer\iexplore.exe
rem look in the HKEY_CLASSES_ROOT\htmlfile\shell\open\command registry for the default browser
for /f "tokens=*" %%a in ('REG QUERY HKEY_CLASSES_ROOT\htmlfile\shell\open\command /ve ^| FIND /i "default"') do (
set input=%%a
)
setlocal enableDelayedExpansion
rem parse the input field looking for the second token
for /f tokens^=^2^ eol^=^"^ delims^=^" %%a in ("!input!") do set browser=%%a
setlocal disableDelayedExpansion
rem this may not be needed, check if reg returned a real file, if not unset browser
if not "%browser%" == "" if not exist "%browser%" set browser=
if "%browser%"=="" set browser=%default_browser%
"%browser%" index.html
endlocal
This code will set the Environment variable browser to FirefoxURL which gives you a good indicator:
#ECHO OFF
REG QUERY HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice > browser.txt
FOR /F "skip=2 tokens=*" %%G IN (browser.txt) DO ( SET browser=%%G )
SET browser=%browser:~20%
ECHO Is: %browser%
It works by querying the registry to a text file then skipping the first two lines (useless for your purposes), then taking the text that starts at the 20th character of te remaining line. Which gives you FirefoxURL
Andy E's answer does not seem to work for me, it opens IE instead of Chrome.
But, if I use http instead of htmlfile it does. Like this.
reg QUERY HKEY_CLASSES_ROOT\http\shell\open\command /ve
bubble's answer has some caveats.
This is what works in much more cases for me:
start "" explorer "protocol://your.complicated/url?foo=bar"
The only thing you have to escape is a double quote, and you escape it by typing it once more.
Works at least for protocols http://, https:// and file:// (without query string). Doesn't work for ftp:// URLs (it opens them as a network drive).
Fail cases of the accepted answer
First, the webpage has to start with www.
rem Works
start www.google.com
rem FAILS!
start google.com
The system cannot find the file google.com
rem FAILS!
start translate.google.com
The system cannot find the file translate.google.com
This can be fixed by prepending http://
rem Works
start http://google.com
rem Works even for file:// protocol
start file://C:/test/main.html
rem Works - you can even pass QSA
start http://google.com?foo=bar
rem FAILS! outch, you have to escape ampersands
start http://google.com?foo=bar&baz=baz
'baz' is not recognized as an internal or external command, operable program or batch file.
rem FAILS! but QSA only works for http/s URLs; for file:// protocol, it is ignored
start file://D:/Programování/lumix-link/Control.html?foo=bar
rem opens file://D:/Programování/lumix-link/Control.html
One might e.g. think of enclosing the webpage in double quotes (to avoid misinterpretation of some characters). Then it fails and instead tries to open another CMD.exe with the given string as name:
rem FAILS!
start "http://google.com"
Okay, this is not a bug, just a mislead. This is the expected behavior. Let's fix it:
rem Works
start "" "http://google.com"
rem FAILS!
start "" "google.com"
The system cannot find the file google.com.
So we really have to provide an executable that should be launched. You can see the super-long answers here that succeed better or worse in getting the path to the default browser. But what's much simpler and bullet-proof is to use explorer to launch the webpage. But since explorer decides on what app to launch based on the protocol, you have to use the protocol prefix. And that's it!
rem FAILS!
rem start "" explorer "google.com"
rem Works
rem start "" explorer "http://google.com"
rem Works
rem start "" explorer "http://google.com?foo=bar"
rem FAILS! QSA still not supported on file:// URLs
rem start "" explorer "file://C:/test/main.html?foo=bar"
Thank you, #Rob.
#Rob's answer is close, but it still only pulls the ProgId. This one will set the browser name as reported by the ProgId (not always what you expect) in the browser variable, the specific verb used as browserverb, and the cmd path as browsercmd:
setlocal enableDelayedExpansion
:: parse the ProgId
FOR /F "usebackq tokens=1,2,* delims==" %%A IN (`REG QUERY "HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice" /v ProgId 2^>NUL ^| more +2`) DO (
SET browserstub=%%C
:: parse for Class information
FOR /F "usebackq tokens=1,2,* delims==" %%R IN (`REG QUERY "HKCR\!browserstub!" /v AppUserModelId 2^>NUL`) DO SET "browser=%%T"
FOR /F "usebackq tokens=1,2,* delims==" %%R IN (`REG QUERY "HKCR\!browserstub!\shell" /ve 2^>NUL`) DO SET "browserverb=%%T"
FOR /F "usebackq tokens=1,2,* delims==" %%R IN (`REG QUERY "HKCR\!browserstub!\shell\!browserverb!\command" /ve 2^>NUL`) DO SET "browsercmd=%%T"
)
:: display results
SET browser
This is the method i am using to open a browser window
start /REALTIME "~\iexplore.exe" "http://192.168.0.1"
Which opens internet explorer at the logon screen of the router, i have tested it on win 7 and win 10 and it works well. What i have gotten from this forum is that opening any website from a batch file or cmd window will use the default browser.
which works well here on win 10
start /REALTIME "" "http://192.168.0.1"
This also works well.
start /ABOVENORMAL /SEPARATE "" "http://192.168.0.1"
which allows the browser priority over other apps using cpu and also runs in a separate memory space which i have found to cause a lot of work for intruders of sorts.
The empty (path) "" need to be there other wise it just opens another cmd window.