Powershell-quick-guide
Powershell-概要
Windows PowerShellは、特にシステム管理用に設計された*コマンドラインシェル*および*スクリプト言語*です。 Linuxの類似物はBashスクリプトと呼ばれます。 .NET Framework上に構築されたWindows PowerShellは、ITプロフェッショナルがWindows Server環境で実行されるWindowsオペレーティングシステムとアプリケーションの管理を制御および自動化するのに役立ちます。
*cmdlets* と呼ばれるWindows PowerShellコマンドを使用すると、コマンドラインからコンピューターを管理できます。 Windows PowerShellプロバイダーを使用すると、ファイルシステムにアクセスするのと同じくらい簡単に、レジストリや証明書ストアなどのデータストアにアクセスできます。
さらに、Windows PowerShellには、豊富な式パーサーと完全に開発されたスクリプト言語があります。 つまり、簡単な言葉で言えば、GUIなどで実行するすべてのタスクを完了できます。
PowerShell ISE
Windows PowerShell 統合スクリプト環境(ISE)は、Windows PowerShellのホストアプリケーションです。 Windows PowerShell ISEでは、複数行の編集、タブ補完、構文の色付け、選択的実行、状況依存ヘルプ、および権限のサポートを備えた単一のWindowsベースのグラフィックユーザーインターフェイスでコマンドを実行し、スクリプトを記述、テスト、およびデバッグできます。 -左言語。
メニュー項目とキーボードショートカットを使用して、Windows PowerShellコンソールで実行するのと同じタスクの多くを実行できます。 たとえば、Windows PowerShell ISEでスクリプトをデバッグするときに、スクリプトに行ブレークポイントを設定するには、コード行を右クリックして、[ブレークポイントの切り替え]をクリックします。
PowerShellの基本コマンド
PowerShellのコマンドは多数あり、このチュートリアルでこれらすべてのコマンドを入力することは非常に困難です。PowerShellの最も重要なコマンドと基本的なコマンドのいくつかに焦点を当てます。
最初の手順は、コマンドとそのパラメーターを指定する方法について説明するGet-Helpコマンドに移動することです。
Powershell-環境設定
PowerShellアイコンは、タスクバーと[スタート]メニューにあります。 アイコンをクリックするだけで開きます。
開くには、アイコンをクリックするだけで、次の画面が開き、PowerShellで作業できる状態になります。
PowerShellバージョン
PowerShellの最新バージョンは5.0です。サーバーに何がインストールされているかを確認するには、次のスクリーンショットに示すように、次のコマンド*:$ PSVersionTable *を入力し、画面からPSVersion 4.0があることもわかります。
コマンドレットのある最新バージョンで更新するには、次のリンクから Windows Management Framework 5.0 をダウンロードする必要があります-https://www.microsoft.com/en-us/download/details.aspx?id=50395およびそれをインストールします。
PowerShell ISE
Windows PowerShell 統合スクリプト環境(ISE)は、Windows PowerShellのホストアプリケーションです。 Windows PowerShell ISEでは、複数行の編集、タブ補完、構文の色付け、選択的実行、状況依存ヘルプ、および権限のサポートを備えた単一のWindowsベースのグラフィックユーザーインターフェイスでコマンドを実行し、スクリプトを記述、テスト、およびデバッグできます。 -左言語。
メニュー項目とキーボードショートカットを使用して、Windows PowerShellコンソールで実行するのと同じタスクの多くを実行できます。 たとえば、Windows PowerShell ISEでスクリプトをデバッグするときに、スクリプトに行ブレークポイントを設定するには、コード行を右クリックして、[ブレークポイントの切り替え]をクリックします。
開くには、次のスクリーンショットに示すように、[スタート]-[検索]に移動し、次に[タイプ]-[PowerShell]に移動します。
次に、Windows PowerShell ISEをクリックします。 または、次のスクリーンショットに示すように、下向き矢印をクリックします。
サーバーにインストールされているすべてのアプリケーションが一覧表示され、Windows PowerShell ISEをクリックします。
次の表が開かれます-
これには3つのセクションがあります。1番の* PowerShellコンソール*、2番の Scripting File 、3番めのモジュールはモジュールを見つけることができる Command Module です。
スクリプトを作成しながら、直接実行して、次の例のような結果を見ることができます-
PowerShellの基本コマンド
PowerShellのコマンドは多数あり、このチュートリアルでこれらすべてのコマンドを入力することは非常に困難です。PowerShellの最も重要なコマンドと基本的なコマンドのいくつかに焦点を当てます。
最初の手順は、コマンドとそのパラメーターを指定する方法について説明するGet-Helpコマンドに移動することです。
アップデートのリストを取得するには-
- Get-HotFixおよび次のようにホットフィックスをインストールする
- Get-HotFix -id kb2741530
Powershell-コマンドレット
コマンドレットまたは「コマンドレット」は、Windows PowerShell環境で使用される軽量コマンドです。 Windows PowerShellランタイムは、コマンドプロンプトでこれらのコマンドレットを呼び出します。 Windows PowerShell APIを使用して、プログラムでプログラムを作成して呼び出すことができます。
コマンドレットとコマンド
コマンドレットは、以下の方法で他のコマンドシェル環境のコマンドとは大きく異なります-
- コマンドレットは.NET Frameworkクラスオブジェクトです。スタンドアロンの実行可能ファイルだけではありません。
- コマンドレットは、わずか数十行のコードから簡単に構築できます。
- 解析、エラー表示、および出力フォーマットは、コマンドレットでは処理されません。 Windows PowerShellランタイムによって実行されます。
- コマンドレットプロセスは、テキストストリームではなくオブジェクトに対して機能し、オブジェクトをパイプライン処理の出力として渡すことができます。
- コマンドレットは、一度に1つのオブジェクトを処理するため、レコードベースです。
困ったときは
最初の手順は、コマンドとそのパラメーターを指定する方法について説明するGet-Helpコマンドに移動することです。
Powershell-ファイルとフォルダーの操作
以下は、ファイルとフォルダーのPowerShellスクリプトの例です。
Sr.No. | Operation & Description |
---|---|
1 |
PowerShellスクリプトを使用してフォルダーを作成する方法を示すスクリプトの例。 |
2 |
PowerShellスクリプトを使用してファイルを作成する方法を示すスクリプトの例。 |
3 |
PowerShellスクリプトを使用してファイルをコピーする方法を示すサンプルスクリプト。 |
4 |
PowerShellスクリプトを使用してファイルを作成する方法を示すスクリプトの例。 |
5 |
PowerShellスクリプトを使用してフォルダーを削除する方法を示すサンプルスクリプト。 |
6 |
PowerShellスクリプトを使用してファイルを削除する方法を示すサンプルスクリプト。 |
7 |
PowerShellスクリプトを使用してフォルダーを移動する方法を示すサンプルスクリプト。 |
8 |
PowerShellスクリプトを使用してファイルを移動する方法を示すサンプルスクリプト。 |
9 |
PowerShellスクリプトを使用してフォルダーの名前を変更する方法を示すサンプルスクリプト。 |
10 |
PowerShellスクリプトを使用してファイルの名前を変更する方法を示すサンプルスクリプト。 |
11 |
PowerShellスクリプトを使用してアイテムを取得する方法を示すサンプルスクリプト。 |
12 |
PowerShellスクリプトを使用してフォルダーの存在を確認する方法を示すサンプルスクリプト。 |
13 |
PowerShellスクリプトを使用してファイルの存在を確認する方法を示すサンプルスクリプト。 |
Powershell-日付と時刻の操作
以下は、システムの日付と時刻に関するPowerShellスクリプトの例です。
Sr.No. | Operation & Description |
---|---|
1 |
PowerShellスクリプトを使用してシステムの日付を取得する方法を示すサンプルスクリプト。 |
2 |
PowerShellスクリプトを使用してシステム日付を設定する方法を示すサンプルスクリプト。 |
3 |
PowerShellスクリプトを使用してシステム時間を取得する方法を示すサンプルスクリプト。 |
4 |
PowerShellスクリプトを使用してシステム時間を設定する方法を示すサンプルスクリプト。 |
Powershell-ファイルI/O操作
以下は、さまざまな種類のファイルを作成および読み取るためのPowerShellスクリプトの例です。
シニア
操作と説明
1
リンク:/powershell/powershell_filesio_create_text [テキストファイルの作成]
PowerShellスクリプトを使用してテキストファイルを作成する方法を示すサンプルスクリプト。
2
リンク:/powershell/powershell_filesio_read_text [テキストファイルの読み取り]
PowerShellスクリプトを使用してテキストファイルを読み取る方法を示すスクリプトの例。
3
リンク:/powershell/powershell_filesio_create_xml [XMLファイルの作成]
PowerShellスクリプトを使用してXMLファイルを作成する方法を示すサンプルスクリプト。
4
リンク:/powershell/powershell_filesio_read_xml [XMLファイルの読み取り]
PowerShellスクリプトを使用してXMLファイルを読み取る方法を示すサンプルスクリプト。
5
リンク:/powershell/powershell_filesio_create_csv [CSVファイルの作成]
PowerShellスクリプトを使用してCSVファイルを作成する方法を示すサンプルスクリプト。
6
リンク:/powershell/powershell_filesio_read_csv [CSVファイルの読み取り]
PowerShellスクリプトを使用してCSVファイルを読み取る方法を示すサンプルスクリプト。
7
リンク:/powershell/powershell_filesio_create_html [HTMLファイルの作成]
PowerShellスクリプトを使用してHTMLファイルを作成する方法を示すサンプルスクリプト。
8
リンク:/powershell/powershell_filesio_read_html [HTMLファイルの読み取り]
PowerShellスクリプトを使用してHTMLファイルを読み取る方法を示すサンプルスクリプト。
9
リンク:/powershell/powershell_filesio_erase [ファイルコンテンツの消去]
PowerShellスクリプトを使用してファイルの内容を消去する方法を示すスクリプトの例。
10
リンク:/powershell/powershell_filesio_append [Append Text Data]
PowerShellスクリプトを使用してファイルの内容にテキストを追加する方法を示すサンプルスクリプト。
Powershell-高度なコマンドレット
コマンドレット
コマンドレットまたは「コマンドレット」は、Windows PowerShell環境で使用される軽量コマンドです。 Windows PowerShellランタイムは、コマンドプロンプトでこれらのコマンドレットを呼び出します。 Windows PowerShell APIを使用して、プログラムでプログラムを作成して呼び出すことができます。 以下は、コマンドレットの高度な使用例です。
シニア
コマンドレットのタイプと説明
1
リンク:/powershell/powershell_cmdlets_get_unique [Get-Unique Cmdlet]
Get-Unique Cmdletを紹介するサンプルプログラム。
2
グループオブジェクトコマンドレット
Group-Object Cmdletを紹介するサンプルプログラム。
3
リンク:/powershell/powershell_cmdlets_measure_object [Measure-Object Cmdlet]
Measure-Object Cmdletを紹介するサンプルプログラム。
4
リンク:/powershell/powershell_cmdlets_compare_object [Compare-Object Cmdlet]
Compare-Object Cmdletを紹介するサンプルプログラム。
5
リンク:/powershell/powershell_cmdlets_format_list [Format-List Cmdlet]
Format-List Cmdletを紹介するサンプルプログラム。
6
リンク:/powershell/powershell_cmdlets_format_wide [フォーマット全体のコマンドレット]
Format-Wide Cmdletを紹介するサンプルプログラム。
7
リンク:/powershell/powershell_cmdlets_where_object [Where-Objectコマンドレット]
Where-Objectコマンドレットを紹介するサンプルプログラム。
8
リンク:/powershell/powershell_cmdlets_get_childitem [Get-ChildItemコマンドレット]
Get-ChildItemコマンドレットを紹介するサンプルプログラム。
9
リンク:/powershell/powershell_cmdlets_foreach_object [ForEach-Object Cmdlet]
ForEach-Object Cmdletを紹介するサンプルプログラム。
10
リンク:/powershell/powershell_cmdlets_start_sleep [Start-Sleep Cmdlet]
Start-Sleep Cmdletを紹介するサンプルプログラム。
11
リンク:/powershell/powershell_cmdlets_read_host [Read-Host Cmdlet]
Read-Host Cmdletを紹介するサンプルプログラム。
12
リンク:/powershell/powershell_cmdlets_select_object [Select-Object Cmdlet]
Select-Object Cmdletを紹介するサンプルプログラム。
13
リンク:/powershell/powershell_cmdlets_sort_object [Sort-Object Cmdlet]
Sort-Object Cmdletを紹介するサンプルプログラム。
14
リンク:/powershell/powershell_cmdlets_write_warning [書き込み警告コマンドレット]
Write-Warning Cmdletを紹介するサンプルプログラム。
15
リンク:/powershell/powershell_cmdlets_write_host [Write-Host Cmdlet]
Write-Host Cmdletを紹介するサンプルプログラム。
16
リンク:/powershell/powershell_cmdlets_invoke_item [Invoke-Itemコマンドレット]
Invoke-Item Cmdletを紹介するサンプルプログラム。
17
リンク:/powershell/powershell_cmdlets_invoke_expression [Invoke-Expression Cmdlet]
Invoke-Expression Cmdletを紹介するサンプルプログラム。
18
リンク:/powershell/powershell_cmdlets_measure_command [Measure-Command Cmdlet]
Measure-Command Cmdletを紹介するサンプルプログラム。
19
リンク:/powershell/powershell_cmdlets_invoke_history [Invoke-Historyコマンドレット]
Invoke-History Cmdletを紹介するサンプルプログラム。
20
リンク:/powershell/powershell_cmdlets_add_history [Add-History Cmdlet]
Add-History Cmdletを紹介するサンプルプログラム。
21
リンク:/powershell/powershell_cmdlets_get_history [Get-History Cmdlet]
Get-History Cmdletを紹介するサンプルプログラム。
22
リンク:/powershell/powershell_cmdlets_get_culture [Get-Cultureコマンドレット]
Get-Culture Cmdletを紹介するサンプルプログラム。
Powershell-スクリプト
Windows PowerShellは、特にシステム管理用に設計された*コマンドラインシェル*および*スクリプト言語*です。 Linuxの類似物は、Bash Scriptingと呼ばれます。 .NET Framework上に構築されたWindows PowerShellは、ITプロフェッショナルがWindows Server環境で実行されるWindowsオペレーティングシステムとアプリケーションの管理を制御および自動化するのに役立ちます。
*cmdlets* と呼ばれるWindows PowerShellコマンドを使用すると、コマンドラインからコンピューターを管理できます。 Windows PowerShellプロバイダーを使用すると、ファイルシステムにアクセスするのと同じくらい簡単に、レジストリや証明書ストアなどのデータストアにアクセスできます。
さらに、Windows PowerShellには、豊富な式パーサーと完全に開発されたスクリプト言語があります。 つまり、簡単な言葉で言えば、GUIなどで実行するすべてのタスクを完了できます。 Windows PowerShellスクリプトは完全に開発されたスクリプト言語であり、豊富な式パーサー/
特徴
- コマンドレット-コマンドレットは、レジストリ、サービス、プロセス、イベントログの管理、Windows Management Instrumentation(WMI)の使用など、一般的なシステム管理タスクを実行します。
- タスク指向-PowerShellスクリプト言語はタスクベースであり、既存のスクリプトとコマンドラインツールのサポートを提供します。
- 一貫した設計-コマンドレットとシステムデータストアは共通の構文を使用し、共通の命名規則を持っているため、データ共有は簡単です。 あるコマンドレットからの出力は、操作なしで別のコマンドレットにパイプライン化できます。
- 使いやすい-簡素化されたコマンドベースのナビゲーションにより、ユーザーはファイルシステムのナビゲーションと同様にレジストリやその他のデータストアをナビゲートできます。
- オブジェクトベース-PowerShellは強力なオブジェクト操作機能を備えています。 オブジェクトは、他のツールまたはデータベースに直接送信できます。
- 拡張可能なインターフェイス-PowerShellは独立したソフトウェアベンダーとしてカスタマイズ可能であり、エンタープライズ開発者はPowerShellを使用してソフトウェアを管理するカスタムツールとユーティリティを構築できます。
変数
PowerShell変数は名前付きオブジェクトです。 PowerShellはオブジェクトを操作するため、これらの変数はオブジェクトを操作するために使用されます。
変数を作成する
変数名は$で始まる必要があり、名前に英数字とアンダースコアを含めることができます。 有効な変数名を入力すると、変数を作成できます。
PowerShell ISEコンソールで次のコマンドを入力します。 D:\ testフォルダーにいると仮定します。
$location = Get-Location
ここで、変数$ locationを作成し、Get-Locationコマンドレットの出力を割り当てました。 現在の場所が含まれています。
変数を使用する
PowerShell ISEコンソールで次のコマンドを入力します。
$location
出力
PowerShellコンソールで次の出力を確認できます。
Path
D:\test
=== 変数の情報を取得する
Get-Memberコマンドレットは、使用されている変数の種類を知ることができます。 下記の例をご覧ください。
[source,prettyprint,notranslate]
$location | Get-Member
=== 出力
PowerShellコンソールで次の出力を確認できます。
[source,result,notranslate]
TypeName: System.Management.Automation.PathInfo
Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Drive Property System.Management.Automation.PSDriveInfo Drive {get;} Path Property System.String Path {get;} Provider Property System.Management.Automation.ProviderInfo Provider {get;} ProviderPath Property System.String ProviderPath {get;}
Powershell-特殊変数
PowerShell特殊変数には、PowerShellに関する情報が格納されます。 これらは自動変数とも呼ばれます。 以下は自動変数のリストです-
Operator | Description |
---|---|
$$ | Represents the last token in the last line received by the session. |
$? | Represents the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed. |
$^ | Represents the first token in the last line received by the session. |
$_ | Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline. |
$ARGS | Represents an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. |
$CONSOLEFILENAME | Represents the path of the console file (.psc1) that was most recently used in the session. |
$ERROR | Represents an array of error objects that represent the most recent errors. |
$EVENT | Represents a PSEventArgs object that represents the event that is being processed. |
$EVENTARGS | Represents an object that represents the first event argument that derives from EventArgs of the event that is being processed. |
$EVENTSUBSCRIBER | Represents a PSEventSubscriber object that represents the event subscriber of the event that is being processed. |
$EXECUTIONCONTEXT | Represents an EngineIntrinsics object that represents the execution context of the PowerShell host. |
$FALSE | Represents FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false". |
$FOREACH | Represents the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. |
$HOME | Represents the full path of the user’s home directory. |
$HOST | Represents an object that represents the current host application for PowerShell. |
$INPUT | Represents an enumerator that enumerates all input that is passed to a function. |
$LASTEXITCODE | Represents the exit code of the last Windows-based program that was run. |
$MATCHES | The $Matches variable works with the -match and -notmatch operators. |
$MYINVOCATION | $MyInvocation is populated only for scripts, function, and script blocks. PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script. |
$NESTEDPROMPTLEVEL | Represents the current prompt level. |
$NULL | $null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts. |
$PID | Represents the process identifier (PID) of the process that is hosting the current PowerShell session. |
$PROFILE | Represents the full path of the PowerShell profile for the current user and the current host application. |
$PSCMDLET | Represents an object that represents the cmdlet or advanced function that is being run. |
$PSCOMMANDPATH | Represents the full path and file name of the script that is being run. |
$PSCULTURE | Represents the name of the culture currently in use in the operating system. |
$PSDEBUGCONTEXT | While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value. |
$PSHOME | Represents the full path of the installation directory for PowerShell. |
$PSITEM | Same as $_. Contains the current object in the pipeline object. |
$PSSCRIPTROOT | Represents the directory from which a script is being run. |
$PSSENDERINFO | Represents information about the user who started the PSSession, including the user identity and the time zone of the originating computer. |
$PSUICULTURE | Represents the name of the user interface (UI) culture that is currently in use in the operating system. |
$PSVERSIONTABLE | Represents a read-only hash table that displays details about the version of PowerShell that is running in the current session. |
$SENDER | Represents the object that generated this event. |
$SHELLID | Represents the identifier of the current shell. |
$STACKTRACE | Represents a stack trace for the most recent error. |
$THIS | In a script block that defines a script property or script method, the $This variable refers to the object that is being extended. |
$TRUE | Represents TRUE. You can use this variable to represent TRUE in commands and scripts. |
Powershell-オペレーター
PowerShellは、変数を操作するための豊富な演算子セットを提供します。 私たちはすべてのPowerShell演算子を次のグループに分けることができます-
- 算術演算子
- 割り当て演算子
- 比較演算子
- 論理演算子
- リダイレクト演算子
- こぼれた演算子と結合演算子
- タイプ演算子
- 単項演算子
算術演算子
算術演算子は、代数で使用されるのと同じ方法で数式で使用されます。 次の表は、算術演算子を示しています-
整数変数Aが10を保持し、変数Bが20を保持すると仮定します-
リンク:/powershell/powershell_arithmatic_operators_examples [例を表示]
Operator | Description | Example |
---|---|---|
PLUS (Addition) | Adds values on either side of the operator. | A PLUS B will give 30 |
- (Subtraction) | Subtracts right-hand operand from left-hand operand. | A - B will give -10 |
AST (Multiplication) | Multiplies values on either side of the operator. | A AST B will give 200 |
/(Division) | Divides left-hand operand by right-hand operand. | B/A will give 2 |
% (Modulus) | Divides left-hand operand by right-hand operand and returns remainder. | B % A will give 0 |
比較演算子
PowerShell言語でサポートされている代入演算子は次のとおりです-
整数変数Aが10を保持し、変数Bが20を保持すると仮定します-
リンク:/powershell/powershell_comparison_operators_examples [例を表示]
オペレーター
説明
例
eq(等しい)
2つの値が等しいかどうかを比較します。
A -eq Bはfalseを返します
ne(等しくない)
2つの値が等しくないことを比較します。
A -ne Bはtrueを返します
gt(より大きい)
最初の値が2番目の値より大きいかどうかを比較します。
B -gt Aはtrueを返します
ge(以上)
最初の値を2番目の値以上に比較します。
B -ge Aは真を与える
lt(未満)
最初の値が2番目の値より小さいかどうかを比較します。
B -lt Aはfalseを返します
le(以下)
最初の値が2番目の値以下になるように比較します。
B -le Aは偽を与える
割り当て演算子
PowerShell言語でサポートされている代入演算子は次のとおりです-
リンク:/powershell/powershell_assignment_operators_examples [例を表示]
Operator | Description | Example |
---|---|---|
= | Simple assignment operator. Assigns values from right side operands to left side operand. | C = A PLUS B will assign value of A PLUS B into C |
PLUS= | Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. | C PLUS= A is equivalent to C = C PLUS A |
-= | Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. | C -= A is equivalent to C = C - A |
論理演算子
次の表は、論理演算子を示しています-
ブール変数Aがtrueを保持し、変数Bがfalseを保持すると仮定します-
リンク:/powershell/powershell_logical_operators_examples [例を表示]
Operator | Description | Example |
---|---|---|
AND (logical and) | Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. | (A -AND B) is false |
OR (logical or) | Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. | (A -OR B) is true |
NOT (logical not) | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | -NOT(A -AND B) is true |
その他の演算子
以下は、PowerShell言語でサポートされるさまざまな重要な演算子です-
リンク:/powershell/powershell_miscellaneous_operators_examples [例を表示]
オペレーター
説明
例
>(リダイレクトオペレーター)
リダイレクト演算子。 リダイレクトされたファイル/出力デバイスに印刷する出力を割り当てます。
dir> test.logは、test.logファイルのディレクトリリストを出力します
Powershell-ループ
コードのブロックを数回実行する必要がある場合があります。 一般に、ステートメントは順番に実行されます。関数の最初のステートメントが最初に実行され、次に2番目のステートメントが実行されます。
プログラミング言語は、より複雑な実行パスを可能にするさまざまな制御構造を提供します。
- ループ*ステートメントは、ステートメントまたはステートメントのグループを複数回実行することを可能にし、ほとんどのプログラミング言語でのループステートメントの一般的な形式は次のとおりです-
PowerShellプログラミング言語は、ループ要件を処理するために次の種類のループを提供します。 詳細を確認するには、次のリンクをクリックしてください。
シニア
ループと説明
1
リンク:/powershell/powershell_for_loop [forループ]
一連のステートメントを複数回実行し、ループ変数を管理するコードを短縮します。
2
リンク:/powershell/powershell_foreach_loop [forEachループ]
拡張forループ。 これは主に、配列を含む要素のコレクションを走査するために使用されます。
3
リンク:/powershell/powershell_while_loop [while loop]
特定の条件が真の間、ステートメントまたはステートメントのグループを繰り返します。 ループ本体を実行する前に条件をテストします。
4
リンク:/powershell/powershell_do_while_loop [do … while loop]
whileステートメントと似ていますが、ループ本体の最後で条件をテストします。
Powershell-条件
意思決定構造には、プログラムによって評価またはテストされる1つ以上の条件と、条件が真であると判定された場合に実行されるステートメント、およびオプションで、条件が判定された場合に実行される他のステートメントがあります偽りです。
以下は、ほとんどのプログラミング言語で見られる典型的な意思決定構造の一般的な形式です-
PowerShellスクリプト言語は、次の種類の意思決定ステートメントを提供します。 詳細を確認するには、次のリンクをクリックしてください。
Sr.No. | Statement & Description |
---|---|
1 |
|
2 |
|
3 |
1つの if または elseif ステートメントを別の if または elseif ステートメント内で使用できます。 |
4 |
|
Powershell-配列
PowerShellは、任意の型の要素の固定サイズの順次コレクションを格納するデータ配列 array を提供します。 配列はデータのコレクションを格納するために使用されますが、配列を変数またはオブジェクトのコレクションと考える方が便利な場合があります。
number0、number1、…、number99などの個々の変数を宣言する代わりに、numbersなどの1つの配列変数を宣言し、numbers [0]、numbers [1]、…、numbers [99]を使用して表現します個々の変数。
このチュートリアルでは、配列変数の宣言、配列の作成、およびインデックス付き変数を使用した配列の処理方法を紹介します。
配列変数の宣言
プログラムで配列を使用するには、配列を参照する変数を宣言する必要があり、変数が参照できる配列のタイプを指定できます。 ここに配列変数を宣言するための構文があります-
構文
$A = 1, 2, 3, 4
or
$A = 1..4
注-デフォルトでは、配列のオブジェクトのタイプはSystem.Objectです。 GetType()メソッドは、配列のタイプを返します。 タイプを渡すことができます。
例
次のコードスニペットは、この構文の例です-
[int32[]]$intA = 1500,2230,3350,4000
$A = 1, 2, 3, 4
$A.getType()
これは、次の結果を生成します-
出力
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
配列要素は index を介してアクセスされます。 配列インデックスは0ベースです。つまり、0から arrayRefVar.length-1 で始まります。
例
次のステートメントは、配列変数myListを宣言し、double型の10要素の配列を作成し、その参照をmyListに割り当てます-
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
次の図は、配列myListを表しています。 ここで、myListは10個のdouble値を保持し、インデックスは0〜9です。
配列の処理
配列要素を処理するときは、配列のすべての要素が同じ型であり、配列のサイズがわかっているため、 for ループまたは foreach ループを使用することがよくあります。
例
配列を作成、初期化、処理する方法を示す完全な例は次のとおりです-
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
write-host("Print all the array elements")
$myList
write-host("Get the length of array")
$myList.Length
write-host("Get Second element of array")
$myList[1]
write-host("Get partial array")
$subList = $myList[1..3]
write-host("print subList")
$subList
write-host("using for loop")
for ($i = 0; $i -le ($myList.length - 1); $i += 1) {
$myList[$i]
}
write-host("using forEach Loop")
foreach ($element in $myList) {
$element
}
write-host("using while Loop")
$i = 0
while($i -lt 4) {
$myList[$i];
$i++
}
write-host("Assign values")
$myList[1] = 10
$myList
これは、次の結果を生成します-
出力
Print all the array elements
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
Get the length of array
10
Get Second element of array
4.5
Get partial array
print subList
4.5
3.3
13.2
using for loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using forEach Loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using while Loop
5.6
4.5
3.3
13.2
Assign values
5.6
10
3.3
13.2
4
34.33
34
45.45
99.993
11123
配列メソッドの例
メソッドを使用した配列の操作を示す完全な例です
$myList = @(0..4)
write-host("Print array")
$myList
$myList = @(0..4)
write-host("Assign values")
$myList[1] = 10
$myList
これは、次の結果を生成します-
出力
Clear array
Print array
0
1
2
3
4
Assign values
0
10
2
3
4
Powershell-ハッシュテーブル
Hashtableは、キー/値のペアをハッシュテーブルに保存します。 ハッシュテーブルを使用する場合、キーとして使用されるオブジェクトと、そのキーにリンクする値を指定します。 通常、キーとして文字列または数字を使用しました。
このチュートリアルでは、ハッシュテーブル変数を宣言し、ハッシュテーブルを作成し、そのメソッドを使用してハッシュテーブルを処理する方法を紹介します。
ハッシュテーブル変数の宣言
プログラムでハッシュテーブルを使用するには、ハッシュテーブルを参照する変数を宣言する必要があります。 ハッシュテーブル変数を宣言するための構文は次のとおりです-
構文
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}
注-同様の構文を使用して、順序付けられた辞書を作成できます。 順序付けされた辞書は、エントリが追加される順序を維持しますが、ハッシュテーブルはそうではありません。
例
次のコードスニペットは、この構文の例です-
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
ハッシュテーブルを印刷します。
$hash
出力
Name Value
---- -----
ID 1
Color Blue
Shape Square
ハッシュテーブルの値は、*キー*を介してアクセスされます。
> $hash["ID"]
1
ハッシュテーブルの処理
ドット表記を使用して、ハッシュテーブルのキーまたは値にアクセスできます。
> $hash.keys
ID
Color
Shape
> $hash.values
1
Blue
Square
例
ハッシュテーブルを作成、初期化、処理する方法を示す完全な例は次のとおりです-
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
write-host("Print all hashtable keys")
$hash.keys
write-host("Print all hashtable values")
$hash.values
write-host("Get ID")
$hash["ID"]
write-host("Get Shape")
$hash.Number
write-host("print Size")
$hash.Count
write-host("Add key-value")
$hash["Updated"] = "Now"
write-host("Add key-value")
$hash.Add("Created","Now")
write-host("print Size")
$hash.Count
write-host("Remove key-value")
$hash.Remove("Updated")
write-host("print Size")
$hash.Count
write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key
これは、次の結果を生成します-
出力
Print all hashtable keys
ID
Color
Shape
Print all hashtable values
1
Blue
Square
Get ID
1
Get Shape
print Size
3
Add key-value
Add key-value
print Size
5
Remove key-value
print Size
4
sort by key
Name Value
---- -----
Color Blue
Created Now
ID 1
Shape
Square
Powershell-正規表現
正規表現は、パターンに保持されている特殊な構文を使用して、他の文字列または文字列のセットを一致または検索するのに役立つ特殊な文字シーケンスです。 テキストおよびデータの検索、編集、または操作に使用できます。
PowerShellで利用可能なすべての正規表現メタ文字構文をリストした表は次のとおりです-
Subexpression | Matches |
---|---|
^ | Matches the beginning of the line. |
$ | Matches the end of the line. |
. | Matches any single character except newline. Using m option allows it to match the newline as well. |
[…] | Matches any single character in brackets. |
[^…] | Matches any single character not in brackets. |
\A | Beginning of the entire string. |
\z | End of the entire string. |
\Z | End of the entire string except allowable final line terminator. |
re* | Matches 0 or more occurrences of the preceding expression. |
rePLUS | Matches 1 or more of the previous thing. |
re? | Matches 0 or 1 occurrence of the preceding expression. |
re\{ n} | Matches exactly n number of occurrences of the preceding expression. |
re\{ n,} | Matches n or more occurrences of the preceding expression. |
re\{ n, m} | Matches at least n and at most m occurrences of the preceding expression. |
a | b |
Matches either a or b. | (re) |
Groups regular expressions and remembers the matched text. | (?: re) |
Groups regular expressions without remembering the matched text. | (?> re) |
Matches the independent pattern without backtracking. | \w |
Matches the word characters. | \W |
Matches the nonword characters. | \s |
Matches the whitespace. Equivalent to [\t\n\r\f]. | \S |
Matches the nonwhitespace. | \d |
Matches the digits. Equivalent to [0-9]. | \D |
Matches the nondigits. | \A |
Matches the beginning of the string. | \Z |
Matches the end of the string. If a newline exists, it matches just before newline. | \z |
Matches the end of the string. | \G |
Matches the point where the last match finished. | \n |
Back-reference to capture group number "n". | \b |
Matches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets. | \B |
Matches the nonword boundaries. | \n, \t, etc. |
Matches newlines, carriage returns, tabs, etc. | \Q |
Escape (quote) all characters up to \E. | \E |
PowerShellで正規表現を使用する方法を示す完全な例を次に示します。
Sr.No. | Match & Description |
---|---|
1 |
サポートされている正規表現文字の例。 |
2 |
サポートされている文字クラスの例。 |
3 |
サポートされている数量詞の例。 |
Powershell-バックティック
バックティック( )演算子は、ワードラップ演算子とも呼ばれます。 コマンドを複数行に書き込むことができます。 文の改行( `n)またはタブ(
t)にも使用できます。 以下の例を参照してください-
例1
Get-Service *| Sort-Object ServiceType `
| Format-Table Name, ServiceType, Status -AutoSize
になります
Get-Service* | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize
出力を次のように検証します
Name ServiceType Status
---- ----------- ------
MSSQLServerADHelper100 Win32OwnProcess Stopped
ntrtscan Win32OwnProcess Running
...
例2
新しい行とタブの使用。
> Write-host "Title Subtitle"
Title Subtitle
> Write-host "Title `nSubtitle"
Title
Subtitle
> Write-host "Title `tSubtitle"
Title Subtitle
link:/cgi-bin/printpage.cgi [__印刷]
Powershell-ブラケット
Powershellは3種類のブラケットをサポートしています。
- 括弧括弧。 −()
- *中かっこ。 − \ {} *
- *角括弧。 − [] *
かっこ
このタイプのブラケットは
- 引数を渡す
- 複数の命令セットを同封する
- あいまいさを解決する
- 配列を作成する
例
> $array = @("item1", "item2", "item3")
> foreach ($element in $array) { $element }
item1
item2
item3
中かっこ
このタイプのブラケットは
- 文を囲む
- ブロックコマンド
例
$x = 10
if($x -le 20){
write-host("This is if statement")
}
これは、次の結果を生成します-
出力
This is if statement.
角括弧
このタイプのブラケットは
- 配列へのアクセス
- ハッシュテーブルへのアクセス
- 正規表現を使用したフィルター
例
> $array = @("item1", "item2", "item3")
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3
>Get-Process [r-s]*
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
320 72 27300 33764 227 3.95 4028 SCNotification
2298 77 57792 48712 308 2884 SearchIndexer
...
Powershell-エイリアス
PowerShellエイリアスは、コマンドレットまたはコマンド要素の別名です。
エイリアスを作成する
*New-Alias* コマンドレットを使用してエイリアスを作成します。 次の例では、Get-Helpコマンドレットのエイリアスヘルプを作成しました。
New-Alias -Name help -Value Get-Help
ここでエイリアスを呼び出します。
help Get-WmiObject -Detailed
次の出力が表示されます。
NAME
Get-WmiObject
SYNOPSIS
Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.
SYNTAX
Get-WmiObject [
...
エイリアスを取得する
*get-alias* コマンドレットを使用して、powershellの現在のセッションに存在するすべてのエイリアスを取得します。
Get-Alias
次の出力が表示されます。
CommandType Name Definition
----------- ---- ----------
Alias % ForEach-Object
Alias ? Where-Object
Alias ac Add-Content
Alias asnp Add-PSSnapIn
...