Search code examples
c#.netpowershellhttpwebrequest

write httpwebresponse to file--powershell--short and sweet (piping)


I am trying to write the httpWebResponse to a file using powershell. The original script was in cURL,but I am trying to use .NET classes to do it. I can get the request (either post or delete) to work, but I am having a hard time getting the response to write to a text file correctly. Is there a way to use piping instead of/with streamReader and Writer?

Because this is a succinct script, I would like to avoid the lines of code that come with streamreader and streamwriter if I can help it. What is the best way to write the responsestream to a text file in the smallest amount of code in powershell? Can piping do it? I'm assuming it would look like

|add-content $filename

but what would go on the left?

Here is my Delete call.

[System.Reflection.Assembly]::LoadWithPartialName("System.Net")
write-host Deleting $database
$delRequest = [Net.HttpWebRequest]::Create("$DestinationRoot$database")
$delRequest.Method = "DELETE"
$delRequest.ContentType = "application/json"
$authorization = [System.Convert]::ToBase64String([System.Text.ASCIIEncoding]::ASCII.GetBytes("username" + ":" + "password")) 
$delRequest.Headers.Add("Authorization", "Basic " + $authorization)
[Net.HttpWebResponse] $delResponse = $delRequest.GetResponse() 
$delReader = new-object System.IO.StreamReader $delResponse.GetResponseStream() 
[System.IO.FileStream] $delStream = [System.IO.File]::Open($Log,[System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Write)
$delWrt = new-object IO.StreamWriter $delStream
while(-not $delReader.EndOfStream)
{
 $delWrt.WriteLine($delReader.ReadLine()) 
}
$delWrt.Close()     

This works, but I would much rather use a pipe if it can save me lines of code. cURL can do this all in about 5 lines, so the simpler I can make it, the better.


Solution

  • You can replace everything below $delReader = ... with the .ReadToEnd() method on the stream, and pipe that to a file.

    $delReader = new-object System.IO.StreamReader $delResponse.GetResponseStream() 
    $delReader.ReadToEnd() | Out-File $logFile