代码之家  ›  专栏  ›  技术社区  ›  Techknow

基本Powershell日志记录

  •  2
  • Techknow  · 技术社区  · 7 年前

    我在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
    } 
    

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Kory Gill    7 年前

    创建一个“run and log”函数,并将其与“do stuff”一起调用,作为该函数的scriptblock参数。

    例子:

    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
    

    当然,上面的写主机将是您的 Add-Content 或者别的什么。。。