How can I modify this snippet code for PowerShell version 2.0 on Windows 7?
$path = "myfolder/file.txt"
$body = "file=$(Get-Content $path | Out-String)"
Invoke-WebRequest -Uri "http//mywebsite" -Method POST -Body $body`
I tried this but cannot run on PowerShell version 2.0.
Any suggestions?
Invoke-webRequest is present in PowerShell v3.0 [ref - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-6]
There are two solution to solve the problem, one you can update the powershell version to 3 or above ,
else use following cmdlet to perform WebRequest.
$WebRequest = [System.Net.WebRequest]::Create("http://url")
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json"
$Response = $WebRequest.GetResponse()
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$Data=$ReadStream.ReadToEnd()
Related
I have followed proper documentation and examples. Also other methods are working fine, but message move is not working properly. Please look at below and suggest what I should change:
PS C:\> $body = #{
>> "destinationId" = "$folderid"
>> }
## Note: I have tried well known folder types also like deleteditems
PS C:\> $body
Name Value
---- -----
destinationId AAMkADIzYjU1MDg4LWIzOTAtNDVhYi1iNjczLTdlNjBiMjExMGE3MwAuAAAAAAAMiK_sOzYGRJ9qF2G24SoEA...
$urimove="https://graph.microsoft.com/v1.0/users/mymailbox#xyz.com/messages/$conv/move"
$body = #{
"destinationId" = "$folderid"
}
$mv = Invoke-WebRequest -Method Post -Uri $urimove -ContentType "application/x-www-form-urlencoded" -Headers $Headers -Body $body
### if I change above -ContentType "application/x-www-form-urlencoded" to "application/json", I start getting 400 bad request error
ERROR:
Invoke-WebRequest : The remote server returned an error: (415) Unsupported Media Type.
At line:1 char:1
+ Invoke-WebRequest -Method Post -Uri $urimove -ContentType "applicatio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Finally it worked... below is the solution:
$urimove="https://graph.microsoft.com/v1.0/users/mailbox#domain.com/messages/$Id/move"
$body = #{
"destinationId" = "$folderid"
}
$body_json = $body | ConvertTo-Json
$mv = Invoke-WebRequest -Method Post -Uri $urimove -Headers $Headers -Body $body_json
Changes are:
body should be body_json as shown above
no content-type in request call
content-type should be in headers and equals application/json
How to convert "prefer=minimal" request header if I write a PowerShell code within the Invoke-Webrequest to minimize the response?
$Data = Invoke-WebRequest -Headers $authHeader -Uri $Url -Body $body -Method POST -UseBasicParsing -ContentType "application/json; charset=utf-8" -prefer "return=minimal"
This code does not work from my end.
PowerShell
Invoke-WebRequest does not support Prefer parameter, it needs to be specified via Headers parameter instead, for example:
$Url = "https://graph.microsoft.com/v1.0/users/delta?`$select=displayName,jobTitle,mobilePhone"
$headers = #{
Authorization="Bearer $token"
Prefer="return=minimal"
}
$Data = Invoke-WebRequest -Headers $headers -Uri $Url -Method GET -ContentType "application/json"
I have existing team project ( TFS 2018 )I want to know which process template have been used.
List the projects via REST API and get the {projectId} for
a specific project:
GET http://SERVER:8080/tfs/DefaultCollection/_apis/projects
Retrieve the Process template information from project
properties by calling REST API:
GET http://SERVER:8080/tfs/DefaultCollection/_apis/projects/{projectId}/properties
Please see Projects - Get Project Properties for details.
Well, you can simply use below Powershell script to get which process template have been used for a specific team project:
Param(
[string]$collectionurl = "http://server:8080/tfs/DefaultCollection",
[string]$projectname = "GXJGitTest",
[string]$user = "domain\user",
[string]$token = "password/PAT"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
#Get project ID
$ProjectsUrl = "$collectionurl/_apis/projects"
$ProjectsResponse = Invoke-RestMethod -Uri $ProjectsUrl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$projectid = ($ProjectsResponse.value | where {$_.name -eq $projectname}).id
#Get system.template
$PTurl = "$collectionurl/_apis/projects/$projectid/properties"
$response = Invoke-RestMethod -Uri $PTurl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$ProcressTemplate = ($response.value | where {$_.name -eq 'System.Process Template'}).value
Clear-host
Write-Host "The project $projectname is using the $ProcressTemplate Process Template."
If you use 1 from 3 built-in templates (Agile, Scrum, CMMI) you can check which work item type you have:
Agile - User story
Scrum - Product Backlog Item
CMMI - Requirement
If you use a custom template you can check the process template with rest API:
Get http://yourServer:8080/tfs/DefaultCollection/_apis/projects/TestTemplate?includeCapabilities=true&api-version=1.0
You could get the result about the template like the following:
"capabilities": {
"processTemplate": {
"templateName": "Test"
},
I have a trial 2017 online TFS and i am trying to find a way to upload files with powershell commands. I have tried installing some relevant modules with wrapped api commands, but none of them has anything similar.
Any suggestions?here are actually the two commands i am trying to execute through ps
Why you have to do this? The actions via web portal are more convenient and friendly.
Whatever you can have a try with the REST API.
Create a folder: (Create folder test0232 under $/0522TFVCScrum/ in below example)
Param(
[string]$vsoAccount = "YourInstance",
[string]$keepForever = "true",
[string]$user = "test#hotmail.com",
[string]$token = "PAT or Password here"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
function CreateJsonBody
{
$value = #"
{"changes":[{"changeType":1,"item":{"path":"$/0522TFVCScrum/test0232","isFolder":true}}],"comment":"Added folder test0232"}
"#
return $value
}
$json = CreateJsonBody
$uri = "https://$($vsoAccount).visualstudio.com/_apis/tfvc/changesets?api-version=4.1-preview.3"
$result = Invoke-RestMethod -Uri $uri -Method Post -Body $json -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-host $result
Create a file with below body: (Just replace the Jsonbody in above script, 0229test.ps1 created in this sample)
{"changes":[{"changeType":1,"item":{"path":"$/0522TFVCScrum/0229test.ps1","contentMetadata":{"encoding":65001}},"newContent":{"content":"test0229","contentType":0}}],"comment":"Added file 0229test.ps1"}
Upload file:
Cannot find a way to upload files directly with the REST API, however you can try to copy files to workspace first, then add the files in source control with Add command, then check in the files with Checkin command.
Downlaod as Zip:
You can track the API with tools, then you can get the URL something like this:
https://{your account}.visualstudio.com/b3cbc52a-22f6-4de9-ae78-b2b305365ff8/_api/_versioncontrol/itemContentZipped?repositoryId=&path=%24%2F0522TFVCScrum%2Ftest0228&version=T&__v=5
Then you can try downlaod with that url in your script.
Background: I am creating a script to send out a message to everyone in my Domain. I was able to complete this using Invoke-WMImethod and MSG.exe. However, my supervisor wants a more customizable message to be sent. Like changing Color, font size, font style...etc. Which i have created using PowerShell.
Script:
Invoke-WmiMethod -ComputerName $Computer -Class Win32_Process -Name Create -ArgumentList {"C:\x\x\x\Powershell.exe -File `"\\Server\Share\Folder\Script.ps1`""}
When i run this script against my Computer it works perfectly. However, when i attempt to run it on a remote computer it fails.
I don't understand why.
It's the same exact script that i used with MSG.exe, which worked, but it still doesn't work with a powershell script.
I attempted to copy the script to the remote computers 'C:\' and run it from that file path but it still didn't work.
I've verified the file path to Powershell.exe is the same as the script and that the remote workstation can access the .PS1 Script.
However, the script does run and says it is successful with a Return Value of 0. Example:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ProcessId : 8748
ReturnValue : 0
My Suggestion would be to check for the versions on both the machines. The CmdLet you using may not be working on the previous version.
I again have a suggestion to make, you can use the below command to get your work done, if you have powershell Version 3 or above.
$Outputreport = "Test message to send data using port 443"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$wc = new-object System.Net.WebClient
Invoke-RestMethod -Method Post https://hostnamedotcom/cgi-bin/dir-path/$hostname-filename -Body $Outputreport