배치 또는 CMD 파일을 통해 서비스를 중지하고 시작 하시겠습니까?
-
02-07-2019 - |
문제
BAT 또는 CMD를 스크립트하여 오류 확인을 통해 서비스를 중지하고 안정적으로 시작할 수있는 방법 (또는 어떤 이유로 든 성공하지 않았 음을 알려주십시오)?
해결책
사용 SC
(서비스 제어) 명령, 그것은 단순한 것보다 더 많은 옵션을 제공합니다. start
& stop
.
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc <server> [command] [service name] ... The option <server> has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc <server> <command> <option> boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService
다른 팁
net start [serviceName]
그리고
net stop [serviceName]
그들이 성공했는지 또는 실패했는지 여부를 알려주십시오. 예를 들어
U:\>net stop alerter
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
배치 파일에서 실행되면 반환 코드의 오류표에 액세스 할 수 있습니다. 0은 성공을 나타냅니다. 더 높은 것은 실패를 나타냅니다.
박쥐 파일로서 error.bat
:
@echo off
net stop alerter
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause
출력은 다음과 같습니다.
U:\>error.bat
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
There was a problem
Press any key to continue . . .
반환 코드
- 0 = Success
- 1 = Not Supported
- 2 = Access Denied
- 3 = Dependent Services Running
- 4 = Invalid Service Control
- 5 = Service Cannot Accept Control
- 6 = Service Not Active
- 7 = Service Request Timeout
- 8 = Unknown Failure
- 9 = Path Not Found
- 10 = Service Already Running
- 11 = Service Database Locked
- 12 = Service Dependency Deleted
- 13 = Service Dependency Failure
- 14 = Service Disabled
- 15 = Service Logon Failure
- 16 = Service Marked For Deletion
- 17 = Service No Thread
- 18 = Status Circular Dependency
- 19 = Status Duplicate Name
- 20 = Status Invalid Name
- 21 = Status Invalid Parameter
- 22 = Status Invalid Service Account
- 23 = Status Service Exists
- 24 = Service Already Paused
편집 20.04.2015
반환 코드 :
NET 명령은 문서화 된 Win32_Service 클래스 리턴 코드 (서비스 활성화, 서비스 요청 시간 초과 등)를 반환하지 않으며 많은 오류에 대해서는 ErrorLevel 2를 반환합니다.
Net Start 명령을 사용한 다음 ErrorLevel Environment 변수 (예 :
net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%
면책 조항 : 나는 이것을 머리 꼭대기에서 썼지 만 그것이 효과가 있다고 생각합니다.
코드를 확인하는 대신이 기능도 작동합니다
net start "Apache tomcat" || goto ExitError
:End
exit 0
:ExitError
echo An error has occurred while starting the tomcat services
exit 1
나는 이것을 위해 내 개인 배치 파일을 만들었습니다. 내 것은 약간 다르지만 당신이 적합한대로 자유롭게 수정하십시오. 나는 지루하고 사람들이 결말, 시작, 중지 또는 자동 설정을 입력 할 수 있도록 간단한 방법을 만들고 싶었 기 때문에 조금 전에 이것을 만들었습니다. 이 BAT 파일은 단순히 서비스 이름을 입력하도록 요청하며 나머지는 귀하를 위해 수행합니다. 나는 그가 어떤 오류를 언급 한 것을 찾고 있다는 것을 몰랐다. 나는 그 부분을 잘못 읽어야했다. 일반적으로 이것은 라인 끝에 >> output.txt를 입력하여 수행 할 수 있습니다.
% var %는 다른 서비스를 시작/중지 할 때마다 BAT 파일을 수정하는 대신 사용자가 자신의 서비스를 입력 할 수있는 방법 일뿐입니다.
내가 틀렸다면 누구나 이것에 대해 나를 자유롭게 수정할 수 있습니다.
@echo off
set /p c= Would you like to start a service [Y/N]?
if /I "%c%" EQU "Y" goto :1
if /I "%c%" EQU "N" goto :2
:1
set /p var= Service name:
:2
set /p c= Would you like to stop a service [Y/N]?
if /I "%c%" EQU "Y" goto :3
if /I "%c%" EQU "N" goto :4
:3
set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
if /I "%c%" EQU "Y" goto :5
if /I "%c%" EQU "N" goto :6
:5
set /p var2= Service name:
:6
set /p c= Would you like to set a service to auto [Y/N]?
if /I "%c%" EQU "Y" goto :7
if /I "%c%" EQU "N" goto :10
:7
set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto
리턴 코드를 사용합니다 net start
그리고 net stop
나에게 가장 좋은 방법 인 것 같습니다. 이것을 살펴보십시오 : 순 시작 리턴 코드.
구문은 항상 나를 얻습니다 .... 그래서 ...
다음은 두 컴퓨터의 관리자 인 경우 원격 서비스 (다른 컴퓨터에서)를 죽이는 배치 파일에 라인을 추가하는 방법이 있습니다. 기계 이름은 UNC 형식 myserver를 따릅니다
sc \\ip.ip.ip.ip stop p4_1
이 경우 ... P4_1은 서비스 관리자 서비스 관리자의 속성을 볼 때 서비스 이름과 디스플레이 이름이었습니다. 서비스 이름을 사용해야합니다.
서비스 OPS Junkies의 경우 ... 이유 코드와 댓글을 추가하십시오! 예를 들어 '계획'과 같은 '4', '유지 보수를위한 서버 중지'와 동일합니다.
sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance
우리는 "Net Stop"이 서비스를 중단 할 것이라고 생각하고 싶습니다. 안타깝게도 현실은 그렇게 흑백이 아닙니다. 서비스를 중지하는 데 시간이 오래 걸리면 서비스가 중지되기 전에 명령이 반환됩니다. 그래도 ErrorLevel을 확인하지 않으면 알 수 없습니다.
솔루션은 루프가 중지 될 때까지 서비스 상태를 찾는 루프를 루프하는 것 같습니다.
하지만 다시 ...
첫 번째 서비스가 중지하는 데 시간이 오래 걸리는 것을보고 있습니다. 그러면 후속 서비스의 "순 정지"는 아무것도하지 않는 것으로 보입니다. 서비스 관리자의 서비스를 살펴보고 그 상태는 여전히 "시작된" - "중지"에 대한 변화가 없습니다. 그러나 SCM을 사용 하여이 두 번째 서비스를 수동으로 중지 할 수 있으며 3 ~ 4 초 안에 중지됩니다.
또는이 CMD로 원격 서비스를 시작할 수 있습니다. sc \\<computer> start <service>
방금 위의 Jonas의 예를 사용하고 0 ~ 24 개의 오류 레벨의 전체 목록을 만들었습니다. 다른 게시물이 맞습니다 net start
그리고 net stop
만 사용합니다 errorlevel
성공의 경우 0, 실패의 경우 2.
그러나 이것이 저에게 효과적인 것입니다.
net stop postgresql-9.1
if %errorlevel% == 2 echo Access Denied - Could not stop service
if %errorlevel% == 0 echo Service stopped successfully
echo Errorlevel: %errorlevel%
변화 stop
에게 start
반대로 작동합니다.
수동 서비스 재시작은 괜찮습니다 - Services.msc는 "다시 시작"버튼이 있지만 SC와 NET 명령에는 "다시 시작"스위치가 부족하고 CMD/BAT 파일에서 다시 시작되면 서비스가 중지되어 즉시 시작됩니다. 서비스가 아직 중지되지 않았으므로 오류가 발생합니다. 물건을 종료하는 데 시간이 필요합니다.
이것은 오류가 발생할 수 있습니다 : SC 정지 SC 시작
타임 아웃을 삽입하는 것이 좋습니다. 핑을 사용합니다 (1 초마다 핑 핑) : SC 중지 LocalHost -N 60 SC START
SC
서비스로 모든 것을 할 수 있습니다 ... 시작, 중지, 확인, 구성 등 ...
때로는 정지가 작동하지 않는다는 것을 찾을 수 있습니다 ..
내 sqlserver가 때때로 이것을합니다. 다음 명령을 사용하면 그것을 죽인다. 멈추지 않는 물건을 죽이려면 스크립트가 정말로 정말로 필요하다면. 나는 그것을 최후의 수단으로 할 것입니다
taskkill /pid [pid number] /f
다음은 Batch를 사용하여 시스템 복원을 시작하기위한 Windows 10 명령입니다.
sc config swprv start= Auto
당신은 또한 그 명령을 좋아할 수도 있습니다.
자동 시작 시스템 복원으로 레지스트리 값을 변경합니다
Reg Add "HKLM Software Microsoft Windows NT CurrentVersion SystemRestore" /v Disablesr /T Reg_dword /D 0 /F
시스템 복원 지점을 만듭니다
wmic.exe /namespace : root Default Path SystemRestore Call CreaterestorePoint "Djibe Saved Your PC", 100, 12
시스템 변경 디스크 사용을 복원합니다
vssadmin resize shadowstorage /for = c : /on = c : /maxsize = 10%
즐기다
C#에 Windows 서비스를 작성하고 있습니다. STOP/UNININSTALL/BUILD/Install/START 루프가 너무 피곤해졌습니다. 미니 스크립트를 썼습니다 reploy.bat
루프를 자동화하기 위해 Visual Studio 출력 디렉토리 (구축 된 서비스 실행 파일이있는)에 삭제했습니다.
이 3 개의 VAR을 설정합니다
servicename
: 이것은 Windows Service Control Panel (Services.msc)에 나타납니다.
slndir
: 솔루션 (.SLN) 파일이 포함 된 폴더 (전체 경로 아님)
binpath
: 빌드에서 서비스 실행 가능에 대한 전체 경로 (폴더 경로 아님)
참고 : 이것은 Visual Studio Developer Command Line에서 실행해야합니다. msbuild
일하도록 명령.
SET servicename="My Amazing Service"
SET slndir="C:dir\that\contains\sln\file"
SET binpath="C:path\to\service.exe"
SET currdir=%cd%
call net stop %servicename%
call sc delete %servicename%
cd %slndir%
call msbuild
cd %bindir%
call sc create %servicename% binpath=%binpath%
call net start %servicename%
cd %currdir%
아마도 이것은 누군가를 도울 것입니다 :)