2017-10-01 5 views
0

パラメータ(キー)を実行する際に、そのパラメータを確認する必要があります。たとえば、間違ったパラメータを設定すると、(myscript.ps1 -p1 blabla -p2 blabla)私はコンソール(間違ったタイプ)にエラーがあります。どのようにこのエラーをスローすることができますか?また、さまざまなレベルのログ(Debug、Error、Warning)を記述する必要があります。私は1つのコマンドレットStart-Transcriptを知っていますが、すべてのアクションを記述します。PowerShellスクリプトでキーを確認するにはどうしたらいいですか?

 param 
     (
      [datetime]$sleep, 
      [datetime]$wake_up 
     ) 
     #Starting log process 
Start-Transcript .\logger.txt -Append 
function do_sleep() 
{ 
    if (!$sleep) 
    { 
     [datetime]$sleep = Read-Host "Input time when you go to sleep" 
    } 
    if (!$wake_up) 
    { 
     [datetime]$wake_up = Read-Host "Input time when you wake up" 
    } 
    if ($wake_up.Hour -le 8) { 
     Write-Host "You are lark" 
    } 
    if ($wake_up.Hour -gt 8) { 
     Write-Host "You are owl" 
    } 
    if ($wake_up -lt $sleep) { 
     $sleeping_time = ($wake_up.AddDays(1) - $sleep) 
     $normal_sleep = $sleeping_time.hours; 
    } 
    else { 
     $sleeping_time = $wake_up - $sleep; 
     $normal_sleep = $sleeping_time.hours; 
    } 
    if ($normal_sleep -ge 8) { 
     Write-Host "You slept more" $sleeping_time.Hours "hours. You are lucky man. " 
    } 
} 
do 
{ 
    try 
    { 
     do_sleep 
     exit 
    } 
    catch 
    { 
     Write-Host ("Wrong input. Please input data again.") 
     $g = 1; 
    } 
} 
while ($g -eq 1) 
Stop-Transcript 

答えて

0

このような何かしてみてください:、

[CmdletBinding()]Param 

あなたが検証属性を使用できるパラメータを検証するには、次の属性でのparamを飾るさまざまなログレベルを使用できるようにするために

$ScriptName = "Script1" 

try 
{ 

    #create log 
    if (![System.Diagnostics.EventLog]::SourceExists($ScriptName)) 
    { 
     New-EventLog -LogName Application -Source $ScriptName 
    } 


    #Log information 
    Write-EventLog –LogName Application –Source $ScriptName –EntryType Information –EventID 1 –Message "Starting..." 

    $Test="test1" 


    if ($Test -eq "test1") 
    { 
    #throw exception 1 
    throw "$Test is bad" 
    } 

    if ($Test -eq "test2") 
    { 
    #throw exception 2 
    throw "$Test is really bad" 
    } 

    if ($Test -eq "test3") 
    { 
    #Log warning 
    Write-EventLog –LogName Application –Source $ScriptName –EntryType Warning –EventID 1 –Message "Starting..." 
    } 

} 
catch 
{ 
     #log all exceptions 
     $result="Message : {0}, Type : {1}, Exception : {2}, StackTrace : {3}" -f $_, $_.GetType(), $_.Exception, $_.Exception.StackTrace 

     Write-EventLog –LogName Application –Source $ScriptName –EntryType Error –EventID 1 –Message $result 

     #rethrow if you want print errors to output standard error 
     throw 
} 
finally 
{ 
    #Log information 
    Write-EventLog –LogName Application –Source $ScriptName –EntryType Information –EventID 1 –Message "Ending..." 
} 
0

を例えば

[ValidateNotNullOrEmpty()] $MyParam 
の高度な機能PowerShellの 'のより多くの情報検索については

たり、PowerShellのISE

でCtrl + Jを押したときに取得スニペットを見て
関連する問題