基本的 Powershell 日志记录

Basic Powershell Logging

我在 Powershell 中编写了一个自动化脚本,可以多次运行少量函数...

我开始了解 Powershell,但我仍然做很多愚蠢的事情...我想知道我是否错过了显而易见的事情。

每次函数运行时,它依赖于传递给它的一些变量以及一些用户输入...没有什么棘手的,重新启动远程服务,同步时间服务等。我想将结果记录为我去了,但似乎我将添加更多代码到日志中,而不是我用来完成工作的实际代码。这是正常现象,还是我遗漏了什么?

我已经研究了 Try/Catch/Finally 块,但它们看起来相当笨重,而且我似乎用这种方法嵌套了很深的函数...这是我正在使用的函数的精简示例:

    Function MyFunc($Param1, $Param2){
Do{
  $Var = Get-Something | Select Name, MachineName, Status 
 $NotherVar = Read-Host -Prompt "Do you want to Stop or Start or check the $Var (1 to Start, 2 to stop, 3 to check, 4 to continue)?" 
    If ($SetState -eq 1) 
     {
      Do Stuff
    }
    ElseIf ($Var -eq 2) 
       {
      Do Stuff
    }
    ElseIf ($Var -eq 3)
       {
      Do Stuff
    }
  }
    Until ($Var -eq 4)
Do other stuff
} 

是否可以在没有国会法案的情况下简单地添加内容 $logpath $FunctionResult?

创建一个 "run and log" 函数并使用您的 "do stuff" 作为此函数的脚本块参数来调用它。

示例:

function Invoke-RunScriptblockAndLogResult([scriptblock]$sb)
{
    $result = Invoke-Command -ScriptBlock $sb

    # log result
    Write-Host "RESULT: $result"
}

Invoke-RunScriptblockAndLogResult {2+2; 3*3}

$myScript = {
    4+4
    5*5
}

Invoke-RunScriptblockAndLogResult $myScript

输出:

RESULT: 4 9
RESULT: 8 25

当然,上面的 Write-Host 将是您的 Add-Content 或其他...