LoginSignup
5
7

More than 5 years have passed since last update.

PowerShellでWindows Serviceを起動する。

Last updated at Posted at 2018-08-28

やりたいこと

Windowsで、サービス(Windows Service)をたくさん起動していると、だんだん動作が重くなってきます。
そこで、普段はサービスを停止しておき、必要な機会に手動で起動するようにします。

作るもの

Redmineの稼働に必要な4つのサービスをまとめて起動するスクリプトを作成します。

設計

  1. PowerShellでRedmineのサービスを起動するスクリプトを作成します。
  2. そのスクリプトをキックするbatファイル(Windows Batch File)を作成します。
  3. 「Redmineを使いたい」と思ったとき、batファイルを手動で実行し、Redmineを起動します。

ソースコード

サービス起動スクリプト

StartService_Redmine.ps1
### RedmineのServiceを全て起動する ###

# Redmineの稼働に必要なサービスの名前を配列で用意します。
$services = @("redmineApache","redmineMySQL","redmineThin1","redmineThin2")

# 上記サービスのうち、停止しているサービスを起動します。
foreach($service In Get-Service $services | Where-Object {$_.status -eq "stopped"}){
    Start-Service $service
}
# 現在のサービスの稼働状況をコンソール出力します。
# サービスの状態が全て「running」になっていれば、サービスの起動が成功しています。
echo "`r`n<<<  Redmine Service Status  >>>"
Get-Service $services | Format-Table -Property DisplayName, Status

スクリプトをキックするbatファイル

StartService_Redmine.bat
powershell -ExecutionPolicy RemoteSigned -File C:\Tool\StartService_Redmine.ps1
pause

使い方

1. 上記の2ファイルを以下のように配置します。

C:
└─Tool
    StartService_Redmine.ps1
    StartService_Redmine.bat

2. batファイルを管理者権限で実行します。
3. Redmineのサービスが起動されます。既にサービスが起動している場合は、何も起きません。

実行結果


C:\Tool>powershell -ExecutionPolicy RemoteSigned -File C:\Tool\StartService_Redmine.ps1

<<<  Redmine Service Status  >>>

DisplayName                        Status
-----------                        ------
redmineApache                     Running
redmineMySQL                      Running
redmineThin1 (managed by WinServ) Running
redmineThin2 (managed by WinServ) Running

C:\Tool>pause
続行するには何かキーを押してください . . .
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7