I'm trying to create a command in Powershell that is an equivalent of
curl -u username:abcd -i -F name=files -F filedata=#employees.csv https://myservice.com/v1/employees/csv
I need to have file name in the request. So in Powershell
$FilePath = 'employees.csv'
$FieldName = 'employees.csv'
$ContentType = 'text/csv'
$username = "user"
$password = "..."
$FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open)
$FileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new('form-data')
$FileHeader.Name = $FieldName
$FileHeader.FileName = Split-Path -leaf $FilePath
$FileContent = [System.Net.Http.StreamContent]::new($FileStream)
$FileContent.Headers.ContentDisposition = $FileHeader
$FileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($ContentType)
$MultipartContent = [System.Net.Http.MultipartFormDataContent]::new()
$MultipartContent.Add($FileContent)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($username):$($password)" ))
$Response = Invoke-WebRequest -Headers #{Authorization = "Basic $base64AuthInfo" } -Body $MultipartContent -Method 'POST' -Uri 'https://myservice.com/v1/employees/csv'
Is there a better (shorter) way of doing this so I have a file name in Content Disposition?
$body = get-content employees.csv -raw
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("user:pass" ))
Invoke-RestMethod -Headers #{Authorization = "Basic $base64AuthInfo" } -uri url -Method Post -body $body -ContentType 'text/csv
# a flag -ContentDispositionFileName would be great
Taking a guess with what your endpoint will accept, but here's an example of your curl request in powershell:
$u, $p = 'username', 'password'
$b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${u}:$p"))
$invokerestmethodParams = #{
'Uri' = 'https://myservice.com/v1/employees/csv'
'Method' = 'POST'
'Headers' = #{ Authorization = "Basic $b64" }
'InFile' = 'C:\path\to\employees.csv'
'SessionVariable' = 's' # use $s to view content headers, etc.
}
$output = Invoke-RestMethod #invokerestmethodParams
Related
I am having an issue related to the encoding.
$usermailactivitydetail = Invoke-RestMethod -uri $uri -headers $headers -ContentType "text/plain; charset=utf-8"
$usermailactivitydetail variable :
İç test01 Bölge)
https://learn.microsoft.com/en-us/graph/api/reportroot-getemailactivityuserdetail?view=graph-rest-1.0
script:
$appid = 'APPID'
$tenantid = 'TENANTID'
$secret = 'SECRETID'
$body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $appid
Client_Secret = $secret
}
$ConnectionParameters=#{
Uri="https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token"
Method ="POST"
Body = $body
}
$connection = Invoke-RestMethod #ConnectionParameters
$token = $connection.access_token
Connect-MgGraph -AccessToken $token
$headers = #{"Authorization" = "Bearer "+ $token}
$uri = "https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='D7')"
thanks,
UPDATE :
$usermailactivitydetail = Invoke-RestMethod -uri $uri -headers $headers
$result = $usermailactivitydetail.Replace('Report Refresh Date','Report Refresh Date')
$resultarray = ConvertFrom-Csv -InputObject $result
#Export result to CSV
$resultarray | Export-Csv "C:\output.csv" -NoTypeInformation -encoding utf8
As Jeroen suggested, try to download to a file to prevent Invoke-RestMethod from trying to interpret the data and get the encoding wrong. The file will contain the raw response from the server. Then force the encoding when reading the file through PowerShell.
$tempFilePath = (New-TemporaryFile).Fullname
Invoke-RestMethod -uri $uri -headers $headers -OutFile $tempFilePath
$usermailactivitydetail = Import-Csv $tempFilePath -Encoding UTF8
Remove-Item $tempFilePath
The script below works fine to check a single URL, but what is the simplest way to check a list of URL's in one query? Turning $URL into an array doesn't work (only the first entry is checked).
$HEADERS = #{ 'Content-Type' = "application/json" }
$GOOGLE_API_KEY='[API Key]'
$Uri = 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key='+ $GOOGLE_API_KEY
$URL = 'http://www.sitetocheck.com'
$BODY = #()
$BODY +=[pscustomobject]#{"client" = #{"clientId" = "company"; "clientVersion" = "1.0"}; "threatInfo" = #{"threatTypes" = "MALWARE","SOCIAL_ENGINEERING","THREAT_TYPE_UNSPECIFIED","UNWANTED_SOFTWARE","POTENTIALLY_HARMFUL_APPLICATION"; "platformTypes" = "ANY_PLATFORM"; "threatEntryTypes" = "URL"; "threatEntries" = #{"url" = $URL}}}
$JSONBODY = $BODY | ConvertTo-Json
Invoke-RestMethod -Method 'POST' -Uri $Uri -Body $JSONBODY -Headers $HEADERS
If you look at your existing code, you'll find that the only thing deriving it's value from the target URL is the request body.
Prepare your URL values as an array, then take the code that creates the request body and calls Invoke-RestMethod, and put that inside a loop (or ForEach-Object):
$URLs = 'http://www.sitetocheck.com','http://www.othersitetocheck.com','http://somethingelse.com'
$HEADERS = #{ 'Content-Type' = "application/json" }
$GOOGLE_API_KEY='[API Key]'
$Uri = 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key='+ $GOOGLE_API_KEY
foreach($URL in $URLs) {
$BODY = #([pscustomobject]#{"client" = #{"clientId" = "company"; "clientVersion" = "1.0"}; "threatInfo" = #{"threatTypes" = "MALWARE","SOCIAL_ENGINEERING","THREAT_TYPE_UNSPECIFIED","UNWANTED_SOFTWARE","POTENTIALLY_HARMFUL_APPLICATION"; "platformTypes" = "ANY_PLATFORM"; "threatEntryTypes" = "URL"; "threatEntries" = #{"url" = $URL}}})
$JSONBODY = $BODY | ConvertTo-Json
Invoke-RestMethod -Method 'POST' -Uri $Uri -Body $JSONBODY -Headers $HEADERS
}
I am trying to upload a pdf file into Right fax via the RightFax Web Api. I can do this via PostMan and I am able to send the attachment afterwards. When I try do upload via PowerShell an I send my attachment I only get the Object Name in the actual fax ex. System.Net.Http.StreamContent. Here is my borrowed powershell code:
Add-Type -AssemblyName System.Net.Http
$AuthURL = "http://" + $RESTAPIServer + "/RightFax/API"
$BaseURL = "http://" + $RESTAPIServer + "/RightFax/API/SendJobs"
$AttachURL = "http://" + $RESTAPIServer + "/RightFax/API/Attachments"
$Base = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))
$vCenterSessionURL = $BaseAuthURL
$Header = #{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))}
$TARGET_FOLDER_PATH = "\\SomeFolderPath\"
$TokenUri = "http://" + $RESTAPIServer + "/RightFax/API/Login?rememberMe={rememberMe}"
$Token = Invoke-RestMethod -Method GET -Headers $Header -Uri $TokenUri
Get-ChildItem $TARGET_FOLDER_PATH -Filter *.pdf |
Foreach-Object {
$TARGET_FILE_NAME = $_.Name
$LDA_TARGET_FILE_NAME = $TARGET_FOLDER_PATH + $TARGET_FILE_NAME
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $Base")
$fileName = $TARGET_FILE_NAME
$uri = $AttachURL
$filePath = $LDA_TARGET_FILE_NAME
$FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open)
$fileContent = [System.Net.Http.StreamContent]::new($FileStream)
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"
$bodyLines = (
"--$boundary",
"Content-Disposition: attachment; name=`"$fileName`"; filename=`"$filePath`"",
"Content-Type: application/octet-stream",
"Content-Transfer-Encoding: base64$LF",
$fileContent,
"--$boundary--$LF"
) -join $LF
$Attach = Invoke-RestMethod -Uri $uri -Headers $headers -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines #-InFile $filePath
write-host $Attach
$FileStream.Dispose()
$fileContent.Dispose()
}
I figured it out. I needed to encode the file. For those of you who are here to actually get help and not here to play police for other users posts but neglect to add any actual positive helpful comments.... Here is the code for RightFax add attachments to a fax.
$AttachURL = "http://" + $RESTAPIServer + "/RightFax/API/Attachments"
$Base = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))
$vCenterSessionURL = $BaseAuthURL
$Header = #{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))}
$TARGET_FOLDER_PATH = "\\SomeFolderPath\"
$TokenUri = "http://" + $RESTAPIServer + "/RightFax/API/Login?rememberMe={rememberMe}"
$Token = Invoke-RestMethod -Method GET -Headers $Header -Uri $TokenUri
Get-ChildItem $TARGET_FOLDER_PATH -Filter *.pdf |
Foreach-Object {
$TARGET_FILE_NAME = $_.Name
$LDA_TARGET_FILE_NAME = $TARGET_FOLDER_PATH + $TARGET_FILE_NAME
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $Base")
$fileName = $TARGET_FILE_NAME
$uri = $AttachURL
$filePath = $LDA_TARGET_FILE_NAME
$fileRead = [IO.File]::ReadAllBytes($filePath)
$enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$fileEnc = $enc.GetString($fileRead)
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"
$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"$fileName`"; filename=`"$ResultFilePath`"", # filename= is optional
"Content-Type: application/pdf$LF",
$fileEnc,
"--$boundary--$LF"
) -join $
$Attach = Invoke-RestMethod -Uri $uri -Headers $headers -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -TimeoutSec 20 -Body $bodyLines
Write-host $Attach
}
I'm setting up a different fax service (SRFax) that needs the attachments in base64.
$file = [IO.File]::ReadAllBytes("C:\Users\Path\To\File.pdf")
$filebase64 = [System.Convert]::ToBase64String($file)
I am trying to run an Invoke-WebRequest command on PowerShell Core 6.3 on a Ubuntu system with the following settings to create a forwarder:
$userLocalMailPart = "user"
$userGlobalMailPart = "Hotmail.com"
$address = "Some Address"
$pair = $login + ":" + $password
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$url = "https://" + $server + ":" + $port + "/Domain/ObjectList.html"
$headers = #{"Authorization" = $basicAuthValue;
"Referer" = $url
}
$body = #{
"NewForwarderName" = $userLocalMailPart ;
"NewForwarderAddress" = $address;
"CreateForwarder" = "Create Forwarder"
}
$result = Invoke-WebRequest `
-Uri $url `
-SkipCertificateCheck `
-Method 'POST' `
-Headers $headers `
-Body $body
This runs perfectly. No error and the forwarder is successfully created.
Now I want to use a function like this:
[Web]::requestHeaderContent($url, $headers, (ConvertTo-Json($body)), 'POST')
[object] static requestHeaderContent([String] $url, [hashtable] $headers, [Object] $body, [String] $meth) {
Invoke-WebRequest `
-Uri $url `
-SkipCertificateCheck `
-Method $meth `
-Headers $headers `
-Body $body
}
The variables like headers and body are the same. I also tried it with ConvertTo-Json but it just don’t work. I also receive a Success 200 Code but the forwarder is not created. I guess my problem are the parameters. Any idea what I am doing wrong?
Thanks
Stephan
I've this command:
curl -s -L --header "PRIVATE-TOKEN:XXXX" https://myuri/"
And I need to convert to PowerShell
I've tried this, but doesn't works:
Invoke-RestMethod -Method Get -Headers #{"AUTHORIZATION"="XXXXXX"} -Uri https://myUri
I've also tried this:
PS > $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
PS > $headers.Add("Authorization","XXXXXX")
PS > $headers.Add("Accept","application/json")
PS > $headers.Add("Content-Type","application/json")
PS> $uri = "https://myUri"
PS> $response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get -ContentType "application/json"
PS> $response
PS>
but the $response is empty.
Any help ?
Here is one that I used to authenticate to Teamcity
function Connect-to-Teamcity ($userName, $password, $tcServer, $uri)
{
$auth = $username + ':' + $password
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)
$headers = #{"Authorization"="Basic $($EncodedPassword)"}
$url = "http://$tcServer/httpAuth/app/rest"
$result = Invoke-RestMethod -Uri "$url/$uri" -Header $headers -Method Get
return $result
}
Here is another example if you have more than one header Item:
$resourceAppIdURI = "https://graph.windows.net"
# Login to Azure and get a token valid for accessing the graph API
$authority = "https://login.windows.net/$adTenant"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto")
# Add the token to the header of all future calls to the graph API
$headers = #{"Authorization"=$authResult.CreateAuthorizationHeader();"Content-Type"="application/json"}
$uri = [string]::Format("https://graph.windows.net/{0}/groups/{1}/appRoleAssignments?api-version=1.5", $adTenant, $groupId)
$body = #"
{
"id": $appRoleId,
"principalId": $groupId,
"principalType": "Group",
"resourceId": $appObjectId
}
"#
$result = Invoke-RestMethod -Method "POST" -Uri $uri -Headers $headers -Body $Body