I have a powershell script with 2 funtions:
function Stonebrach.Connect {
param(
[Parameter(Mandatory=$true)]
$Sb_uri,
[Parameter(Mandatory=$true)]
$Auth_filename,
[Parameter(Mandatory=$true)]
$Method,
[Parameter(Mandatory=$false)]
$Body
)
$basicAuth=Get-Content "C:\$auth_filename"
$headers = #{
"Authorization" = $basicAuth
"Content-Type"="application/json"
}
$RSP=$null
try{
if ( $body -eq $null ) {
$response = invoke-restmethod -Uri $Sb_uri -Method $Method -Headers $headers
}
else {
$response = invoke-restmethod -Uri $sb_uri -Method $method -Headers $headers -Body $body
}
return $response
}
catch{
$RSP = $_.Exception.Message
return $RSP
}
}
function Stonebranch.Create.Task.Windows {
param(
[Parameter(Mandatory=$true)]
$Sb_base_uri,
[Parameter(Mandatory=$true)]
$Auth_filename,
[Parameter(Mandatory=$true)]
$Method,
[Parameter(Mandatory=$true)]
$Body
)
Stonebrach.Connect -SB_uri $Sb_base_uri/task -Auth_filename $Auth_filename -Method $Method -Body $Body
}
the body param is hardcoded as below:
$body = '
{
"type" : "taskWindows",
"actions" : {
"abortActions" : [],
"emailNotifications" : [],
"setVariableActions" : [],
"snmpNotifications" : [],
"systemOperations" : []
},
"agent" : "test",
"name" : "Test Create",
"summary" : "Test Create"
}
'
Call the function:
$response = Stonebranch.Create.Task.Windows -Sb_base_uri $Sb_base_uri -Auth_filename $Auth_filename -Method POST -Body $body
Here's the question: i want to separate the $body into a different file (prefer YAML file). Anyone know how to separate and pass the list of param to the script so i can use them? I find it hard to pass the list of param and call the function.
Please help me, thanks.
Related
I am trying to create a user story and task in Azure DevOps with this RESTapi
There are multiple backlogs.
POST https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/${type}?api-version=6.0
My code
function Set-pbiStuff {
param
(
[Parameter(Mandatory = $true)] [string] $Organization,
[Parameter(Mandatory = $true)] [string] $Project,
[Parameter(Mandatory = $true)] [hashtable] $Token
)
$Base = "https://dev.azure.com/$($organization)/$($project)/_apis/wit/workitems"
$workItemType = 'task'
$URL = "$($Base)/$($workItemType)?api-version=6.0"
$Json = #(
#{
op = 'add'
path = '/fields/System.Title'
value = $workItemType
}
)
$Body = (ConvertTo-Json $Json)
$response = Invoke-RestMethod `
-Method Post `
-Uri $URL `
-ContentType 'application/json' `
-Body $Body `
-Headers $Token
Write-Host $URL
Write-Host $response
}
$Token= #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($env:SYSTEM_ACCESSTOKEN)")) }
$tt = Set-pbiStuff -Organization 'myOrganization' -Project 'myProject' -Token $Token
return $tt
But the response I get is that the page was not found.
What have I missed?
The problem is that the type ${type} is incorrect in your script, the character $ is missing.
Please try this:
$URL = "$($Base)/"+"$"+"$($workItemType)?api-version=6.0"
And the content type should be "application/json-patch+json"
Below script works for me : (PAT used for the test, you can change it back to SYSTEM_ACCESSTOKEN if you run it in pipeline)
function Set-pbiStuff {
param
(
[Parameter(Mandatory = $true)] [string] $Organization ,
[Parameter(Mandatory = $true)] [string] $Project ,
[Parameter(Mandatory = $true)] [string] $Token
)
$Base = "https://dev.azure.com/$($organization)/$($project)/_apis/wit/workitems"
$workItemType = 'task'
$URL = "$($Base)/"+"$"+"$($workItemType)?api-version=6.0"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f '',$Token)))
$Json = #(
#{
op = 'add'
path = '/fields/System.Title'
value = $workItemType
}
)
$Body = (ConvertTo-Json $Json)
$response = Invoke-RestMethod `
-Method Post `
-Uri $URL `
-ContentType 'application/json-patch+json' `
-Body $Body `
-Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host $URL
Write-Host $response
}
$tt = Set-pbiStuff -Organization 'orgname' -Project 'ProjectName' -Token Tokenhere
return $tt
You're trying to call the API with a PATCH verb, see line two:
$response = Invoke-RestMethod `
-Method Patch `
-Uri $URL `
-ContentType 'application/json' `
-Body $Body `
-Headers $AzAuthHeader
The API endpoint is, like the documentation shows and you stated in your question, a POST endpoint.
Try this URL:
$URL = "$($Base)/`$$($workItemType)?api-version=6.0"
Check this sample: https://arindamhazra.com/create-azure-devops-task-using-powershell/
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'm using the following to send to single recipient, and single Cc recipient.
How do I send to multiple recipients, either in To: and/or Cc: ?
Thanks! I have tried all different combinations but its still not working (still getting as if its no surprise, the usual Invoke-RestMethod :The remote server returned an error: (400) Bad Request.)
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
HelpMessage="Email Address e.g man1#whatever.com")]
[Alias('Email')]
$Subject,
$Content)
UserName = "myUPN#mywork.com"
$Password = cat C:\Creds\mycreds.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -
argumentlist $username,$password
$contentType = "application/json;odata.metadata=full"
$uri = "https://outlook.office365.com/api/v1.0/me/sendmail"
$body = "{
""Message"":{
""Subject"": ""$Subject"",
""Importance"": ""High"",
""Body"": {
""ContentType"": ""HTML"",
""Content"": ""$Content""
},
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""man1#whateverdomain.com""
}
}
],
""CcRecipients"": [
{
""EmailAddress"":{
""Address"": ""man2#whateverdomain.com""
}
}
]
}}"
Invoke-RestMethod -Uri $uri -Method Post -Credential $cred`
-Body $Body -ContentType $contentType
You can specify the CC's with an array to feed into this
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
HelpMessage="Email Address e.g man.man#domain.com")]
[Alias('Email')]
$EmailAddress,
$CCEmailAddress,
$Subject,
$Content)
$UserName = "man.man#domain.com"
$Password = cat C:\Creds\regcreds.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
$CCinJSON = $CCEmailAddress | %{'{"EmailAddress": {"Address": "'+$_+'"}},'}
$CCinJSON = ([string]$CCinJSON).Substring(0, ([string]$CCinJSON).Length - 1)
$contentType = "application/json;odata.metadata=full"
$uri = "https://outlook.office365.com/api/v1.0/me/sendmail"
$body = "{
""Message"":{
""Subject"": ""$Subject"",
""Importance"": ""High"",
""Body"": {
""ContentType"": ""HTML"",
""Content"": ""$Content""
},
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""$EmailAddress""
}
}
],
""CcRecipients"": [
$CCinJSON
]
}}"
echo $body
Invoke-RestMethod -Uri $uri -Method Post -Credential $cred -Body $Body -ContentType $contentType
As the tile said, i would like to know the way to use this Get-AnsibleParam function. More specific, how to apply Get-AnsibleParam in this case:
i have a YAML file that contained some variables
---
type: taskWindows
actions:
abortActions: []
emailNotifications: []
setVariableActions: []
snmpNotifications: []
systemOperations: []
agent: test
name: "Test"
summary: "Test"
...
I have a Powershell Script:
function Stonebrach.Connect {
param(
[Parameter(Mandatory=$true)]
$Sb_uri,
[Parameter(Mandatory=$true)]
$Auth_filename,
[Parameter(Mandatory=$true)]
$Method,
[Parameter(Mandatory=$false)]
$Body
)
$basicAuth=Get-Content "C:\$auth_filename"
$headers = #{
"Authorization" = $basicAuth
"Content-Type"="application/json"
}
$RSP=$null
try{
if ( $body -eq $null ) {
$response = invoke-restmethod -Uri $Sb_uri -Method $Method -Headers $headers
}
else {
$response = invoke-restmethod -Uri $sb_uri -Method $method -Headers $headers -Body **$body**
}
return $response
}
catch{
$RSP = $_.Exception.Message
return $RSP
}
}
function Stonebranch.Create.Task.Windows {
param(
[Parameter(Mandatory=$true)]
$Sb_base_uri,
[Parameter(Mandatory=$true)]
$Auth_filename,
[Parameter(Mandatory=$true)]
$Method,
[Parameter(Mandatory=$true)]
$Body
)
Stonebrach.Connect -SB_uri $Sb_base_uri/task -Auth_filename
$Auth_filename -Method $Method -Body $Body
}
Can i use Get-AnsibleParam to get the variables from YAML file (all of them) into the $body in the PS script in this case? I tried to read the documentation, but it is not very clear how to use the function:
https://code.vt.edu/nis-ansible-roles/upstream-ansible/blob/2a751e1753c1fe675ba3d0b1dbc9939c9253ea70/lib/ansible/module_utils/powershell.ps1
Please help. Thanks
Get-AnsibleParam is used to access specific parameter passed to a module. You can't use it to get all variables from your playbooks.
Take a look at win_ping for example usage:
$params = Parse-Args $args -supports_check_mode $true
$data = Get-AnsibleParam -obj $params -name "data" -type "str" -default "pong"
if ($data -eq "crash") {
throw "boom"
}
In this case win_ping can accept parameter named data of type string with default value pong.
I need to trigger a build after successful deployment of a release. I have tried using below code in Powershell in the release definition.
After executing, I get this error - Access is denied due to invalid credentials
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?
api-version=2.0"
$body = "{ 'definition' : { 'id' : 1} }"
$type = "application/json"
$headers = #{
Authorization = "Basic d3JlblxzcsampleTIzNA=="
}
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -
Method Post -Headers $headers
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"`
Based on my test, you can use -UseDefaultCredentials :
$type = "application/json"
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
$body = "{ 'definition' : { 'id' : 56} }"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -UseDefaultCredentials
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"
Alternatively provide the specific Credential:
$user = "username"
$password = "password"
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$type = "application/json"
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
$body = "{ 'definition' : { 'id' : 56} }"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"