How to get all services autostarting on windows using batch? - windows

I need to list all services with a special name and a index and their autostart status. My thoughts were to use a batch and something like sc query but this doesn't give me the required information.
This is what I tried
sc query service
sc query service2
sc query service3
pause
Which command is suitable to list the start setting for a service?

I would rather use powershell, as sc query does not display startup type by default:
To see startup type by Display name, open cmd.exe and type (or paste):
powershell "Get-Service | select -property displayname,starttype"
or by actaul service name:
powershell "Get-Service | select -property name,starttype"
or you can create a powershell script by creating a file and give it a .ps1 extension and adding:
Get-Service | select -property name,starttype
or if you really want to use batch file, simply create a batch file with .cmd or .bat extension and add:
powershell "Get-Service | select -property name,starttype"
But, if you really are determined to use batch, you can run this which runs 2 for loops, one to get all the services, second will get the startup type of each. the set's are simply there to cleanup some unwanted items.
#echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2 delims=:" %%i in ('sc query ^|findstr "SERVICE_NAME"') do (
set serv=%%j
set serv=!serv: =!
for /f "tokens=1,2 delims=:" %%a in ('sc qc !serv! ^| findstr "START_TYPE"') do set type=%%b
set type=!type: =!
set type=!type:1=!
set type=!type:2=!
set type=!type:3=!
echo !serv! : !type!
)

Related

Setting both Name and GUID as a variable WMIC Product Get

I'm trying to create a basic script to uninstall an application across all our endpoints using cmd;
msiexec /quiet /norestart /uninstall {xxxx-xxx-xxx-xxxx-xxxxx}
Due to different versions, the same app may have multiple GUIDs on different endpoints
How can I run the wmic product get name,IdentifyingNumber cmdlet to search for a specific application and set it's GUID also to a variable?
wmic product get name,IdentifyingNumber"
IdentifyingNumber Name
{E8CAD3B5-7016-45AE-97DF-098B5C8D4AC8} App1
{90160000-008C-0000-1000-0000000FF1CE} App
I can find and match the Application to a variable, bit is struggling setting the GUID to a variable.
FOR /F "tokens=2 delims==" %%A IN ('WMIC product GET Name /VALUE ^| FIND /I "App1"') DO SET _application=%%A
ECHO Application: "%_application%"
Rem ECHO GUID:%_GUIDVALUE% //Matching Application GUID
Any help would appreciated
wmic has a few ugly habits that makes its output hard to parse *), but it's not impossible:
#echo off
setlocal
for /f %%a in ('wmic product where "name='Update for Windows 10 for x64-based Systems (KB4023057)'" get name^,IdentifyingNumber^|find "{"') do set "GUID=%%a"
echo %GUID%
*) especially
1. an ugly line ending of CRCRLF, which doesn't apply here, because we don't use a string "at the end of a line".
2. Some "empty" lines (not really empty - they contain a remaining CR), which we overcome with find "{" (we know, that char will be in the desired line).
A FOR /F loop can retrieve the GUID ID. Change the value of APPNAME to what you are seeking. How are you planning to hadle the case of multiple versions of an app being installed on the machine?
#ECHO OFF
SET "APPNAME=Windows SDK"
FOR /F "delims=" %%A IN ('powershell -NoLogo -NoProfile -Command ^
"Get-CimInstance -Class Win32_Product |" ^
"Where-Object { $_.Name -eq '%APPNAME%' } |" ^
"ForEach-Object { $_.IdentifyingNumber }"') DO (SET "APPID=%%A")
ECHO APPID is %APPID%

SC Query returns errors when used in BATCH FILE 'FOR' loop

Trying to use the following line of code in a Batch File FOR loop:
FOR /F "delims=" %%g IN ('sc query type=service ^| FIND /I "bthserv"') DO ( ECHO %%g )
The command in brackets works successfully when used from CMD Prompt.
However, in a FOR loop it simply returns:
[SC] EnumQueryServicesStatus:OpenService FAILED 123:
The filename, directory name, or volume label syntax is incorrect.
Is anyone familiar with this error and how to get the FOR loop to report all services with the specific, or similar name(s)?
[Edit /]
Even changing the command to this fails with the same message:
FOR /F "delims=" %%g IN ('sc query type^= service ^| FIND /I "bthserv"') DO ( ECHO %%g )
To begin with, your title is confusing because it uses queryex not query as in your code.
In addition to that query type=service is not valid, it should be query type= service, (the space after the = is required).
However, I'm a little confused also by your command, I'm unsure whether you're wanting to know if there's an active service named bthserv, or if there's an active service with a name containing the case insensitive string bthserv.
If you're wanting to know if there's an active service named bthserv, you should really just query it by name, query bthserv. From there you can simply use && and || for successful and unsuccessful commands, (I've just used Echo commands below).
Example:
#%__AppDir__%sc.exe query bthserv 1> NUL && (Echo bthserv is an installed service) || Echo bthserv is not an installed service
Alternatively, you can use the ErrorLevel.
Example:
#%__AppDir__%sc.exe query bthserv 1> NUL
#If ErrorLevel 1 (Echo bthserv is not an installed service)Else Echo bthserv is an installed service
If you're wanting to know if there's an active service with a name containing the case insensitive string bthserv, (not matching it), then the find command is okay.
However, when you run that command within a for-loop, the = character is treated as a delimiter by the cmd.exe instance, the command is passed to. You'll therefore need to escape it, using the caret, ^. In addition to that, if you want the matched service name to be captured, you'll need to select everything after the first token, using the default       and TAB delimiters.
Example:
#For /F "Tokens=1,*" %%G In ('%__AppDir__%sc.exe query type^= service ^| %__AppDir__%find.exe /I "bthserv"') Do #Echo %%H
However, you could also enclose the entire string passed to the cmd.exe instance in doublequotes, and not need to escape anything.
Example:
#For /F "Tokens=1,*" %%G In ('"%__AppDir__%sc.exe query type= service | %__AppDir__%find.exe /I "bthserv""') Do #Echo %%H

Take output of net group command and make it a list of users

I want to take the output of a "net group" command and parse it so that the group members are a list. I don't have access any of the actual domain utilities except for this. (So Get-ADGroupMember isn't an option)
net group /domain MyADGroup
The request will be processed at a domain controller for domain encana.com.
Group name MyADGroup
Comment Sccm Deployment
Members
-------------------------------------------------------------------------------
MemberA MemberB MemberC
.
.
.
MemberZ
The command completed successfully.
What I would like is a file that just has
MemberA
MemberB
MemberC
.
.
.
MemberZ
It also has to be automated so I can schedule it to run periodically.
What I have so far is this
In command prompt:
net group /domain MyADGroup |more +8 > output.txt
In power shell:
(Get-Content output.txt)|ForEach-Object { $_ -replace "The command completed successfully.", ""}| ForEach-Object { $_ -replace " ", "`n`r"}|Set-Content output2.txt
I can probably put these both into a batch file. The output file has a boat load of extra lines but the tool I am importing with will happily ignore them. I'd just like something a little more streamlined without the million extra lines.
I made a little script that first saves all groups to an "array" and then outputs them all. You can change it as your needs demand. Test it on WinServer 2003 and WinServer 2012. Hope it helps.
#echo off
setlocal EnableDelayedExpansion
set "count=0"
for /f "delims=* skip=4" %%i in ('net group') do (
set /a "count+=1"
set "groups[!count!]=%%i"
)
set /a "count-=1"
for /l %%i in (1,1,!count!) do (
echo(!groups[%%i]!
)

How Can I use the SC command in a Batch to convert the Service Display Name to the Service Name?

I have two parameters that are passed bye a service monitoring system. They are the Service Display Name and Machine name. I found the SC command can retrieve the service name via the GetKeyName. I have searched this site and others for a week and I'm stuck with how to extract output from that data to convert to a Service Start Command when the system is notified that a service is down.
I am needing to create the batch/script so that is can receive the Service Display Name as a parameter, determine the Service Name then issue the start command. This seems simple enough but when looking at the FOR command and taking into account the unknown number of tokens possible when looking at the FOR option because some service display names have multiple space breaks.
I'm looking for a solution that crosses multiple Window 2008/2003 systems without having to code for each specific set of services on that server or building a script that searcher all services when just one is stopper because there are services that are stopped for a reason and should not be restarted. This is why we have a central monitoring system that is using the display name/server name.
Thank you,
#echo off
setlocal enableextensions enabledelayedexpansion
rem Assume that everything will be fine
set "_exitCode=0"
rem Retrieve the service display name from parameters to batch file
rem If it contains spaces, "quote the service name"
set "_serviceDN=%~1"
rem Check parameters
if "%_serviceDN%"=="" (
echo ERROR: Usage is %~n0 "service display name"
set "_exitCode=1"
goto endProcess
)
rem Retrieve service name
set "_serviceName="
for /F "tokens=1,* delims== " %%a in (' sc GetKeyName "%_serviceDN%" ^| find "=" ') do (
set "_serviceName=%%b"
)
rem Check if we have retrieved the service name.
if "%_serviceName%"=="" (
echo ERROR: Service "%_serviceDN%" not found
set "_exitCode=2"
goto endProcess
)
rem Get service state
set "_serviceState="
for /f "skip=2 tokens=3 delims=: " %%f in ('sc query "%_serviceName%" ^| find ":" ') do (
if not defined _serviceState set "_serviceState=%%f"
)
rem Check if service is stopped and if necessary, start it
if "%_serviceState%"=="STOPPED" (
sc start "%_serviceName%" > nul 2>nul
set "_exitCode=!errorlevel!"
)
:endProcess
rem Clean and return exit code
endlocal & exit /b %_exitCode%
sc //machinename query | findstr DISPLAY_NAME | findstr service.name
Run from PowerShell

How to use a notepad file full of Server names to execute a command using batch?

Im using the sc command to query the services running on machines and was using code similar to:
sc \\"server_name" query | find "SERVICE_NAME" > servicelist2.txt
so basically all the server names are listed in this one notepad file. there are 100+ of them. it is too hard to manually put each name in and write 100+ lines of code. is there a way i can use batch itself to direct to the notepad file and iterate through all the server names written in it and then put them back into the "sc" command?
EDIT: Am on windows btw if it wasnt obvious. Using batch scripts for the above.
Assuming you have a file named servers.list in the same directory, you can use this:
for /f %%a in (%~d0%~p0servers.list) do (
ECHO %%a > servicelist2.txt
sc \\%%a query | find "SERVICE_NAME" > servicelist2.txt
)
you can do this with for /f :
OR /F "usebackq tokens=*" %%G IN ("C:\My Documents\servers.txt") DO (
sc \\%%G query | find "SERVICE_NAME" > servicelist2.txt
)
#echo off
echo Starting to list query services...
for /f %%i in (servieslist2.txt) do sc query %%i > output.txt
echo Finished query services...
The above will loop through each of the 100 service names specified in serviceslist2.txt and output it to a file called output.txt in the same directory as the batch file

Resources