「[[マイクロソフト系技術情報 Wiki>http://techinfoofmicrosofttech.osscons.jp/]]」は、「[[Open棟梁Project>https://github.com/OpenTouryoProject/]]」,「[[OSSコンソーシアム .NET開発基盤部会>https://www.osscons.jp/dotNetDevelopmentInfrastructure/]]」によって運営されています。 -戻る --[[シェル]] --[[スクリプティング]] * 目次 [#a80353b5] #contents * 概要 [#l26e6c22] PowerShell のトピックを纏めています。 *特徴 [#r9b4dbd1] -Windows PowerShell - Wikipedia~ https://ja.wikipedia.org/wiki/Windows_PowerShell **[[オブジェクトベースのシェル>PowerShell オブジェクトベースのシェル]] [#h3946920] **Cmd.exeを置き換えるものではない [#l34fd736] 別物として使用する必要がある。 -例えば、 --ipconfig などのコマンドを実行すると、おなじみの出力が表示される。 --netshなどのコマンドを実行して設定するぐらいはPowerShellで実行可能。 -ただし、Cmd.exeを置き換えるものではない。 --標準出力をテキストとしてパイプできない。 --[[BAT]]の構文を使用できない。 * 環境構築 [#ibc8b5fb] PowerShell の各バージョンは、以下のOSに添付されているか、別途ダウンロードできます。 -新しいOSほど、新しいPowerShellに対応します。 -また、旧OSでは、新しいPowerShellのサポートがありません。 -PowerShellのバージョンに依存しそうな場合は、対象とするOSが何か確認ください。 **Windows PC [#z348c9a8] |--Windows PC-- | PowerShell 1.0 | PowerShell 2.0 | PowerShell 3.0 |PowerShell 4.0 |h |Windows XP SP2 | PS1 | | n/a | n/a | |Windows XP SP3 | PS1 | PS2 | n/a | n/a | |Windows Vista SP1 | PS1 | PS2 | n/a | n/a | |Windows Vista SP2 | PS1 | PS2 | n/a | n/a | |Windows 7 | | OS添付 | n/a | n/a | |Windows 7 SP1 | | OS添付 | PS3 | PS4 | |Windows 8 | | OS添付(*1) | OS添付 | PS4 | |Windows 8.1 | | OS添付(*1) | | OS添付 | (*1) Windows 8/8.1 の PowerShell 2.0 スクリプトは、PowerShell 4.0 の下位互換で実行できます。~ PowerShell を -version 2.0 指定で実行する場合は .NET Framework 3.5 をインストールすると有効になります。~ ~ **Windows Server [#u0f2f33a] |--Windows Server-- | PowerShell 1.0 | PowerShell 2.0 | PowerShell 3.0 | PowerShell 4.0 |h |Windows Server 2003R2 | PS1 | | n/a | n/a | |Windows Server 2003 SP2 | PS1 | PS2 | n/a | n/a | |Windows Server 2008 SP1 | OS添付 | PS2 | PS3 | n/a | |Windows Server 2008 SP2 | OS添付 | PS2 | PS3 | n/a | |Windows Server 2008R2 SP1 | | OS添付 | PS3 | PS4 | |Windows Server 2012 | | OS添付(*1) | OS添付 | PS4 | |Windows Server 2012 R2 | | OS添付(*1) | | OS添付 | (*1) Windows Server 2012/2012R2 の PowerShell 2.0 スクリプトは、PowerShell 4.0 の下位互換で実行できます。~ PowerShell を -version 2.0 指定で実行する場合は .NET Framework 3.5 をインストールすると有効になります。~ **バージョン [#uaff435c] ***PS1 [#k0e3e8a8] -http://support.microsoft.com/kb/926140 (XP/2003用) -http://support.microsoft.com/kb/928439 (Vista用) ***PS2 [#gc3cf7d4] -http://support.microsoft.com/kb/926139 (英語版) -http://support.microsoft.com/kb/968929 (日本語版) ***PS3 [#de124eac] http://www.microsoft.com/en-us/download/details.aspx?id=34595 (現在、英語版) ***PS4 Preview [#sc27693f] http://www.microsoft.com/en-us/download/details.aspx?id=39347 (現在、英語版) *基本 [#g002dfa5] ** 実行方法 [#v29d2093] -スタートメニューからPowerShell コマンドプロンプトを開いても、 -コマンドプロンプトから PowerShell.exe を実行しても、 PowerShell を手で([[シェル]]として)逐次実行できます。 ** 変数 [#n585d270] ***定義 [#y9071564] 変数は $ で始まる 英数字記号 の名前を使用します。~ 後述の様に スコープ($global:, $script:) をつけることも出来ます。~ 下の様に ${ } で囲むと、名前にスペースを含むこともできますが、混乱やスペルミスの元になりやすいので避けましょう。 PS E:\temp> ${var test 1} = 123 PS E:\temp> $a = ${var test 1} + "123" PS E:\temp> $a 246 PS E:\temp> 未初期化の初期状態は $null と同じです。~ 文脈によっては 0 や "" (空文字列) と解釈されます。 PS E:\temp> $var001 PS E:\temp> $var001 -eq 0 False PS E:\temp> $var001 -eq $null True PS E:\temp> $a1 = $var001 + 2 PS E:\temp> $a1 2 PS E:\temp> $a1 = $var001 + "abc" PS E:\temp> $a1 abc PS E:\temp> 上の例では、変数 $var001 は未初期化なので、 $null と同じです。~ 変数をそのまま出力すると、$null は 何も表示されません。~ また、 -eq 比較演算子を使って、 0 や $null と比較すると、$null であることが判断できます。~ ~ 未初期化変数は、数値を足し算した場合は、0 が、文字列を連結した場合は、"" が、それぞれ仮定されます。 Set-StrictMode を使用すると、未初期化変数を参照する際にエラーとして検出できます。 PS E:\temp> Set-StrictMode -Version 1.0 PS E:\temp> $a1 = $var001 + 2 変数 '$var001' は、設定されていないために取得できません。 発生場所 行:1 文字:14 + $a1 = $var001 <<<< + 2 + CategoryInfo : InvalidOperation: (var001:Token) []、RuntimeExcep tion + FullyQualifiedErrorId : VariableIsUndefined PS E:\temp> ***スコープ [#y88b36f0] PowerShellの変数は、変数を使用する場所がスコープの範囲になります。 -functionの中、 -PowerShellモジュールの中、 -[[.ps1スクリプトの中>PowerShellのPS1ファイルの作成と実行#d923bb09]]、 などがスコープの境界になります。 ***参考 [#b14a0b57] -変数について --Windows Powershell 変数の機能~ http://lab.technet.microsoft.com/ja-jp/magazine/cc162486 -Set-StrictModeについて、 --「get-help Set-StrictMode」 --または、下のページ~ ---Set-StrictMode~ http://technet.microsoft.com/ja-jp/library/dd347614.aspx -変数のスコープについて、 --「get-help about_Scopes」 --または、下のページ~ ---about_Scopes~ http://technet.microsoft.com/ja-jp/library/dd315289.aspx ** if文 [#b3a3550b] if文は、下の様に -で始まる比較演算子を使います。 $var1 = sub2 $arg1 $arg2 if ( ( $var1 -eq 1 ) -or ( $var1 -gt 10 ) ) { ... } 条件のANDやORは、 それぞれを ( ... )で囲んで -and や -or で結びます。 論理のANDやORによるビット演算は、 -band や -bor の -b で始まる演算子を使います。 $file = get-item $dirname if ( $file.Attributes -band [System.IO.FileAttributes]::Directory ) { ... } bit演算結果が0以外の場合は、真 とみなされます。 if文の演算子の詳細は、powershellコマンドプロンプトの中で 「get-help about_Comparison_Operators」を参照してください。 ** 配列 [#gfd0e13d] 配列は、以下の形式で定義できます。 $array1 = @() $array2 = @(1,2,3) $array3 = 1,2,3 ( ) で囲まなくても、「,」で並べると、配列になります。~ コマンドや関数への引数を「,」で区切った場合も配列になるので、書き間違いに注意。~ $ret1 = sub1 2,3,4 # これは @(2,3,4) の配列で引数1つ $ret2 = sub1 2 3 4 # これは 引数3つ $ret3 = sub1 2,3 4 # これは @(2,3)の配列1つと 数値4 の 引数2つ また、配列の添え字は、$変数名[添え字] で参照します。~ 添え字に 負数 を指定すると、配列の末尾からの添え字を指定できます。~ $var1 = $array2[1] # 上の $array2 から 2 を取り出す $var2 = $array2[-1] # 上の $array2 から 3 を取り出す 配列について詳しくは、 PowerShellコマンドプロンプトで「get-help about_array」 を参照ください。 ** 拡張 [#b2d2b641] ***[[PSSnapin と Module>PowerShell Module vs Snapin]] [#oe30e413] ***[[PowerShellのPS1ファイルの作成と実行]] [#j25cd86b] ***[[PowerShell Cmdletの作り方]] [#ofbc761c] ***[[PowerShell プロバイダとドライブ]] [#yfe81b74] **情報の探し方 [#g2df6a75] ***Get-Command [#ec95c735] コマンドを探すには、下の様に、コマンド名の一部を*で省略して Get-Command を実行します。~ Get-Command *event ***get-help コマンド名 [#qdaf661d] -コマンドの説明や引数の構文を確認するには、get-help を使います。 get-help get-childitem -Windows Server 2012 では、 ヘルプの文章が online から取得する様になっていることがあります。 --必要に応じて 「get-help コマンド -online」のようにするか、 --表示されたURLをブラウザで表示して構文を確認ください。 ***Get-Member [#zc03dfb2] オブジェクトのメンバーやプロパティを確認するには、~ 下の様にコマンドの出力を パイプ で Get-Member に渡します。 Get-ChildItem | Get-Member ***Get-WmiObject [#s6ff6a6b] Get-WmiObject -List -WMI オブジェクトの取得 (Get-WmiObject) | Microsoft Docs~ https://docs.microsoft.com/ja-jp/powershell/scripting/getting-started/cookbooks/getting-wmi-objects--get-wmiobject- * 勘所1 [#x44711fb] ** エラー処理 [#bb1a74a1] .ps1ファイルの中でエラーが発生すると、既定では、~ 赤文字でエラー表示されて、そのまま次の行が実行されます。~ エラーを処理するには、下のいずれか必要です。 *** -ErrorAction (省略形は -EA) オプション [#zfec5ccb] Trap { エラー処理 } コマンド .... -ErrorAction "stop" *** try/catch で囲む [#ya21a9c5] $ErrorActionPreference = "stop" try { コマンド .... } catch [Exception] { エラー処理 } try/catch の例は、上の [[ps_test.ps1>#k5dc1c30]] を参照ください。~ ***その他 [#w6126274] その他の例、説明は、以下のサイトも参照ください。~ -Windows PowerShell の –ErrorAction (–EA) を使用してエラーをトラップする~ http://technet.microsoft.com/ja-jp/subscriptions/2009.01.windowspowershell **デバッグ [#gae834c7] debugは、 debug用print文、 デバッグ用環境、を使ってデバッグできます。 ***debug用print文 [#l40d8762] debug用print文は、 スクリプトの中に write-host コマンドを埋め込む方法です。~ write-host を使用すると、 引数に指定した値が PowerShellコマンドプロンプトへ出力されます。~ (write-output は、 関数の出力になるので、debug用には使わないでください。) ***デバッグ用環境 [#u0722db3] デバッグ用環境 は、 PowerShell ISE (Integrated Scripting Environment) 環境が使用できます。~ PowerShell ISE を使用すると、ブレークポイントの設定、ステップ実行が、メニュー操作で行えます。 -PowerShell ISE は、下の情報を参照ください。 --Windows PowerShell ISE の概要~ http://technet.microsoft.com/ja-jp/library/dd367962%28v=vs.85%29.aspx --Windows PowerShell ISE でスクリプトをデバッグする方法~ http://technet.microsoft.com/ja-jp/library/dd819480.aspx -PowerShell ISE でのデバッグ操作の画面例は、下を参照ください。 --Use the Debugger in the Windows PowerShell ISE~ http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/24/use-the-debugger-in-the-windows-powershell-ise.aspx ***debug用のコマンド [#b5352391] 通常の PowerShellコマンドプロンプトのままでも、~ Set-PsBreakpoint 等の debug用のコマンドを使用して、1行ずつステップ実行することも出来ます。 -デバッグ例 PS E:\temp> Set-PsBreakpoint -command .\ps_scope1.ps1 ID Script Line Command Variable Action -- ------ ---- ------- -------- ------ 0 .\ps_scope1.ps1 PS E:\temp> .\ps_scope1.ps1 デバッグ モードを開始します。ヘルプを表示するには、h または ? を使用してください。 ヒット '.\ps_scope1.ps1' のコマンドのブレークポイント .\ps_scope1.ps1 [DBG]: PS E:\temp>>> s ps_scope1.ps1:2 $global:g1 = "0" [DBG]: PS E:\temp>>> s ps_scope1.ps1:3 $script:s1 = "0" [DBG]: PS E:\temp>>> s ps_scope1.ps1:4 $v1 = "0" [DBG]: PS E:\temp>>> s ps_scope1.ps1:6 write-host "before : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2" [DBG]: PS E:\temp>>> s before : g1=0 s1=0 v1=0 v2= ps_scope1.ps1:8 function test1 { [DBG]: PS E:\temp>>> s ps_scope1.ps1:17 test1 [DBG]: PS E:\temp>>> s ps_scope1.ps1:9 write-host "start test1 : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2" [DBG]: PS E:\temp>>> -Set-PsBreakpoint を使ったデバッグ方法~ 「about_Debuggers」 および下のページを参照ください。 --ブレークポイントを設定、削除、無効化、有効化、および一覧表示する方法~ http://technet.microsoft.com/ja-jp/library/dd819519.aspx~ --about_Debuggers~ http://technet.microsoft.com/ja-jp/library/dd347652.aspx -変数が変更されたときに停止するようにブレークポイントを設定することもできます。~ 手順の例は、下を参照ください。~ --Use the PowerShell Debugger to Troubleshoot Scripts~ http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/22/use-the-powershell-debugger-to-troubleshoot-scripts.aspx * 勘所2 [#g3eae783] **Windows Server 2012以降の管理 [#o387c11c] Windows Server 2012以降は管理コンソールの裏はPowerShellコマンドレットになる。 -現行、管理コンソールはCUI → [[WMI]]で構成されている。 -コマンドレットの裏は.NET、その裏は[[WMI]](Windows Management Instrumentation)。 -MS的には、今後PowerShell押し。 --コマンドレットは<操作>-<ターゲット>の名称ルールに準拠。 --[[WSH>VBS]]([[VBS]]とJS)は凍結される。 --[[BAT]]は今後もエンハンス有り。 --[[PowerShell]]から[[BAT]]や、[[WSH>VBS]]を実行可能。 --また、Get-WmiObjectで[[WMI]]も実行可能。 --難しい事をやるなら、まだ[[WMI]]が必要。 -windows management framework 3.0 RC(Win2008 sp2以降にインストール可能)~ 標準化:[[PowerShell]] → WS-Management → CIMOM、SMI-S(WS-Management 以下から他のPFも管理できる) --Windows PowerShell 3.0 --WinRM --[[WMI]](アップデート) --Windows PowerShell Web Service(WPWS) --Server Manager CIM Provider **リモート、非同期ジョブ、ワークフロー [#x461eac9] ***[[リモート>PowerShellをリモートコンピューターで実行]] [#n36803b1] -invoke-command マシン名やSessionを指定 -scriptblock { ・・・コード・・・ } -invoke-command マシン名やSessionを指定 -filepath ファイルパス # Sessionを指定すれば処理中のジョブ等に再接続することも可能。 ***非同期ジョブ [#j3087585] -start-job - scriptblock { ・・・コード・・・ } -start-job - filepath ファイルパス # 結果はSessionの範囲でしか有効では無い。 ***ワークフロー [#w372d1c1] -ファイルとして登録 -クライアントでもサーバでも実行できる。 -サーバが停止しても処理をレジュームできる。~ 非同期ジョブと異なり、結果は永続化されている。 -その他、並列処理等も可能。 *その他 [#tc84bc50] -エイリアスを使ってUnix風にできる。 -Windows2012からuiのアンインストール可能で、サーバコア風に運用可能。 * 参考 [#i16bae1b] -PowerShell - Wikipedia~ http://ja.wikipedia.org/wiki/Windows_PowerShell~ -PowerShell Documentation | Microsoft Docs~ https://docs.microsoft.com/ja-jp/powershell/index -Windows PowerShell コマンドレットのタスク別ガイド~ http://technet.microsoft.com/ja-jp/scriptcenter/dd772285.aspx -PowerShell 使い方メモ - Qiita~ http://qiita.com/opengl-8080/items/bb0f5e4f1c7ce045cc57 -ゼロからはじめるWindows PowerShell | マイナビニュース --環境構築編~ https://news.mynavi.jp/article/20081112-powershell/ --計算編~ https://news.mynavi.jp/article/20081218-powershell/ --コマンドレット編~ https://news.mynavi.jp/article/20090424-powershell/ --ヘルプ編~ https://news.mynavi.jp/article/20090608-powershell/ --ディレクトリ編~ https://news.mynavi.jp/article/20090923-powershell/ **PowerShell バージョン と 動作環境 [#z48bba9f] -Windows PowerShell System Requirements~ http://technet.microsoft.com/en-us/library/hh847769.aspx >Updated: June 24, 2013~ Applies To: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0~ **VBScriptから変換 [#l0129022] VBScript から PowerShell へ変換のパターン -VBScript から PowerShell へ~ http://technet.microsoft.com/ja-jp/library/ff852826.aspx~ -VBScript のスクリプトを Windows PowerShell のスクリプトに変換する方法はありますか~ http://gallery.technet.microsoft.com/scriptcenter/3002aff2-d444-4f6f-b0b7-2ca77f95e9ca~ -その他の検索~ site:microsoft.com vbscript powershell 変換 **MSDN magazine [#u859c231] -Windows PowerShell - PowerShell での Windows サービスの作成~ https://msdn.microsoft.com/ja-jp/magazine/mt703436.aspx -Essential .NET - 進化を続ける PowerShell~ https://msdn.microsoft.com/magazine/mt742875 **junichia [#gcdd1643] -blog~ http://blogs.technet.com/b/junichia/archive/tags/powershell/ -SlideShare~ http://www.slideshare.net/junichia/tag/powershell -Windows PowerShell 3.0 によるWindows Server 2012 管理の自動化 v2.2 2012.10.1...~ http://www.slideshare.net/junichia/windows-powershell-30-windows-server-2012 -MS安納さん の セミナー資料、 Tech Fielders PowerShell 3.0 シリーズ(東京)~ 概要から、基本的な使い方、スクリプト例、tipsまで、具体的に解説。~ 以下のサイトから、セミナーの各回ごとの資料がダウンロードできます。~ http://www.microsoft.com/ja-jp/techfielders/seminar.aspx~ --2012.06.25 [10:00-11:30]~ 「開発者のための Windows PowerShell ~ 開発コストを低減する究極のライブラリ集を使い倒そう」~ --2012.06.19 [10:00-11:30]~ 「Windows PowerShell 3.0 による Windows Server 2012 管理の自動化~ワークフロー編」~ --2012.06.12 [10:00-11:30]~ 「Windows PowerShell 3.0 による Windows Server 2012 管理の自動化~リモート サーバー管理編」~ --2012.06.04 [10:00-11:30]~ 「Windows PowerShell 3.0 による Windows Server 2012 管理の自動化~初級編」~ >>#この資料では、PowerShell 3.0 の beta/RC 版をベースにしてるため、 PowerShell 2.0 にはないコマンドも紹介されています。~ #ただ、WMIオブジェクトの使い方、リモートや権限などのtipsは、PowerShell 2.0 でも参考になります。~ **その他 [#f940605e] ***[[PowerShell ISE]] [#j853d058] ***[[Azure PowerShell]] [#ra40adac] ***[[Azure Cloud Shell]] [#beef7fca] ***PowerShell Core [#keec9ed9] -PowerShell Core:Dev Basics/Keyword - @IT~ http://www.atmarkit.co.jp/ait/articles/1801/16/news026.html ---- Tags: [[:シェル]], [[:インフラストラクチャ]], [[:Windows]]