Joey Joey - 4 months ago 23
PowerShell Question

Creating log file in powershell

I have a powershell program that checks if the site is responding and retrieves data and put it inside a file using invoke-webrequest function. I want to log the response status (200 or either way) of the request with the current date and time of the request. Below is a working script. The only problem is I don't know how to concatenate my datetime variable and my status variable (separated by a space) in a single line in the log file.

$Logfile = "D:\PROJECTS\mylog.log"
Function LogWrite
Param ([string]$logstring)

Add-content $Logfile -value $logstring
$datetime = get-date

$x = invoke-webrequest -Uri http://somesite/form/Download?uid=$number"&"sdate=$startdate"&"edate=$enddate -OutFile D:\PROJECTS\Timekeeping\build_src\$Branch-$enddate.dat -PassThru
if($x.StatusCode -eq 200){
LogWrite $datetime
LogWrite $x.StatusCode
LogWrite $datetime
LogWrite $x.StatusCode

The result of my mylog.log is:

08/24/2016 18:43:27 its alive!
08/24/2016 18:43:27

I want it to be like

08/24/2016 18:43:27 its alive!
08/24/2016 18:43:27 200

I tried

LogWrite $datetime+$x.StatusCode


LogWrite $datetime+" "+$x.StatusCode

But to no avail.

LogWrite "$datetime $($x.StatusCode)"

Using $( <code> ) within a string will evaluate the contents of the brackets first then convert the result into the string. Note:You will need to use double quotes.