はじめに
PowerShellでスクリプトを作成していると、「Getコマンドの中から特定の値を抽出したい」と言う時はありませんか?
今回は、こちらの方法をアウトプットします。
抽出するデータとは?
以下、コマンド実行結果のDomain
という値を抽出したいと思います。
※Get-NetFirewallProfile
はファイアウォール設定を確認するコマンドになります。
コマンド実行結果
PS C:\Users\Administrator> Get-NetFirewallProfile -Name Domain
Name : Domain ← これを抽出
Enabled : False
DefaultInboundAction : NotConfigured
DefaultOutboundAction : NotConfigured
AllowInboundRules : NotConfigured
AllowLocalFirewallRules : NotConfigured
AllowLocalIPsecRules : NotConfigured
AllowUserApps : NotConfigured
AllowUserPorts : NotConfigured
AllowUnicastResponseToMulticast : NotConfigured
NotifyOnListen : False
EnableStealthModeForIPsec : NotConfigured
LogFileName : %systemroot%\system32\LogFiles\Firewall\pfirewall.log
LogMaxSizeKilobytes : 4096
LogAllowed : False
LogBlocked : False
LogIgnored : NotConfigured
DisabledInterfaceAliases : {NotConfigured}
データ抽出
こちらのコマンドを実行します。
実行コマンド
(確認コマンド).項目名
コマンド実行例①
Get-NetFirewallProfile
のName
の値を抽出したい場合
コマンド実行例
PS C:\Users\Administrator> (Get-NetFirewallProfile -Name Domain).Name
Domain
コマンド実行例②
Get-Service
からサービス名のみ抽出
コマンド実行例
PS C:\Users\Administrator> (Get-Service -Name ALG).Name
ALG
※抽出しない場合の表示
PS C:\Users\Administrator> Get-Service -Name ALG
Status Name DisplayName
------ ---- -----------
Stopped ALG Application Layer Gateway Service
最後に
この方法を探す前は、以下記事の方法を使っていました。
【PowerShell】Linuxのgrepのように行を検索する方法(Windows)
しかし、今回紹介した内容の方が短文で使いやすいことがわかりました。
是非、ご活用ください!