Search code examples
jsonpowershellnewlinewindows-server-2016invoke-webrequest

Why Add-Content in Windows Server 2016 is writing the text on a single line instead of on multiple lines like my Windows 10 PC?


I'm working with a script to search for places in Google Maps using their API. I use my local PC (Windows 10) as my development environment. The part of the code that matters is below:

$api_call_url ="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lon&radius=$rad&type=$place_type&key=$Api_Key"
$api_call_response=Invoke-WebRequest $api_call_url
$api_call_obj = ConvertFrom-Json -InputObject $api_call_response
Add-Content "$file_name_json" $api_call_response

The json returned by Google is stored in the $api_call_response variable and then appended to a text file using Add-Content. Once the script was completed and tested, I moved it to the production environment (Windows Server 2016 Std). Ran the script and found out that the way the json is written to the text file is different.

This is what is written to the text file from my Windows 10 PC (multiple lines for each result)

{
    "html_attributions" : [],
    "results" : [],
    "status" : "ZERO_RESULTS"
}

{

    "html_attributions" : [],
    "results" : [],
    "status" : "ZERO_RESULTS"
}

This is what is written to the text file from my Windows Server 2016 (One line each result)

 {   "html_attributions" : [],   "results" : [],   "status" : "ZERO_RESULTS"}
 {   "html_attributions" : [],   "results" : [],   "status" : "ZERO_RESULTS"}

If I write-output the variable $api_call_response to screen, it displays with multiple lines.

I need the output with multiple lines because there is another script that cleans the file from results that I do not need and since the resulting text file is lots of jsons appended, it creates only one json file from all jsons. But it expect the results file the way my development environment writes it. Obviously, I'm trying to avoid modifying the cleaning script.

PSVersion on Windows Server 2016: 5.1.14393.3053
PSVersion on Windows 10: 5.1.17763.771

Any Thoughts?


Solution

  • If it's a matter of converting unix text (\n) to windows text (\r\n):

    get-content file1 | set-content file2
    

    Or with the same file:

    (get-content file) | set-content file
    

    Notepad can't display unix text correctly, but Wordpad can. (Although Notepad can handle unicode no bom.)

    Other conversion methods: Unix newlines to windows newlines (on Windows)