LoginSignup
0
0

More than 1 year has passed since last update.

powershellでscriptを引数として指定する方法

Posted at

概要

poweshellでscriptをfunctionに引数として渡すやりかた

実際のコーディング例

timem.ps1
set-alias -name time measure-command 
function timem($script,$num=0){
   if($num -eq 0){
        (time { invoke-command $script }).milliseconds
    }else{
        1..$num|% {(time {invoke-command $script }).milliseconds}|measure -sum -max -min -ave
   }
}

プログラムの説明

これは、\$profileに格納して. $profileで有効にして
timem {ls|select name}

timem {ls|select name} 20
として使えば、最初の例ではミリセカンドでの応答を実測し、
2番目の例の20等の回数を指定すれば最大値、最小値、平均値を
計算してくれる。というものです。

注目点

functionで \$scriptという変数を指定していますが、これは{}がある場合はその部分が引数として
渡されます。最初は文字として渡そうかと思いましたが、その場合は|のパイプが別の意味を持って
しまうので、難しいでした。どうも、
\$a={ls|select name}とかして、$aを見てみるとscript blockという変数になっています。
{}でくくるというのは、文法的にもスクリプトとして優先されるようですねえ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0