Created
February 6, 2022 08:39
-
-
Save Tocchann/20d61fe5a50624219222f26e2f2aa27b to your computer and use it in GitHub Desktop.
PowerShellスクリプトでパイプ処理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# StdinPipe.ps1 [-InputObject] <string[]> [-ReqireParam] <string> [[-OptionalParam] <string>] [<CommonParameters>] | |
[CmdletBinding()] | |
param ( | |
[parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="標準入力か引数で受け取るデータ")] | |
[string[]]$InputObject, | |
[parameter(Mandatory=$true,ValueFromPipeline=$false,HelpMessage="必須パラメータ")] | |
[string]$ReqireParam, | |
[parameter(Mandatory=$false,ValueFromPipeline=$false,HelpMessage="オプションパラメータ")] | |
[string]$OptionalParam | |
) | |
begin{ | |
# 初期化処理等はここに書く | |
Set-StrictMode -Version Latest | |
[string[]]$inputParam = @() | |
# 関数はここに記述して置くと分離できて見やすいのかな? | |
function Func( [Object]$dispParam ){ | |
$dispParam | Out-String | |
} | |
} | |
process{ | |
Write-Verbose "Called-`"$InputObject`"" | |
$inputParam += $InputObject | |
} | |
end{ | |
# ここをメイン関数みたいに使うのがすっきりする | |
# $inputParam は sting[]なのでそのままでは Write-Verbose出来ないため文字列に変換してやる | |
# パターン1 | |
Write-Verbose "`$stringValue = Func `$inputParam; Write-Verbose `$stringValue" | |
$stringValue = Func $inputParam | |
Write-Verbose $stringValue | |
# パターン2 | |
Write-Verbose "Write-Verbose `"`$inputParam`"" | |
Write-Verbose "$inputParam" | |
# さらにパイプをつなぐような場合は、つぎに渡すオブジェクトを return。仕様は明確に! | |
return $inputParam | |
# バッチファイルのように失敗を明確化して返したい場合はexitを呼び出してやる($LASTEXITCODEで値が取れるようになる) | |
# exit 数値 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment