how to get powershell to write to event log or write a log file?

how to get powershell to write to event log or write a log file?

Post by c2NhbG » Sat, 26 Sep 2009 04:15:01


I have a script using

remove-item
and
copy-item

I would like to have a TXT file outputed to say that the scrip ran succesfull.

Something like
remove-item C:\temp -vervbose
Echo the file removal was successful | C:\logs\removal.log
copy-item C:\temp -destination D:\temp
echo the file copy was successful | C:\logs\copy.log




All i am trying to do is verify that the date stamps on the copied files
have changed or that the files are deleted and then are written to the new
location and that succeeded.

If i could do this with an eventlog event that would be great as well and
probably preferred.

any help?
 
 
 

how to get powershell to write to event log or write a log file?

Post by Chris Den » Sat, 26 Sep 2009 17:50:07


Would you want to capture any error returned from the two commands? e.g.

$LogFile = "RemoveItem.log"

Remove-Item $SomeItem -ErrorVariable "RemoveErr"
If ($RemoveErr) {
"Error removing $SomeItem" >> $LogFile
$RemoveErr >> $LogFile
} else {
"Removed $SomeItem" >> $LogFile
}

You can write error messages to the Event Log with:

[Diagnostics.EventLog]::Wri *** try( ... )

The simplest form of that is:

[Diagnostics.EventLog]::Wri *** try("Source", "Message")

Which adds an entry to the Application Event Log.

See:

http://www.yqcomputer.com/ *** try.aspx

Chris

 
 
 

how to get powershell to write to event log or write a log file?

Post by Alex » Thu, 01 Oct 2009 16:25:49

Another full-blown solution could be using log4net. Once it is
installed, add this to your profile:

[Reflection.Assembly]::LoadFrom("log4net.dll") # you may want to
adjust the path here
[log4net.Config.XmlConfigurator]::Configure( `
(new-object System.IO.FileInfo -ArgumentList `
(ls "log4net_config.xml").FullName `
) )
$global:Log = [log4net.LogManager]::GetLogger("Powershell.PSTest")

After that, you can use something like $Log.Warn("hello, log")

Read log4net documentation on how to configure the format and location
of log files

Cheers


> Error removing $SomeItem>>>> $LogFile> > Remove>>r >> $LogFile} else>{ >>
> Removed $Some>>em" >> $Log>il>
> >> >
>
> You can write error messages to the Event Log w>th>
>
> [Diagnostics.EventLog]::Wri *** try( .>. >
>
> The simplest form of that>is>
>
> [Diagnostics.EventLog]::Wri *** try("Source", "Messa>e">
>
> Which adds an entry to the Application Event >og>
>
> >ee>
>
> http://www.yqcomputer.com/ ;..>
>
> Chris