2017-10-01 16 views
0

我需要验证我的参数(键),当我运行它。例如,当我设置错误的参数看起来像(myscript.ps1 -p1 blabla -p2 blabla)我在控制台(错误类型)中有错误。我该如何抛出这个错误?另外,我需要在不同级别写入日志(Debug,Error,Warning)。我只知道一个cmdlet开始 - 转录,但它会写入所有操作。如何在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

尝试这样:

$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

为了能够使用不同的日志记录级别装点PARAM具有以下属性:

[CmdletBinding()]Param 

验证您可以使用验证特性参数,例如

[ValidateNotNullOrEmpty()] $MyParam 

欲了解更多信息,搜索“高级功能的PowerShell”或看看代码段,你得到当你按下Ctrl + J在PowerShell ISE中