Using PowerShell to download file from private GitHub repository (using OAuth) - powershell

I have searched extensively for a solution but have yet to find success. I just want to be able to download files from my private GitHub repo using PowerShell. I want to use OAuth, not basic auth, so I have generated a token. But from here, none of the examples I've referenced worked for me. Best I could do was get a "Not Found" response.
An example of code I've tried is:
Invoke-WebRequest https://api.github.com/repos/MyAccount/MyRepo/contents/MyFile.txt -Headers #{"Authorization"="token 123456789012345678901234567890"} -OutFile C:\Temp\MyFile.txt
Result:
Invoke-WebRequest : {"message":"Not
Found","documentation_url":"https://docs.github.com/rest/reference/repos#get-repository-content"}
I'm fairly confident that I have the authentication right. I believe I just have the path wrong path to my file. Any help would be greatly appreciated.

Potential Duplicate use case relative to this SO discussion ...
PowerShell: retrieve file from GitHub
$url = 'https://github.com/mycompany/myrepo/blob/master/myscript.ps1'
$wc = New-Object -TypeName System.Net.WebClient
$wc.Headers.Add('Authorization','token your_token')
iex ($wc.DownloadString($url))
.. without Invoke-WebRequest of course.
See also:
Using PowerShell and oAuth
# Modified article code
Invoke-RestMethod https://api.github.com/repos/MyAccount/MyRepo/contents/MyFile.txt -Method Get -Headers #{"Authorization" = "Bearer $accessToken"}

I had to change the script in Powershell to get it working:
$credentials="<github_access_token>"
$repo = "<user_or_org>/<repo_name>"
$file = "<name_of_asset_file>"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "token $credentials")
$headers.Add("Accept", "application/json")
$download = "https://raw.githubusercontent.com/$repo/main/$file"
Write-Host Dowloading latest release
Invoke-WebRequest -Uri $download -Headers $headers -OutFile $file

Related

download openBLAS from SourceForge using PowerShell

I would like to use PowerShell to download openBLAS from SourceForge. My problem is that the PS documentation I have read always refers to a specific file name, but, when I submit that request, SF redirects it to /download, and something happens, but I don't get what I am looking for. Here is the current code:
$url = 'https://sourceforge.net/projects/openblas/files/v0.3.6/OpenBLAS-0.3.6-x64.zip'
# $url = 'https://sourceforge.net/projects/openblas/files/v0.3.6/OpenBLAS-0.3.6-x64.zip/download'
$output = 'C:\BLAS\OpenBLAS-0.3.6-x64.zip'
Invoke-WebRequest $url -OutFile $output
It works for me in Windows 10 PowerShell 5.1.
Invoke-WebRequest -Uri $url -OutFile $path -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::FireFox
source

How to download a file accepting license using powershell

I am trying to download package from the below link using powershell.
https://www.tenable.com/downloads/nessus-agents
i do not have direct link for these package also when i click on download it ask to agree. I was able to do it on Linux using command shown below. Kindly advise how can i do it in windows.
"wget --no-check-certificate --post-data='accept="I accept the terms of this license"&x=""&sid=5mcia8gchg28attkc9oarah153&p=NessusAgent-7.4.2-amzn.x86_64.rpm' 'https://www.tenable.com/downloads/nessus-agents' -O NessusAgent-7.4.2-amzn.x86_64.rpm"
could not find anything tried option with invoke-webrequest
Invoke-RestMethod -Uri 'https://www.tenable.com/downloads/nessus-agents'
There's a GET query string parameter that indicates acceptance.
Simply add i_agree_to_tenable_license_agreement=true to your query string parameters.
Invoke-WebRequest -Uri 'https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents/downloads/9762/download?i_agree_to_tenable_license_agreement=true' -OutFile 'NessusAgent-7.4.2-x64.msi'
You can easily get the IDs of the other files from their API endpoint like so:
(Invoke-WebRequest -Uri 'https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents' | ConvertFrom-Json).downloads | Format-Table -AutoSize
This is similar syntax in Powershell, but it's just downloading a file with contents "OK".
$body = 'accept="I accept the terms of this license"&x=""&sid=5mcia8gchg28attkc9oarah153&p=NessusAgent-7.4.2-amzn.x86_64.rpm'
$uri = 'https://www.tenable.com/downloads/nessus-agents'
$resp = Invoke-WebRequest -Method Post -Body $body -Uri $uri -OutFile .\NessusAgent-7.4.2-amzn.x86_64.rpm
Maybe the "sid" variable needs to change per request.

POSTing data to ServiceNow via Powershell using Invoke-WebRequest

I am trying to POST information into a table in ServiceNow via a Powershell script. When I run it I get an error
Invoke-WebRequest : The remote server returned an error: (500) Internal Server Error.
Can someone help me figure out how to solve this? Thank you all in advance.
$userName = 'helpMe'
$password = 'iAmStuck' | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $password)
$uri = 'stuff'
$postParams = "test"
#[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Invoke-WebRequest -Uri $uri -Method Post -Body $postParams -Credential $cred
ServiceNow has a REST API explorer with various code examples to start working with.
Below is an example that I threw together that posts to the incident table with an admin account. Two important factors here, the user must have roles (here for info https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/integrate/inbound-rest/reference/r_RESTAPIRoles.html) to use the API and must have access to the table you are trying to post to. Also, note that the body of the post needs to be RAW JSON and all the correct header data is supplied in the URL. If successful ServiceNow will return JSON data about the post.
# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "noPassword"
# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','application/json')
# Specify endpoint uri
$uri = "https://xxxxx.service-now.com/api/now/table/incident"
# Specify HTTP method
$method = "post"
# Specify request body
{request.body ? "$body = \"" :""}}{\"active\":\"true\",\"number\":\"123\",\"short_description\":\"test\"}"
# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $body
# Print response
$response.RawContent
Even though you posted code, you posted nothing relevant to the problem. Whatever ServiceNow is might have an API for reference on what it's expecting. Often when interacting with web-based APIs, there is a structure that is required for the API to be able to understand the data you're supplying in $postParams. Sometimes it can just be key->value pairs in the case of a flat HTTP POST but often times for RESTful APIs you'll need to structure a JSON header as defined by the API documentation.
If you do a search for "servicenow powershell interaction" it looks like there's a GitHub project for interacting with ServiceNow via PowerShell and also a PDF that specifcally covers this topic.

Invoke-WebRequest pass url as script argument (PowerShell)

I am trying to download file from the web using following command
Invoke-WebRequest $url -OutFile $filePath -Headers $Headers
I have argument, which contains this url and it is passed as parameter
[string]$artifactHttpAddress = $args[2]
Currently its value is
http://10.45.48.26/httpAuth/repository/downloadAll/TeamCityTest_Build/529:id/artifacts.zip
So, when I try to invoke WebRequest with following command
Invoke-WebRequest $artifactHttpAddress -OutFile c:/test.zip -Headers $Headers
it is downloading empty zip file .
but when I try to assign this url to the variable and invoke web request
$url = "http://10.45.48.26/httpAuth/repository/downloadAll/TeamCityTest_Build/529:id/artifacts.zip"
Invoke-WebRequest $url -OutFile c:/test.zip -Headers $Headers
It is working correctly, downloads zip file, which have some content in it.
I tried following script
Write-Host([string]$url -eq [string]$artifactHttpAddress)
Write-Host([string]$url)
Write-Host([string]$artifactHttpAddress)
It outputs
False
http://10.45.48.26/httpAuth/repository/downloadAll/TeamCityTest_Build/528:id/artifacts.zip
http://10.45.48.26/httpAuth/repository/downloadAll/TeamCityTest_Build/531:id/artifacts.zip
What is happening and why?
p.s. this script is inside ScriptBlock
It looks to me, based on your output, that $url and $artifactHttpAddress are not the same value. Does the ZIP file exist at the URL with 531 in it?

PowerShell Invoke-Webrequest not compatible with site?

I've seen many examples of Invoke-Webrequest and I've already had some success with it myself, however, one site where I was trying to automate my login just hasn't worked no matter what I try. Here is the code:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$r.forms[0].fields['form-login-header-email'] = "MyEmail"
$r.forms[0].fields['form-login-header-password'] = 'MyPassword'
$a = Invoke-WebRequest -Uri ("https://order.swisschalet.com" + $r.forms[0].Action) -WebSession $sc -Method POST -Body $r.forms[0]
I have tried using Fiddler 4 to analyze what is going on but it has only confused me even more. When I manually go to the website Fiddler shows 'email' and 'password' fields that were posted rather than what originally came back in the forms which is 'form-login-header-email' and 'form-login-header-password'. However, even if I try to create these new fields and POST them it still doesn't work. Fiddler shows that going to the website manually also creates some kind of synchronization token called 'org.codehaus.groovy.grails.SYNCHRONIZER_TOKEN'.
I am beginning to wonder if Invoke-WebRequest is simply incompatible with this site as I can never get the expected response where I can find my name in the $a.parsedHTML.DocumentElement.InnerText. Instead, when I view this I simply get the full page back telling me that my session has already expired.
I started to try this with the IE Com Object as well but this also did not seem to work. Am I missing something or is it just the way this site has been made? I've been struggling with this (really just to learn) for a couple of days now.
Thanks for any help!
If you send what it sends, to the place it sends it, you get logged in:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$form = #{
delegate='login'
id='null'
mode='save'
target='#form-login'
email='email#example.com'
password='password'
}
$a = Invoke-WebRequest -Uri "https://order.swisschalet.com/order/auth/index" -WebSession $sc -Method POST -Body $form
and it says
<span class="welcome-back">Welcome, <span class="username">TestingSome StuffForStackOverflo</span>
in the $a.RawContent result. So I guess it's not incompatible.