0

how would i write a log file, and do a throw in the same line ?

      Function LogWrite
    {
   Param ([string]$logstring)

 Add-content $Logfile -value $logstring
}

This works, but dont look so good in the code:

LogWrite "$ProgramName Not Installed" throw "$ProgramName Not Installed"

Bendo1984
  • 19
  • 2
  • 6
  • 3
    Why does it need to be on the same line? Just put the `throw` after the `LogWrite` line. – Rynant Jul 09 '14 at 17:27
  • 1
    In addition to @Rynant's comment, I would suggest that you read [this discussion](http://stackoverflow.com/a/77361/1324345) on SO about throwing exceptions in the first place. A return code may be more appropriate than a full-blown exception. – alroc Jul 09 '14 at 17:34
  • Thx, how would i add a timestamp in the logfile at every entry ? do you know that ? :) – Bendo1984 Jul 09 '14 at 17:54

1 Answers1

0

If you are concerned about repeating the "$ProgramName Not Installed" message, you could store the message in a variable and reuse it.

$msg = "$ProgramName Not Installed"
LogWrite $msg
throw $msg
Rynant
  • 23,153
  • 5
  • 57
  • 71
  • Thx, how would i add a timestamp in the logfile at every entry ? do you know that ? :) – Bendo1984 Jul 09 '14 at 17:44
  • 1
    @Bendo1984 In your `LogWrite` function add something like `$logstring = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff ') + $logstring` before the `Add-Content` line. For formatting help see: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx – Rynant Jul 09 '14 at 18:15
  • Thx alot works perfect - do you also think, that i should use exitcode instead of throw ? – Bendo1984 Jul 09 '14 at 18:22
  • @Bendo1984 I think it depends on what you are doing. But whenever I do use a `throw`, the `throw` is contained in a function that has the `[CmdLetBinding()]` attribute (run `help about_Functions_CmdletBindingAttribute` for explanation) that way an error can be ignored like: `Run-MyFunction 'test' -ErrorAction SilentlyContinue` – Rynant Jul 09 '14 at 18:40
  • But i dont want it to continue – Bendo1984 Jul 09 '14 at 19:36
  • Again, it depends on what you are doing, but if your script/function has the possibility of being called by other scripts/functions it is helpful to provide a clean way of handling the error (`-ErrorAction` can also take `Stop`, `Continue`, `Inquire` or `Ignore`). If you are going to throw an error that will never be caught, then why throw it? If that is the case, it would probably be better to `return` or `exit` from the script. – Rynant Jul 09 '14 at 20:45