スクリプト作成(switch文)、ポリシー変更、スクリプト実行(PowerShell)
Windowsにある便利なUtilityの一つに"PowerShell"があります。
作業規模が大きくなるにつれ、スクリプト等で作業をある程度自動化し、負担を軽減する必然が生まれてくると思います。
Unix系でのシェルスクリプトのような使い方が、Windowsでも出来たらいいな。これはそのための第一歩。
ということで、今回の作業は、
ーーーーーーーーーーーーーーーーーーーー
①スクリプト作成
②ポリシー変更
③スクリプト実行
ーーーーーーーーーーーーーーーーーーーー
①スクリプト作成
「オプションのあるコマンドみたいに使いたい」という要望があったとします。
switch文の出番です。
example.ps1 ※PowerShellスクリプトは拡張子を「.ps1」としなければいけません。
param ($x) $_op = " Options help : help date : Today's date xday : the remaining number of days to x'mas" switch -e ($x) help { Write-Output "This script is example." "" $_op ""} date { Get-Date } xday { Write-Output "`n" " X'mas is coming!" New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 25) | Format-List TotalDays } default { "`n" + " !!!You must add [help]!!!" + "`n" + "" }
※PowerShellでは、大文字・小文字を判別しません。
スクリプト内の改行は「|(パイプ)」を用います。
出力文字列内の改行は「`(バッククォート)n」です。
switch文により、多岐分岐が可能となっています。
"$x"は、スクリプト実行時に付与する引数を読み込みます。
.
②ポリシー変更
PowerShellでスクリプトを実行するにはポリシーの変更をしなければいけません。
ここで、現段階のポリシーを確認します。
PS C:\Windows\system32> Get-ExecutionPolicy
Restricted
既定値は"Restricted"となっています。
ポリシーを変更するため、"Set-ExecutionPolicy"コマンドの説明を読みます。
PS C:\Windows\system32> Get-Help -full Set-ExecutionPolicy | more
以下は、説明の抜粋です。
~・~・~・~・~・~
Windows Vista、Windows Server 2008、およびそれ以降のバージョンの Windows でこのコマンドを実行するには、コンピューターの Administrators グループのメンバーである場合でも、[管理者として実行] を指定して Windows PowerShell を起動する必要があります。
...
-
- Restricted: 構成ファイルの読み込みやスクリプトの実行を行いません。既定値は "Restricted" です。
-
- RemoteSigned: インターネットからダウンロードされたすべてのスクリプトおよび構成ファイルが、信頼された発行元によって署名されていることを要求します。
~・~・~・~・~・~
管理者権限でPowerShellを起動しなおし、"Set-ExecutionPolicy"コマンドでポリシーを"RemoteSigned"に変更します。
スクリプト実行を管理者で行う場合は以下のようになります。
PS C:\Windows\system32> Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
※一般ユーザで実行する場合、"-Scope"の引数を"LocalMachine"とします。
現在のポリシー設定一覧から変更を確認します。
PS C:\Windows\system32> Get-ExecutionPolicy -list
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine RemoteSigned
ここでは"CurrentUser"と"LocalMachine"の設定が変更されています。
③スクリプト実行
PowerShellでは、スクリプト実行に必要なコマンドはありません。
僕の場合
PS C:\Windows\system32> D:powershell\example.ps1
実行結果は以下のようになります。
PS C:\Windows\system32\D:powershell\example.ps1 !!!You must add [help]!!! PS C:\Windows\system32\D:powershell\example.ps1 help This script is example. Options help : help date : Today's date xday : the remaining number of days to x'mas PS C:\Windows\system32\D:powershell\example.ps1 date 2014年12月4日 22:43:28 PS C:\Windows\system32\D:powershell\example.ps1 xday X'mas is coming! TotalDays : 21
以上です。