header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
Creating Log File
Last Post 06 Jan 2012 10:11 AM by Bobdee. 5 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
BobdeeUser is Offline
Basic Member
Basic Member
Posts:130
Avatar

--
01 Feb 2010 04:33 AM
    Hi,

    I was hoping someone could point me in the right direction.  I'm attempting to create a logging script that logs actions to a text file.

    At the moment I have it sitting inside a foreach loop so an action is carried out, then an entry written to the log file.  However, it only writes one action in the file which is always the last action carried out.  I understand that the output options in powershell will over write a file, but the -noclobber switch throws errors.

    I'm not sure how best to accomplish logging, so could use a little help!

    The general gist of the loop is as follows.  I've trying to write the var $writelog to the $maillog file

    foreach ($Server in $Servers) { 
       foreach ($Service in $Services) { 
          $WriteLog = "" + $Server + " " + $Service + " has been archived" 
          $maillog = $ArchiveDir + "MailLog-" + $Date + ".txt"
          
          Get-ChildItem $serviceDir -filter *.log | where {$_.lastwritetime -lt $Date}| move-Item -Destination $ServerTMP 
          Set-Location $ServerTMP 
          Invoke-Expression $archiveFiles 
          Move-Item *.zip $DestinationDIR 

          if (test-path -path $ArchivedFilename*) { 
             Write $writelog | Export-Csv $maillog 
             Remove-Item *.log   
          } 
       }

    Thanks in advance,

    Robbie.
    BobdeeUser is Offline
    Basic Member
    Basic Member
    Posts:130
    Avatar

    --
    01 Feb 2010 05:59 AM
    The add-content cmdlet will sort this problem.

    So,

    Add-Content -Path $writelog -Value $maillog

    Robbie.

    cameronoveUser is Offline
    Basic Member
    Basic Member
    Posts:352
    Avatar

    --
    02 Feb 2010 02:50 PM
    This is how I handle logging in my scripts. 

    I've written a function write-log that I send strings to.  The first time the function is used it initializes the file with information in my $FileHeader variable.  After that it just appends strings to the file.

    Below is the function, the info I use to initialize my file and and example of how I use the function throughout my script.

    Also I really hate PowerShell's concatinate operator (+ is just so messy) and find double-quotes much more useful.  i.e.
    This: 

    $WriteLog = "" + $Server + " " + $Service + " has been archived"

    Looks much better like this:

    $WriteLog = "$Server $Service has been archived"

    See Dr. Tobias Weltner's Mastering PowerShell page 360 (free e-book here)
    function write-log([string]$info){            
    if($loginitialized -eq $false){
    $FileHeader > $logfile
    $script:loginitialized = $True
    }
    $info >> $logfile
    }

    <#---------Logfile Info----------#>
    $script:logfile = ".\Filename-$(get-date -format MMddyyHHmmss).log"
    $script:Seperator = @"

    $("-" * 25)

    "@

    $script:loginitialized = $false
    $script:FileHeader = @"
    $seperator
    ***Application Information***
    Filename: FileName.ps1
    Created by: Cameron
    Last Modified: $(Get-Date -Date (get-item .\FileName.ps1).LastWriteTime -f MM/dd/yyyy)
    "@



    <#----An Example of how to use the Write-Log function----#>
    #Delete Accounts
    try{
    if($Admin -ne "passthru"){
    Remove-ADUser $ADUser -Credential $Admin -Server $script:server -Confirm:$false
    write-log "`tDeleted user: $($ADUser.distinguishedName)"
    } else {
    Remove-ADUser $ADUser -Server $script:server -Confirm:$false
    write-log "`tDeleted user: $($ADUser.distinguishedName)"
    }
    } catch {
    write-log "Problem deleting ADObject"
    write-log $ADUser
    write-log $error[0].Exception.GetType().FullName
    write-log $error[0].CategoryInfo
    }
    BobdeeUser is Offline
    Basic Member
    Basic Member
    Posts:130
    Avatar

    --
    03 Feb 2010 12:20 AM
    That's fantastic - thanks.  I'm going to have a good scan through the e-book too.

    I was using Add-Content and IF / Else on each action to populate a summary log (below) which will be emailed when the script has finished, but with your function I can definately be more verbose which is a great step up.

    if (!(test-path -path $UNCZippedFilename)) 
       { 
          Add-Content -Path $maillog -Value $Problemlog 
       } 
       else 
       { 
          Add-Content -Path $maillog -Value $SuccessLog 
          Remove-Item *.log 
       }

    Thanks Again.

    Rob
    StewUser is Offline
    New Member
    New Member
    Posts:1
    Avatar

    --
    06 Apr 2011 04:28 AM
    I like this approach and have enhanced this for my own use... The only thing I would add other than this basic functionality would be to put a TRAP in the script as a default. Directly below the Write-Log function I add the following:

    $script:UseInfo = $($(get-date -format HH:mm:ss) + "`t" + $env:username + "`t")

    Trap [Exception] {
      write-log $("$UseInfo`t$_. - Line:(" + $($_.InvocationInfo.ScriptLineNUmber)+":"+$($_.InvocationInfo.OffsetInLine)+ ") " + $($_.InvocationInfo.Line))
      continue
    }

    Essentially what this does is ANY exception that occures in the script will be written to the log and then continue on without giving the user the annoying powershell exception output. This makes your scripts look like they really work without error.

    For testing simply change write-log to write-host and the errors will come out on screen... after testing change it to put all errors to the log and deal with them as necessary.

    Stew Basterash
    BobdeeUser is Offline
    Basic Member
    Basic Member
    Posts:130
    Avatar

    --
    06 Jan 2012 10:11 AM
    Cameronve - I've revisited this puppy since I've became a bit more knowledgeable with coding, and yes, your original response was spot on.

    Thank you :-)
    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer