Getting a session cookie using powershell - powershell

I'm trying to get a session cookie using PowerShell and InternetExplorer.Application but nothing seems to work.
There is no $ie.Document.cookie variable.
The session cookie is not available to JavaScript(because it is http-only)
# Create an ie com object
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.visible = $true;
$ie.navigate2("https://www.example.com/login");
# Wait for the page to load
while ($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
#Add login details
$ie.Document.getElementById("username").value = "user";
$ie.Document.getElementById("password").value = "1234";
$ie.Document.getElementsByName("login_button")[0].Click();
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$div = $ie.Document.getElementsByTagName('div')[0];
$ie.navigate("javascript: window.location=document.cookie.match(new RegExp('(^| )csrf_token=([^;]+)'))[2]");
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$csrf = $ie.LocationUrl.Substring(32);
echo $csrf;
#Stop-Process -Name iexplore
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$cookie = New-Object System.Net.Cookie
$cookie.Name = "user_name"
$cookie.Value = "user"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);
$cookie = New-Object System.Net.Cookie
$cookie.Name = "user_session_id"
$cookie.Value = "What I need"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);
Invoke-WebRequest -URI "https://www.example.com/demo/my_file&csrf_token=$csrf" -WebSession $session -OutFile 'finally.zip';
echo 'Done!';
Note that the only way I found to get the csrf is to use javascript to get the value to the url, but I can't do it with the user_session_id because it is marked as http_only.

Take a look at these options to incorporate into what you already have.
First, get the cookies
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
Get-Content .\cookie.txt |
foreach {
$line = $_ -split '/' | select -First 1
$tokens=$line.Split("`t").TrimEnd()
$c = #{
name=$tokens[0]
value=$tokens[1]
domain=$tokens[2]
}
$cookie = New-Object System.Net.Cookie
$cookie.Name=$c.name
$cookie.Value=$c.Value
$cookie.Domain=$c.domain
$session.Cookies.Add($cookie)
}
Getting Cookies using PowerShell
Here are two straightforward ways to get website cookies within PowerShell.
$url = "https://www.linkedin.com"
$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession
$cookies = $websession.Cookies.GetCookies($url)
# Here, you can output all of $cookies, or you can go through them one by one.
foreach ($cookie in $cookies) {
# You can get cookie specifics, or just use $cookie
# This gets each cookie's name and value
Write-Host "$($cookie.name) = $($cookie.value)"
}

Related

Powershell hanging in script

I have written a script that will extract a large number of URLs from an excel spreadsheet and then make a web request and fetch the certificate information.
I am very new to powershell and have never worked to debug or process exception/error handling.
In my process there are certain points the script will just hang, no error is thrown and it does not terminate, just hangs for and indefinite period of time. Sometimes its a couple minutes other times a couple seconds.
I am trying to figure out if I can correct something in my code or if this hang is simply because of the servers I am contacting.
function GetCertificates($url) {
# // create a request
$req = [System.Net.WebRequest]::create($url)
$req.Method = "GET"
$req.Timeout = 600000 # = 10 minutes
# // set the proxy for connection
$proxy = New-Object System.Net.WebProxy "proxy.com:8000"
$req.Proxy = $proxy
# // Set if you need a username/password to access the resource
$Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
#$req.Credentials = New-Object Net.NetworkCredential("username", "password");
$req.Credentials = $Credentials
$req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT; Windows NT 6.1; en-US)"
try {
[Net.HttpWebResponse] $result = $req.GetResponse()
}
catch {}
# // define the cert
$cert = ''
$cert = $req.ServicePoint.Certificate
$httpstatuscode = [int]$result.StatusCode
try {
[IO.Stream] $stream = $result.GetResponseStream()
[IO.StreamReader] $reader = New-Object IO.StreamReader($stream)
[string] $output = $reader.readToEnd()
$stream.flush()
$stream.close()
}
catch {}
# // write the results
Write-host $url
Write-host "Issued By : " $cert.Issuer
#Write-host "Subject : " $cert.Subject
#Write-host "Issued On : " $cert.GetEffectiveDateString()
#Write-host "Expires On : " $cert.GetExpirationDateString()
}
function GetExcel{
# // import the csv file
$xcel = import-csv C:\Users\Desktop\excel.csv
# // extract and run the URLs for only required TYPEs
$xcel | foreach{
if
($_.TYPE -like "u_external_url" -or "qa_url" -or "u_load_balancing_url")
{GetCertificates $_.URL}
return $_.APP_ID
}
}

PowerShell Script RESTful API Binance URI structure

I try to write a PowerShell Script and test it using https://api.binance.com/api/v3/order/test REST link but it doesn't work. I can't understand what should I use as message, what as body and what as header. It seems that here everything is clear and when I see a linux example I should have the same link in Output:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
Could someone who understands REST Post method help me to figure out what should I change here.
My output is:
POST https://api.binance.com/api/v3/order/test?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1515586306172&signature=LxHZUfC5MiTUfMPyEtgaVShlV1j4ITo3QxvtPAzPkwQ=
Many thanks in advance.
$apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$unixEpochStart = Get-Date -Date "01/01/1970"
$now = Get-Date
$timestamp = (New-TimeSpan -Start $unixEpochStart -End $now.ToUniversalTime()).TotalMilliseconds
$timestamp = ([math]::Round($timestamp, 0)).ToString()
$apimessage = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=$timestamp"
$apisecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($apisecret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($apimessage))
$signature = [Convert]::ToBase64String($signature)
$uri = "https://api.binance.com/api/v3/order/test?$apimessage&signature=$signature"
$header = #{
"X-MBX-APIKEY" = $apiKey
}
Invoke-RestMethod -Method Post -Uri $uri -Headers $header -Verbose
The issue is this line of code:
$signature = [Convert]::ToBase64String($signature)
Binance expects the HMAC SHA256 transmitted in hex form. Replace the above with this and the issue should be resolved.
$signature = [System.BitConverter]::ToString($signature).Replace('-', '').ToLower()
Below is my working code.
APIKey and Secret are from the example of the Binance API doc
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#signed-endpoint-examples-for-post-apiv1order
Result of $Signature should be the same as in the Binance example: c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
If you use your own APIKey and Secret it should be working
$APIKey = "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A"
$APISecret = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
$TimeStamp = (Get-Date (Get-Date).ToUniversalTime() -UFormat %s).replace(',', '').replace('.', '').SubString(0,13)
$QueryString = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($APISecret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($QueryString))
$signature = [System.BitConverter]::ToString($signature).Replace('-', '').ToLower()
$uri = "https://api.binance.com/api/v3/account?$QueryString&signature=$signature"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-MBX-APIKEY",$APIKey)
try {
Invoke-RestMethod -Uri $uri -Headers $headers -Method Get
}
Catch {
$streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json
$streamReader.Close()
$ErrResp
}
below all the functions you need to request the Binance API.
Reference: https://blog.p-difm.com/interact-with-your-binance-account-using-the-api-and-powershell/
function Get-UnixTimeStamp{
<#
.SYNOPSIS
Return the timestamp in millisecond of the Unix Epoch
.DESCRIPTION
Unix Epoch started the Thursday, January 1, 1970 12:00:00 AM. The function return the number of second from that time.
.EXAMPLE
Get-UnixTimeStamp
#>
param(
)
return $(Get-Date (Get-Date).ToUniversalTime() -UFormat %s).replace(',', '').replace('.', '').SubString(0,13)
}
function Get-BinanceAPISignature{
<#
.SYNOPSIS
Prepare the signature that will be sent with the API request
.DESCRIPTION
Endpoint requires sending a valid API-Key and signature
.PARAMETER QueryString
The queryString must contains the symobol, timestamp and a recvWindow
.PARAMETER EndPoint
The EndPoint you want to request
.EXAMPLE
$URI = Get-BinanceAPISignature -QueryString $QueryString -EndPoint "/api/v3/openOrders"
#>
param(
[Parameter(Mandatory=$true)]$QueryString,
[Parameter(Mandatory=$true)]$EndPoint
)
$APISecret = "ASDHFASUHDFIOUSAHlUGLULUHALUHliuhalushduauauhIUH"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($APISecret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($QueryString))
$signature = [System.BitConverter]::ToString($signature).Replace('-', '').ToLower()
$URI = "https://api.binance.com$($EndPoint)?$QueryString&signature=$signature"
return $URI
}
function Get-BinanceAPIHeader{
<#
.SYNOPSIS
Prepare the header that will be sent with the API request
.DESCRIPTION
The header include your APIKey
.PARAMETER
#APIKey
.EXAMPLE
Get-BinanceAPIHeader
#>
param(
)
$APIKey = "HDAUSHF3989898hiuHGhuhI987898HiuahsduhaiusduhUIH"
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("X-MBX-APIKEY",$APIKey)
return $Headers
}
function Request-API{
<#
.SYNOPSIS
Run the CURL command with defined parameters
.DESCRIPTION
Call the API and error handling. Return the result of the request
.PARAMETER Method
Choose a method according to the EndPoint
.PARAMETER URI
This parameter needs to be obtained with Get-BinanceAPISignature
.PARAMETER Headers
This parameter needs to be obtained with Get-BinanceAPIHeaderx
.EXAMPLE
$ObjResults = Request-API -Method Get -URI $URI -Headers $Headers
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)][ValidateSet("POST","GET","DELETE")]$Method,
[Parameter(Mandatory=$true)]$URI,
[Parameter(Mandatory=$true)]$Headers
)
try{
$ArrayJsonResult = Curl $URI -Method $Method -Headers $Headers #-Verbose
$ObjCustomResult = $ArrayJsonResult.Content | ConvertFrom-Json
}
catch{
$streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json
$streamReader.Close()
$LastError = $Error[0].ErrorDetails.Message | ConvertFrom-Json
write-host "1: " $ErrResp -b Red
write-host "2: " $LastError.code -b Red
write-host "3: " $LastError.msg -b Red
switch ($LastError.code){
("-1105") {write-host "TimeStamp issue"}
("-1003") {write-host "Too much request, IP Banned"; break}
("-2010") {write-host "Stop price would trigger immediately or Account has too many open stop loss and/or take profit orders on the symbol."}
("-1013") {write-host "The amount is not enough for this currency or not following the step size rule for the symbol."}
("-1111") {write-host "Too many decimal check the precision required with Get-ExchangeInfo"}
}
}
return $ObjCustomResult
}
And here an example how to use it
Reference: https://blog.p-difm.com/new-order-with-api-binance-and-powershell/
function New-Order{
<#
.SYNOPSIS
Place an order to buy or sell crypto
.PARAMETER Symbol
The crypto you want to buy or sell
.PARAMETER Side
ValidateSet "BUY" or "SELL"
.PARAMETER OrderType
ValidateSet "OrderMarket" or "OrderLimit" or "OrderStopLimit"
.PARAMETER Quantity
Specifies the amount you want to spend (when buying) or receive (when selling)
.PARAMETER FiatAmount
specifies the amount you want to spend in USDT
.EXAMPLE
New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderMarket -FiatAmount 20 -Verbose
.EXAMPLE
New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderLimit -FiatAmount 1000 -Price 33000
.EXAMPLE
New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderStopLimit -Quantity 0.002 -Price 33000 -StopPrice 36000
.EXAMPLE
New-Order -Symbol XRPUSDT -Side SELL -OrderType OrderLimit -Quantity 100 -Price 0.5
.EXAMPLE
New-Order -Symbol XRPUSDT -Side SELL -OrderType OrderStopLimit -Quantity 100 -Price 0.55 -StopPrice 0.5
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Symbol,
[Parameter(Mandatory=$true)]
[ValidateSet("BUY", "SELL")]
[string]$Side,
[Parameter(Mandatory=$true)]
[ValidateSet("OrderMarket", "OrderLimit", "OrderStopLimit")]
[string]$OrderType,
[Parameter(Mandatory=$true, ParameterSetName = 'quantity')]
[double]$Quantity,
[Parameter(Mandatory=$true, ParameterSetName = 'quantity2')]
[double]$FiatAmount
)
DynamicParam{
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
if ($OrderType -ne "OrderMarket"){
# price param
$attributes = New-Object -Type System.Management.Automation.ParameterAttribute
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Price", [double], $attributeCollection)
$paramDictionary.Add("Price", $dynParam1)
}
if ($OrderType -eq "OrderStopLimit"){
# StopPrice param
$attributes2 = New-Object -Type System.Management.Automation.ParameterAttribute
$attributes2.Mandatory = $true
$attributeCollection2 = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection2.Add($attributes2)
$dynParam2 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("StopPrice", [double], $attributeCollection2)
$paramDictionary.Add("StopPrice", $dynParam2)
}
return $paramDictionary
}
BEGIN{
# Check prerequisit
try{
Get-Command -Name Get-UnixTimeStamp -ErrorAction Stop | out-null
Get-Command -name Get-BinanceAPISignature -ErrorAction Stop | Out-Null
Get-Command -Name Get-BinanceAPIHeader -ErrorAction Stop | Out-Null
Get-Command -Name Request-API -ErrorAction Stop | Out-Null
}
catch{
Write-Host "Load Get-UnixTimeStamp, Get-BinanceAPISignature, Get-BinanceAPIHeader, Request-API first prior to laod the current script" -b red
Break
}
$TimeStamp = Get-UnixTimeStamp
# retrieve value from dyn param
if ($OrderType -ne "OrderMarket"){
$Price = $paramDictionary.values[0].value[0]
$StopPrice = $paramDictionary.values[0].value[1]
}
switch($OrderType){
"OrderMarket"{
if($PSBoundParameters.ContainsKey('Quantity')){
$QueryString = "symbol=$Symbol&side=$Side&type=MARKET&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
}
else{
$QueryString = "symbol=$Symbol&side=$Side&type=MARKET&quoteOrderQty=$FiatAmount&timestamp=$TimeStamp&recvWindow=5000"
}
}
"OrderLimit"{
if($PSBoundParameters.ContainsKey('FiatAmount')){
$CurrentPrice = Get-Price -Symbol $Symbol -Decimal 8
$Quantity = [math]::Round($FiatAmount / $CurrentPrice, 6)
}
$QueryString = "symbol=$Symbol&side=$Side&type=LIMIT&price=$Price&timeInForce=GTC&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
}
"OrderStopLimit"{
if($PSBoundParameters.ContainsKey('FiatAmount')){
$CurrentPrice = Get-Price -Symbol $Symbol -Decimal 0
$Quantity = [math]::Round($FiatAmount / $CurrentPrice, 6)
}
$QueryString = "symbol=$Symbol&side=$Side&type=TAKE_PROFIT_LIMIT&stopPrice=$StopPrice&price=$Price&timeInForce=GTC&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
}
}
}
PROCESS{
$URI = Get-BinanceAPISignature -QueryString $QueryString -EndPoint "/api/v3/order"
$Headers = Get-BinanceAPIHeader
$ObjResults = $null # need to do this?
$ObjResults = Request-API -Method POST -URI $URI -Headers $Headers
}
END{
return $ObjResults
}
}

Powershell invoke-webrequest for powershell 2.0

I have created a script in powershell 5.0 that retrieves a data in the website and puts it inside a file. The following code works on windows 7 and higher since they all have .net framework 5.0. Now I was informed that i needs to run on lower windows OS such as XP. powershells in XP is 2.0, and microsoft already ended XP support. I need a powershell 2.0 code that would behaves the same as the code I have written in 5.0:
$number = 1000
$startdate = 2017-01-05
$enddate = 2017-01-11
invoke-webrequest -Uri http://192.168.1.1/form/Download?uid=$number"&"sdate=$startdate"&"edate=$enddate -OutFile D:\Timekeeping\dtr\data.dat -PassThru
There is no direct cmdlet for an alternative:
But you can use the below:
$URI1 = "<your uri>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential
# $request | Get-Member for a list of methods and properties
try
{
$requestStream = $request.GetRequestStream()
$streamWriter = New-Object System.IO.StreamWriter($requestStream)
$streamWriter.Write($body)
}
finally
{
if ($null -ne $streamWriter) { $streamWriter.Dispose() }
if ($null -ne $requestStream) { $requestStream.Dispose() }
}
$res = $request.GetResponse()
So basically we are using the Dot Net Class for it :
$request = [System.Net.WebRequest]::Create("$url")
$request.ContentType='application/json; charset=utf-8'
$request.GetResponse()
You can parse it stream wise :
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$Data=$ReadStream.ReadToEnd()
Hope it helps.

SSRS and PowerShell: Get report as Excel

I'm trying to make PowerShell send a web request to our SSRS server and capture the results. I've hit a wall using the rs:FORMAT=EXCEL parameter in the SSRS url string. I have the following:
First, init the credentials:
$User = "MYDOMAIN\MyUser"
$PWord = ConvertTo-SecureString -String "WooHooStringP$W0rd" -AsPlainText -Force
$c = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
Now, request a report:
Invoke-WebRequest `
-UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer) `
-Credential $c `
-Uri "http://myserver/ReportServer_DEV/Pages/ReportViewer.aspx?/folder+path/report+name"
This works fine. I can even grab the results (enclosing this request and using ().Content).
Then, specify a format instead of plain rendering:
Invoke-WebRequest `
-UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer) `
-Credential $c `
-Uri "http://myserver/ReportServer_DEV/Pages/ReportViewer.aspx?/folder+path/report+name&rs:format=HTML4.0"
Note the rs:Format specification? Works like a charm.
Then, for the grande finale, give me an Excel file:
Invoke-WebRequest `
-UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer) `
-Credential $c `
-Uri "http://myserver/ReportServer_DEV/Pages/ReportViewer.aspx?/folder+path/report+name&rs:format=EXCEL"
No can do, bud:
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
At line:1 char:11
+ $bytez = (Invoke-WebRequest `
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Why does the rs:format=EXCEL option throw an Unauthorised exception where all the other URLs are served by SSRS?
I've figured it out! I went about this the wrong way: SSRS offers access through a webservice that PowerShell can consume without the need to hack the URL and capture a response. I found a script that did this and modified it to suit my purpose:
function GetRSConnection($server, $instance)
{
# Create a proxy to the SSRS server and give it the namespace of 'RS' to use for
# instantiating objects later. This class will also be used to create a report
# object.
$User = "DOMAIN\Username"
$PWord = ConvertTo-SecureString -String "Pa$$w0rd" -AsPlainText -Force
$c = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
$reportServerURI = "http://" + $server + "/" + $instance + "/ReportExecution2005.asmx?WSDL"
$RS = New-WebServiceProxy -Class 'RS' -NameSpace 'RS' -Uri $reportServerURI -Credential $c
$RS.Url = $reportServerURI
return $RS
}
function GetReport($RS, $reportPath)
{
# Next we need to load the report. Since Powershell cannot pass a null string
# (it instead just passses ""), we have to use GetMethod / Invoke to call the
# function that returns the report object. This will load the report in the
# report server object, as well as create a report object that can be used to
# discover information about the report. It's not used in this code, but it can
# be used to discover information about what parameters are needed to execute
# the report.
$reportPath = "/" + $reportPath
$Report = $RS.GetType().GetMethod("LoadReport").Invoke($RS, #($reportPath, $null))
# initialise empty parameter holder
$parameters = #()
$RS.SetExecutionParameters($parameters, "nl-nl") > $null
return $report
}
function AddParameter($params, $name, $val)
{
$par = New-Object RS.ParameterValue
$par.Name = $name
$par.Value = $val
$params += $par
return ,$params
}
function GetReportInFormat($RS, $report, $params, $outputpath, $format)
{
# Set up some variables to hold referenced results from Render
$deviceInfo = "<DeviceInfo><NoHeader>True</NoHeader></DeviceInfo>"
$extension = ""
$mimeType = ""
$encoding = ""
$warnings = $null
$streamIDs = $null
# Report parameters are handled by creating an array of ParameterValue objects.
# Add the parameter array to the service. Note that this returns some
# information about the report that is about to be executed.
# $RS.SetExecutionParameters($parameters, "en-us") > $null
$RS.SetExecutionParameters($params, "nl-nl") > $null
# Render the report to a byte array. The first argument is the report format.
# The formats I've tested are: PDF, XML, CSV, WORD (.doc), EXCEL (.xls),
# IMAGE (.tif), MHTML (.mhtml).
$RenderOutput = $RS.Render($format,
$deviceInfo,
[ref] $extension,
[ref] $mimeType,
[ref] $encoding,
[ref] $warnings,
[ref] $streamIDs
)
# Determine file name
$parts = $report.ReportPath.Split("/")
$filename = $parts[-1] + "."
switch($format)
{
"EXCEL" { $filename = $filename + "xls" }
"WORD" { $filename = $filename + "doc" }
"IMAGE" { $filename = $filename + "tif" }
default { $filename = $filename + $format }
}
if($outputpath.EndsWith("\\"))
{
$filename = $outputpath + $filename
} else
{
$filename = $outputpath + "\" + $filename
}
$filename
# Convert array bytes to file and write
$Stream = New-Object System.IO.FileStream($filename), Create, Write
$Stream.Write($RenderOutput, 0, $RenderOutput.Length)
$Stream.Close()
}
$RS = GetRSConnection -server "DEVBOX" -instance "ReportServer_DEV"
$report = GetReport -RS $RS -reportPath "folder name/report name"
$params = #()
$params = AddParameter -params $params -name "Month" -val "201311"
GetReportInformat -RS $RS -report $report -params $params -outputpath "i:\test" -format "EXCEL"
Using web request:
[string]$Domain = "DomainUsername"
[string]$Username = "Username"
[string]$Password = "Password"
[string]$ReportServer = "http://ssrsreportserver/ReportServer/ReportExecution2005.asmx" #Report Server
[string]$ReportLocation = "/Report Location/Report Name" #Report Location ON SSRS
$ReportLocation = $ReportLocation.Replace("/", "%2f")
$ReportLocation = $ReportLocation.Replace(" ", "+")
[string]$outputFile = $PSScriptRoot + '\Report.xlsx' #Save location for the file
#If the report has any parameters
[string]$ParamString = "";
$ParamString += "&param1=paramvalue"
$ParamString += "&param2=paramvalue"
[string]$URL = $ReportServer + "?" + $ReportLocation + "&rs:Command=Render&rs:Format=" + "EXCELOPENXML" + "&rs:ParameterLanguage=en-GB" + $ParamString
Write-Host $URL
$Req = [System.Net.WebRequest]::Create($URL);
$Req.Credentials = new-object System.Net.NetworkCredential($Username, $Password, $Domain)
$Req.Timeout = 30000;
$WebStream = $Req.GetResponse().GetResponseStream();
$MemStream = New-Object System.IO.MemoryStream
$WebStream.CopyTo($MemStream);
[long]$Len = $MemStream.Length;
[byte[]]$outBytes = [System.Byte[]]::CreateInstance([System.Byte], $Len)
$MemStream.Seek(0, [System.IO.SeekOrigin]::Begin);
$MemStream.Read($outBytes, 0, [int]$Len);
$WebStream.Close();
$MemStream.Close();
$MemStream.Dispose();
$Stream = New-Object System.IO.FileStream($outputFile), Create, Write
$Stream.Write($outBytes, 0, $outBytes.Length)
$Stream.Close()
Invoke-Item $outputFile

Powershell Http post request

Read over the stackoverflow for the answer, still can't find what causing this..
Trying to connect and send a POST request using powershell, and getting "unable to connect to remote server" error. Tried 3 different dummy servers like http://posttestserver.com/post.php
Script:
Get-ExecutionPolicy
[string]$url = "http://posttestserver.com/post.php"
function Execute-HTTPPostCommand()
{
param([string]$target = $null)
#$username = "administrator"
#$password = "mypass"
$webRequest = [System.Net.WebRequest]::Create($target)
$webRequest.ContentType = "text/html"
$post = "abcdefg"
$PostStr = [System.Text.Encoding]::UTF8.GetBytes($Post)
$webrequest.ContentLength = $PostStr.Length
$webRequest.ServicePoint.Expect100Continue = $false
#$webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
#$webRequest.PreAuthenticate = $true
$webRequest.Method = "POST"
try
{
$requestStream = $webRequest.GetRequestStream()
}
catch
{
write-host $_.Exception
}
$requestStream.Write($PostStr, 0,$PostStr.length)
$requestStream.Close()
[System.Net.WebResponse]$resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
[string]$results = $sr.ReadToEnd();
return $results;
}
Execute-HTTPPostCommand $url
[System.GC]::Collect()