Gerando um Arquivo de Log em Powershell


Bom pessoal em meus scripts powershell além do tratamento de erros , eu também costumo gerar um arquivo de log com o formato xxxxxxxxyyyyMMddhhmmss.log aonde xxxxxxx é o nome do arquivo enviado para a função e yyyyMMddhhmmss é ano ,mes, dia,hora,minuto e segundo. Algo como MeuArquivo20090418101523.log

Nesta função que eu montei eu passo :

Nome do Arquivo a ser gerado     = $NamePS1
Servidor                                     = $Server (uso para logar dentro do arquivo qual servidor , pois são varios)
Erro                                           = $Erro
Folder de geração do arquivo       = $PathFileError

Intaum dentro de meus scripts se eu quero logar alguma coisa eu digito

Save-Log “Service” “Servidor1” “mensagem de erro” "C:\Project\Log"

Gerará um arquivo de log no folder c:\project\log com o formato ServiceyyyyMMddhhmmss.log
As linhas  são adicionadas sempre no final do arquivo

Bom é isso aí…

Um grande abraço

##########################################################
#Save a log in path
##########################################################
Function Save-Log ([String] $NamePS1,
                  [String] $Server,
                  [String] $Erro,
                  [String] $PathFileError
                 )
{

    #test if path wich will contains the error file exists. if not create

  if (!(Test-Path -path $PathFileError))
  {
    New-Item $PathFileError
  }

    #Put the name of error file like  $Nameps1.log
  $NameFileFull = $PathFileError + "\" + $NamePS1 + (get-date -format "yyyyMMddhhmmss") + ".log"

  if (Test-Path -path $NameFileFull)
  {
    del $NameFileFull -ErrorAction "silentlycontinue"
  }

  $date =  get-date -format "yyyy-MM-dd hh:mm:ss"
  "Server : " + $Server, "Date : " + $date ,"Error Message: " + $Erro | Out-file  $NameFileFull -append

}

About Laerte Junior

Laerte Junior Laerte Junior is a SQL Server specialist and an active member of WW SQL Server and the Windows PowerShell community. He also is a huge Star Wars fan (yes, he has the Darth Vader´s Helmet with the voice changer). He has a passion for DC comics and living the simple life. "May The Force be with all of us"
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s