0

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
    }else{
        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 
    200

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

and

    LogWrite $datetime+" "+$x.StatusCode

But to no avail.

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

Add-Content supports -NoNewLine:

Indicates that this cmdlet does not add a new line/carriage return to the content.

I would follow the Console.Write vs. Console.WriteLine metaphor:

Function LogWriteLine
{
   Param ([string]$logstring)

   Add-content $Logfile -value $logstring
}

Function LogWrite
{
   Param ([string]$logstring)

   Add-content $Logfile -NoNewLine -value $logstring
}

...

LogWrite $datetime
LogWrite ' '
LogWriteLine $x.StatusCode

This allows you to simply output in loops, for example, without having to first build up a in-memory string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.