Hướng dẫn lấy danh sách trạng thái và cách cấu hình Windows Services

Trong bài viết hôm nay này mình sẽ trình bày cách lấy danh sách trạng thái và cách cấu hình service áp dụng cho Windows và Windows Server. Đây là chủ đề tương đối phức tạp và hơi dài nhưng nó lại rất thú vị cho những bạn nào muốn tìm hiểu sâu về cấu hình hệ thống.

Chủ đề sẽ được trình bày bao gồm 3 phần chính sau đây:

  1. Lấy danh sách services
  2. Cấu hình services
  3. Tạo powershell csript và batch script

Dưới đây là chi tiết từng phần:

Phần 1: Lấy danh sách Services

1. Lấy danh sách của tất cả services đang được cài đặt

– Powershell

Copy
Get-Service | Select Name, DisplayName, Status, StartType

– Command prompt

Copy
Powershell -ExecutionPolicy Bypass -Command "& Get-Service | Select Name, DisplayName, Status, StartType"

2. Lấy danh sách của những services đang chạy (Running)

– Powershell

Copy
Get-Service | Where {$_.Status -eq 'Running'} | Select Name, DisplayName, StartType

– Command prompt

Copy
Powershell -ExecutionPolicy Bypass -Command "& Get-Service | Where {$_.Status -eq 'Running'} | Select Name, DisplayName, StartType"

3. Lấy danh sách của những service đã bị tắt (stopped)

– Powershell

Copy
Get-Service | Where {$_.Status -eq 'Stopped'}| Select Name, DisplayName, StartType

– Command prompt

Copy
Powershell -ExecutionPolicy Bypass -Command "& Get-Service | Where {$_.Status -eq 'Stopped'} | Select Name, DisplayName, StartType"

Phần 2: Cấu hình Services

1. Tắt service đang chạy. Cấu hình Service status Running

– Powershell

Copy
Stop-Service Name/DisplayName

Ví dụ tắt service có tên Security Center

Copy
Stop-Service wscsvc

Hoặc ghi

Copy
Stop-Service 'Security Center'

– Command prompt

Copy

Powershell -ExecutionPolicy Bypass -Command "& Stop-Service ServiceName/DisplayName"

Ví dụ tắt service có tên Security Center

Copy

Powershell -ExecutionPolicy Bypass -Command "& Stop-Service wscsvc"

Hoặc ghi

Copy

Powershell -ExecutionPolicy Bypass -Command "& Stop-Service 'Security Center'"

2. Bật service đã bị tắt. Cấu hình Service status Stopped

– Powershell

Copy

Start-Service Name/DisplayName

Ví dụ bật service có tên Security Center

Copy

Start-Service wscsvc

Hoặc ghi

Copy

Start-Service 'Security Center'

– Command prompt

Copy

Powershell -ExecutionPolicy Bypass -Command "& Start-Service ServiceName/DisplayName"

Ví dụ tắt service có tên Security Center

Copy

Powershell -ExecutionPolicy Bypass -Command "& Start-Service wscsvc"

Hoặc ghi

Copy

Powershell -ExecutionPolicy Bypass -Command "& Start-Service 'Security Center'"

3. Cấu hình Startup type

– Powershell

Copy

Set-Service Name/DisplayName -StartupType Automatic (Delayed Start)/Automatic/Manual/Disabled

Ví dụ cấu hình service Security Center có Startup type bằng Disabled

Copy

Set-Service wscsvc -StartupType Disabled

Hoặc ghi

Copy

Set-Service 'Security Center' -StartupType Disabled

– Command prompt

Copy

Powershell -ExecutionPolicy Bypass -Command "& Set-Service Name/DisplayName -StartupType Automatic (Delayed Start)/Automatic/Manual/Disabled"

Ví dụ cấu hình service Security Center có Startup type bằng Disabled

Copy

Powershell -ExecutionPolicy Bypass -Command "& Set-Service wscsvc -StartupType Disabled"

Hoặc ghi

Copy

Powershell -ExecutionPolicy Bypass -Command "& Set-Service 'Security Center' -StartupType Disabled"

4. Nâng cao

Bạn không thể bật lại service khi service này đang có Startup type bằng Disabled mà bạn phải dùng từng cú pháp như sau:

– Powershell

Copy

Get-WMIObject win32_service | Where {$_.Name -eq 'Name/DisplayName'}

Set-Service Name/DisplayName -StartupType Automatic (Delayed Start)/Automatic/Manual/Disabled

Start-Service Name/DisplayName

– Command prompt

Copy

Powershell -ExecutionPolicy Bypass -Command "& Get-WMIObject win32_service | Where {$_.Name -eq 'Name/DisplayName'}"

Powershell -ExecutionPolicy Bypass -Command "& Set-Service Name/DisplayName -StartupType Automatic (Delayed Start)/Automatic/Manual/Disabled"

Powershell -ExecutionPolicy Bypass -Command "& Start-Service Name/DisplayName"

Ví dụ nếu service Security Center có status stopped và startup type disabled nếu muốn bật trở lại bạn phải dùng cú pháp như sau:

– Powershell

Copy

Get-WMIObject win32_service | Where {$_.Name -eq 'wscsvc'}

Set-Service wscsvc -StartupType Automatic

Start-Service wscsvc

– Command prompt

Copy

Powershell -ExecutionPolicy Bypass -Command "& Get-WMIObject win32_service | Where {$_.Name -eq 'wscsvc'}"

Powershell -ExecutionPolicy Bypass -Command "& Set-Service wscsvc -StartupType Automatic"

Powershell -ExecutionPolicy Bypass -Command "& Start-Service wscsvc"

Phần 3: Tạo powershell csript và batch script

1. Tạo Powershell script

1.1. Tạo Script tắt service đang chạy Stop-Service.ps1

Soạn nội dung bên dưới vào notepad và lưu lại với tên ví dụ Stop-Service.ps1 định dạng All files và Econding-ANSI

Copy

# Stop-Service

# Created by Nguyen Tuan

# Fb.comkequaduongvodanh



If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {

Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $args" -Verb RunAs

Exit

}

$index=1

$Services=Get-Service | Where-Object {$_.Status -eq "Running"}

#return entire listing of applications

    Write-Host "ID`t Service Name"

    ""

foreach ($Service in $Services)

{

Write-Host " $index`t $($Service.DisplayName)"

$index++

}

   

    Do

    {

        ""

        $IDs=Read-Host -Prompt "For stop the service please select ID and press enter"

    }

    While($IDs -eq "")

   

#check whether input values are correct

try

{

[int[]]$IDs=$IDs -split ","

}

catch

{

Write-warning -Message "wrong ID"

}



foreach ($ID in $IDs)

{

#check id is in the range

if ($ID -ge 1 -and $ID -le $Services.count)

{

$ID--

#Disable each service

$ServiceName=$Services[$ID].Name



Get-WMIObject win32_service | Where-Object {$_.Name -eq "$ServiceName"}

            Set-Service $ServiceName -StartupType disabled

            Stop-Service $ServiceName

}

else

{

""

            Write-warning -Message "wrong ID"

            ""

            $confirmation=Read-Host -Prompt "Do you want to continue stopping the service? (Y/N)"

            if ($confirmation -eq 'y' ) {

                Do

                {

                    Write-Host ""

                    $IDs=Read-Host -Prompt "Select ID and press enter"

                }

                While($IDs -eq "")

                #check whether input values are correct

            try

            {

            [int[]]$IDs=$IDs -split ","

            }

            catch

            {

            Write-warning -Message "wrong ID"

            }



            foreach ($ID in $IDs)

            {

            #check id is in the range

            if ($ID -ge 1 -and $ID -le $Services.count)

            {

            $ID--

            #Disable each service

            $ServiceName=$Services[$ID].Name



            Get-WMIObject win32_service | Where-Object {$_.Name -eq "$ServiceName"}

                        Set-Service $ServiceName -StartupType disabled

                        Stop-Service $ServiceName

            }

                }

           

    }

            else

            {

                exit

            }

        }

    Pause

    }

Khi tạo xong chuột phải tập tin script vừa tạo chọn Run with Powershell

Nếu muốn tắt dịch vụ nào chọn ID ví dụ 81 nhấn enter

Trường hợp nếu chọn ID mà không có trong danh sách sẽ hiện thông báo và hỏi có muốn tiếp tục không? Nếu chọn Y chương trình sẽ tiếp tục nếu nhấn N sẽ thoát chương trình.

1.2. Tạo Script bật service đang bị tắt Start-Service.ps1

Soạn nội dung bên dưới vào notepad và lưu lại với tên ví dụ Start-Service.ps1 định dạng All files và Econding-ANSI

Copy

# Start-Service

# Created by Nguyen Tuan

# Fb.comkequaduongvodanh



If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {

Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $args" -Verb RunAs

Exit

}

$index=1

$Services=Get-Service | Where-Object {$_.Status -eq "Stopped"}

#return entire listing of applications

    Write-Host "ID`t Service Name"

    ""

foreach ($Service in $Services)

{

Write-Host " $index`t $($Service.DisplayName)"

$index++

}

   

    Do

    {

        ""

        $IDs=Read-Host -Prompt "For start the service please select ID and press enter"

    }

    While($IDs -eq "")

   

#check whether input values are correct

try

{

[int[]]$IDs=$IDs -split ","

}

catch

{

Write-warning -Message "wrong ID"

}



foreach ($ID in $IDs)

{

#check id is in the range

if ($ID -ge 1 -and $ID -le $Services.count)

{

$ID--

#Disable each service

$ServiceName=$Services[$ID].Name



Get-WMIObject win32_service | Where-Object {$_.Name -eq "$ServiceName"}

            Set-Service $ServiceName -StartupType automatic

            Start-Service $ServiceName

}

else

{

""

            Write-warning -Message "wrong ID"

            ""

            $confirmation=Read-Host -Prompt "Do you want to continue starting the service? (Y/N)"

            if ($confirmation -eq 'y' ) {

                Do

                {

                    Write-Host ""

                    $IDs=Read-Host -Prompt "Select ID and press enter"

                }

                While($IDs -eq "")

                #check whether input values are correct

            try

            {

            [int[]]$IDs=$IDs -split ","

            }

            catch

            {

            Write-warning -Message "wrong ID"

            }



            foreach ($ID in $IDs)

            {

            #check id is in the range

            if ($ID -ge 1 -and $ID -le $Services.count)

            {

            $ID--

            #Disable each service

            $ServiceName=$Services[$ID].Name



            Get-WMIObject win32_service | Where-Object {$_.Name -eq "$ServiceName"}

                        Set-Service $ServiceName -StartupType automatic

                        Start-Service $ServiceName

            }

                }

           

    }

            else

            {

                exit

            }

        }

    Pause

    }

Khi tạo xong chuột phải tập tin script vừa tạo chọn Run with Powershell

Nếu muốn tắt dịch vụ nào chọn ID ví dụ 139 nhấn enter

Trường hợp nếu chọn ID mà không có trong danh sách sẽ hiện thông báo và hỏi có muốn tiếp tục không? Nếu chọn Y chương trình sẽ tiếp tục nếu nhấn N sẽ thoát chương trình.

2. Tạo batch file

Bạn có thể tạo một tập tin batch kết hợp với cả hai tập tin powershell Start-Service.ps1 và Stop-Service.ps1. Soạn nội dung bên dưới vào notepad và lưu lại với tên ví dụ Service-Configuration.cmd định dạng All files và Econding-ANSI

Copy

@echo off

title Service Configuration

color 3f

cd /d %~dp0

:: --------------------------------------------------



:permission

>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"

if "%errorlevel%" NEQ "0" (

echo: Set UAC = CreateObject^("Shell.Application"^) > "%temp%getadmin.vbs"

echo: UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%getadmin.vbs"

"%temp%getadmin.vbs" & exit

)

if exist "%temp%getadmin.vbs" del /f /q "%temp%getadmin.vbs"

:: --------------------------------------------------



:Menu

cls

echo.

echo.Main menu

echo.

echo. ID Option

echo.

echo. A Start-Service

echo. B Stop-Service

echo.



choice /c ABC /n /m "For Start-Service press A, Stop-Service fress B, if not press C for exit the program: "

if %errorlevel% EQU 1 goto Start-Service

if %errorlevel% EQU 2 goto Stop-Service

if %errorlevel% EQU 3 goto Close

:: --------------------------------------------------



:Start-Service

cls

powershell.exe -ExecutionPolicy Bypass -Command "& '%~dp0Start-Service.ps1'"

cls

choice /c ABC /n /m "For continue Start-Service press A, press B return Main menu, if not press C for exit the program: "

if %errorlevel% EQU 1 goto Start-Service

if %errorlevel% EQU 2 goto Menu

if %errorlevel% EQU 3 goto Close

:: --------------------------------------------------



:Stop-Service

cls

powershell.exe -ExecutionPolicy Bypass -Command "& '%~dp0Stop-Service.ps1'"

cls

choice /c ABC /n /m "For continue Stop-Service press A, press B return Main menu, if not press C for exit the program: "

if %errorlevel% EQU 1 goto Stop-Service

if %errorlevel% EQU 2 goto Menu

if %errorlevel% EQU 3 goto Close

:: --------------------------------------------------



:Close

cls

echo.The program will be closed after 15 seconds.

echo.Thank you for using my program.

echo.Any details please contact me through: fb.com/kequaduongvodanh

echo.Goodbye and see you again!

timeout /t 15 /nobreak

exit

:: --------------------------------------------------

Khi tạo tâp tin batch bạn tạo mới một thư mục lấy tên ví dụ Service-configuration rồi lưu cả 3 tập tin Service-configuration.cmd, Start-Service.ps1, và Stop-Service.ps1 vào trong thư mục này

Khi tạo xong chuột có thể nhấp đúp chuột vào tập tin batch bắt đầu cấu hình service

Cuối cùng nếu bạn thấy code trên phức tạp quá bạn có thể tải code được mình tạo sẵn: https://app.box.com/s/qc4ij56qb18e8ybva7zkxqsj0w818ygp

View Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Published by
4 years ago