Reputation: 301
I have written an automation script in Powershell that runs a small number of functions many times...
I am beginning to get my head around Powershell, but I still do pleeeenty of stupid stuff... I have to wonder if I am missing the obvious.
Each time a function runs, it relies on a few variables passed to it along with some user input... Nothing to tricky, restarting remote services, syncing time services etc.. I would like to log the results as I go, but it seems like I will be adding more code to log, than the actual code that I am using to do the work. Is this normal, or am I missing something?
I have looked into the Try/Catch/Finally blocks, but they seem rather unwieldy and I seem to be nesting functions pretty deep with that approach... Here is a stripped down example of a function that I am using:
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
}
Is it possible to simply Add-Content $logpath $FunctionResult without an act of congress?
Upvotes: 2
Views: 390
Reputation: 7163
Create a "run and log" function and call it with your "do stuff" as a scriptblock parameter to this function.
EXAMPLE:
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
OUTPUT:
RESULT: 4 9
RESULT: 8 25
Of course the Write-Host above would be your Add-Content
or whatever...
Upvotes: 2