Skip to content

Instantly share code, notes, and snippets.

@Tocchann
Created February 6, 2022 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tocchann/20d61fe5a50624219222f26e2f2aa27b to your computer and use it in GitHub Desktop.
Save Tocchann/20d61fe5a50624219222f26e2f2aa27b to your computer and use it in GitHub Desktop.
PowerShellスクリプトでパイプ処理
# 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