I have the code below runs OK in Azure Functions on it's own and displays output. However the code is static, I need the URL (top line) to be able to be passed through as a parameter with an HTTP on-demand trigger.
The article here talks about Binding at runtime via imperative bindings, however it’s not 100% clear as to how to pass an HTTP based parameter e.g. https://myfunction.azurewebsites.net/api/AustereoJustPlaying?url=legacy.scahw.com.au/2classicrock_128.xspf and then work with the parameter in the PowerShell code.
# Get the initial metadata for the stream
$url = 'http://legacy.scahw.com.au/2classicrock_128.xspf'
$iwr = Invoke-RestMethod -Uri $url
# Build up the .Net web client
$HttpCompletionOption = 'ResponseContentRead'
$webClient = New-Object System.Net.Http.HttpClient
$webclient.DefaultRequestHeaders.Add('Icy-MetaData', '1')
# Get the Stream URL
$null = $iwr.InnerXml -match '<location>(?<location>.*)<\/location>'
$location = $matches.location
# Fire up the stream
$response = $webClient.GetAsync($location,$HttpCompletionOption)
$null = $webclient.DefaultRequestHeaders.Remove('Icy-MetaData')
# Pause until the stream title actually fires up
Start-Sleep -Seconds 2
# Grab the song
$iwr = Invoke-RestMethod -Uri $url
$null = $iwr.InnerXml -match '<title>(?<song>.*)<\/title>'
# Kill the stream
$webclient.Dispose()
# Output the song
$matches.song
Side note, if you get the error below on your computer…..
New-Object : Cannot find type [System.Net.Http.HttpClient]: verify that the assembly containing this type is loaded
Run this block of code, seems that you need to ‘warm’ up the system in order to find the ‘type’, running Find-Type httpClient a few times seems to wake up the system to realise Yes, it does have this type installed.
function Find-Type ([regex]$pattern)
{
[System.AppDomain]::CurrentDomain.GetAssemblies().GetTypes() |
Select-Object -ExpandProperty FullName | Select-String $pattern
}
Do {
cls
$TypeSearch = Find-Type httpClient
} until ($TypeSearch -match 'System.Net.Http.HttpClient')
The default PowerShell HTTP Trigger template shows an example of that.
Query string parameters will be made available to your script as variables in the format req_query_<parametername>, so in your example above the URL parameter would be accessible using: $req_query_url
The following function is a simple example of just returning the parameter
Out-File -Encoding Ascii -FilePath $res -inputObject "URL parameter $req_query_url"
Related
We are using the Azure DevOps Test Plan module for our manual testing. We have a Test Plan, under which, we have Test Suite, under which we have Test Cases that are assigned to different Testers. Testers use ADO to mark a Test Case outcome as passed or fail.
We want to download the Test Case outcome/results, but I don't see that option. We have a Test Run tab under Test Plan which shows all Run outcomes but doesn't give the option to download.
I am afraid that there is no out-of-box method can directly export the test results of test runs to excel.
To meet your requirement, you can use Rest API to list all required test runs and test results. Then you can export them to Excel.
You can use the following two Rest APIs:
Get Test Runs: Runs - Query
GET https://dev.azure.com/{organization}/{project}/_apis/test/runs?minLastUpdatedDate={minLastUpdatedDate}&maxLastUpdatedDate={maxLastUpdatedDate}&state={state}&planIds={planIds}&isAutomated={isAutomated}&publishContext={publishContext}&buildIds={buildIds}&buildDefIds={buildDefIds}&branchName={branchName}&releaseIds={releaseIds}&releaseDefIds={releaseDefIds}&releaseEnvIds={releaseEnvIds}&releaseEnvDefIds={releaseEnvDefIds}&runTitle={runTitle}&$top={$top}&continuationToken={continuationToken}&api-version=7.0
Get Test Results: Results - List
GET https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?detailsToInclude={detailsToInclude}&$skip={$skip}&$top={$top}&outcomes={outcomes}&api-version=7.0
Here is PowerShell sample:
$token = "PAT"
$url=" https://dev.azure.com/orgname/projectname/_apis/test/runs?api-version=7.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $response
ForEach( $testrunid in $response.value.id )
{
echo $testrunid
$url1 ="https://dev.azure.com/orgname/projectname/_apis/test/Runs/$($testrunid)/results?api-version=7.0"
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
ForEach( $testresult in $response1.value)
{
$outcome = $testresult.outcome
$startedDate = $testresult.startedDate
$testCase =$testresult.testCase.name
$completedDate = $testresult.completedDate
$testCaseTitle = $testresult.testCaseTitle
echo $outcome
echo $startedDate
$Output = New-Object -TypeName PSObject -Property #{
outcome = $outcome
runid =$testrunid
startedDate = $startedDate
completedDate= $completedDate
testCase = $testCase
testCaseTitle = $testCaseTitle
} | Select-Object runid, outcome,startedDate,testCase,testCaseTitle,completedDate
$Output | Export-Csv C:\testresult.csv -Append
}
}
You can customize the output excel column according to your requirements.
Result:
You could Export the test plan properties, test suite properties along with details of the test cases and test points as either an email or print to pdf by using the Export function of the test suite: doc
Make sure you have test access and permission in Azure DevOps.
Below are the steps to download the Test Run results from ADO –
Navigate to Test Plan -> Runs
Click on filters, remove all filters and run the query
Click on one result and press Ctrl + A and then Ctrl + C
Paste the content in Notepad++, then copy the content from Notepad++ and paste it Excel.
This will give you list of all Test Runs with results. You can get the latest outcome of test run, by sorting data using Run ID in descending order and then using unique rows only.
This question already has answers here:
How can you use an object's property in a double-quoted string?
(5 answers)
Closed 5 months ago.
I wrote a script that allows me to query the whole Azure database park:
#$ErrorActionPreference = 'SilentlyContinue'
# Connect to Azure
$azureAccount = Connect-AzAccount
# Get Azure Access Token (we will use this to query the databasees)
#$azureToken = Get-AzAccessToken -ResourceUrl https://database.windows.net
$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
# Queries will be picked up from here
$folderPath = '.\Queries'
# Choose how to format each date ("yyyy-MM-dd") or ("yyyy-MM-dd HH:mm:ss")
$DateTime = (Get-Date).ToString("yyyy-MM-dd")
# List Azure Sunscriptions
Get-Azsubscription | ForEach-Object -Begin { $a = 1 } -Process {"$a $($_.Name)"; $a++}
$SubscriptionChoice = Read-Host -Prompt "Copy/paste the name of the Subscription that you want to investigate. If more than one separate them by a coma, Type `"All`" if you want to target all of them"
# Iterate into subscriptoins and print names
foreach ($gs in $SubscriptionChoice) {
Select-Azsubscription -Subscription "$gs" | Out-Null
Write-Host "Let's browse into Azure Sunscription: " -NoNewline
Write-Host (Get-AzContext).Subscription.Name -ForegroundColor green
# Fins all Azure SQL Server
Get-AzSqlServer | ForEach-Object -Begin { $a = 1 } -Process {"$a $($_.ServerName)"; $a++}
$SqlServerChoice = Read-Host -Prompt "Copy/paste the name of the SQL Server that you want to investigate. If more than one separate them by a coma, Type `"All`" if you want to target all of them"
if ($SqlServerChoice = "All"){
$SqlServerChoice = Get-AzSqlServer
}
Foreach ($server in $SqlServerChoice){
$DatabaseChoice = Get-AzSqlDatabase -ServerName $server.ServerName -ResourceGroupName $server.ResourceGroupName | Where-Object DatabaseName -NE "master"
Foreach ($database in $DatabaseChoice){
(Get-ChildItem $folderPath | sort-object {if (($i = $_.BaseName -as [int])) {$i} else {$_}} ).Foreach{
Invoke-Sqlcmd -ServerInstance $server.FullyQualifiedDomainName -Database $database.DatabaseName -AccessToken $access_token -InputFile $psitem.FullName | Export-Csv -Path ".\Results\$psitem.csv" -Append -NoTypeInformation
write-host "Executing $psitem on $database.DatabaseName"
}
}
}
}
However each time the query is executed against a database the Write-Hosts returns:
Executing DTU_to_vCore.sql on Microsoft.Azure.Commands.Sql.Database.Model.AzureSqlDatabaseModel.DatabaseName
Here a picture:
This Write-Hosts comes from the line:
write-host "Executing $psitem on $database.DatabaseName"
In which you can find the two variables:
$psitem : which is the name of the file that contains the query
$database.DatabaseName : which should be the database name but instead of printing the database name is printing Microsoft.Azure.Commands.Sql.Database.Model.AzureSqlDatabaseModel.DatabaseName
Why one of the two variable is not interpreted?
You need to encapsulate your variable property in a subexpression operator $().
write-host "Executing $psitem on $($database.DatabaseName)"
This is because only simple variables get expanded in an expandable string.
References
Only simple variable references can be directly embedded in an
expandable string. Variables references using array indexing or member
access must be enclosed in a subexpression.
Source: about_Quoting_Rules
Subexpression operator $( )
Returns the result of one or more statements. For a single result,
returns a scalar. For multiple results, returns an array. Use this
when you want to use an expression within another expression. For
example, to embed the results of command in a string expression.
PS> "Today is $(Get-Date)"
Today is 12/02/2019 13:15:20
PS> "Folder list: $((dir c:\ -dir).Name -join ', ')"
Folder list: Program Files, Program Files (x86), Users, Windows
Source: about_Operators
Trying to build a link with a variable and a string, but I always get a space in between them. How can I fix this?
The $sub is a SPWeb object from sharepoint.
Write-Host $sub.Url "/default.aspx"
result:
https://intra.mycompany/pages/sales /default.aspx
Put the $sub variable inside the string literal so that it is treated as one string:
Write-Host "$($sub.Url)/default.aspx"
Note that you will need to use a sub expression operator $(...) since you are accessing an attribute of $sub.
Another approach, depending on how complicated your string is, is to use the -f format operator:
Write-Host ("{0}/default.aspx" -f $sub.Url)
If you have many variables that you need to insert, it can make for cleaner and easier to read code.
Use the URL class' constructor to do the join, rather than using string manipulation. This will have the additional advantage of automatically take care of appending any slashes required.
function Join-Uri {
[CmdletBinding()]
param (
[Alias('Path','BaseUri')] #aliases so naming is consistent with Join-Path and .Net's constructor
[Parameter(Mandatory)]
[System.Uri]$Uri
,
[Alias('ChildPath')] #alias so naming is consistent with Join-Path
[Parameter(Mandatory,ValueFromPipeline)]
[string]$RelativeUri
)
process {
(New-Object -TypeName 'System.Uri' -ArgumentList $Uri,$RelativeUri)
#the above returns a URI object; if we only want the string:
#(New-Object -TypeName 'System.Uri' -ArgumentList $Uri,$RelativeUri).AbsoluteUri
}
}
$sub = new-object -TypeName PSObject -Property #{Url='http://demo'}
write-host 'Basic Demo' -ForegroundColor 'cyan'
write-host (Join-Uri $sub.Url '/default.aspx')
write-host (Join-Uri $sub.Url 'default.aspx') #NB: above we included the leading slash; here we don't; yet the output's consistent
#you can also easily do this en-masse; e.g.
write-host 'Extended Demo' -ForegroundColor 'cyan'
#('default.aspx','index.htm','helloWorld.aspx') | Join-Uri $sub.Url | select-object -ExpandProperty AbsoluteUri
Above I created a function to wrap up this functionality; but you could just as easily do something such as below:
[string]$url = (new-object -TypeName 'System.Uri' -ArgumentList ([System.Uri]'http://test'),'me').AbsoluteUri
Link to related documentation: https://msdn.microsoft.com/en-us/library/9hst1w91(v=vs.110).aspx
I'm trying to create a report which will get two sets of information, Group name and domain. The problem is that the information will be output into one column instead of two for example:
Group Member Domain
thisIsGroupMember,Domain
but I want it to be like this:
Group Member Domain
thisIsGroupMember, Domain
I also try export-csv but the created csv file only show
Length
32
Here's my code:
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$inputstring = "$appName,$domain"
out-file -FilePath "C:\Test\Result.csv" -append -inputObject $inputstring
If your code iterates through a list of objects pulled from AD you can use something like this:
# your foreach code
{
...
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$output += ,(New-Object -TypeName psobject -Property #{"Group Member"=$appName;"Domain"=$domain})
}
$output | Export-Csv "C:\Test\Result.csv"
$output is an array of objects being created on the fly with $appName and $domain values. It will then nicely export to a csv after all AD objects are processed.
#Function to get the computerlist: Name,OS,IPv4, IPv6,DiskInfo
function Get-ComputerListnDiskInfo{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True)] [string[]]$ComputerName
)
BEGIN {
Import-Module ActiveDirectory -Cmdlet Get-ADComputer -ErrorAction SilentlyContinue
}
PROCESS {
try{
$computerinfo = Get-ADComputer -Filter * -Properties OperatingSystem
#Information about Name,Ipv4,IPv6,Device,VolumeName,Free,Busy,Size,Pfree,Pbusy for ALL COMPUTERS container
$AllComputerInfo = #()
foreach ($comp in $computerinfo){
#Testing if computers is ON LINE
$TestCon = Tester $comp.name
$test = $TestCon.BooleanV
if($test) {
#write-output "$Test"
$PhysicalDisks = Get-WMIObject -computername $comp.name -query "SELECT * from win32_logicaldisk where DriveType = 3" | Select Deviceid,VolumeName,FreeSpace,Size
$Target = #()
#Create the Object foreach disk and append in the Target Variable
$GetOPNHealthStatus = Get-PhysicalDisk | select FriendlyName,OperationalStatus,HealthStatus
Write-Output "$PhysicalDisk.count"
#write-output $GetOPNHealthStatus.OperationalStatus
$i=0
foreach ($disk in $physicalDisks){
#Get all Items: size,free,busy,pfree and pbusy disk space info (can add a number at the end to set decimals)
$Size=FormatNSetSizeFreeSpace $disk.Size
$Free=FormatNSetSizeFreeSpace $disk.FreeSpace
$Busy=FormatNSetBusySpace $disk.Size $disk.FreeSpace
$Pfree=PercentFreeBusy $Free $size
$PBusy=PercentFreeBusy $Busy $size
#Create a new Object using all the info
$result =New-Object PSObject -Property #{
Device=$disk.DeviceID
VolumeName=$disk.VolumeName
Size=$Size
Free=$Free
Busy=$Busy
Pfree = $PFree
PBusy = $PBusy
OPStatus = $GetOPNHealthStatus.OperationalStatus[$i]
HStatus = $GetOPNHealthStatus.HealthStatus[$i]
}
$i++
#add this info to the target array
$Target+= $result
}
#Add all info into new object
$allIComnDiskInfo=New-Object PSObject -Property #{
Name = $comp.Name
OS = $comp.OperatingSystem
IPV4 = $TestCon.IPv4
IPV6 = $TestCon.IPv6
disksInfo = $Target
}
#and Fill any just add this info to the $Allcomputer info (just online computer's)
$AllComputerInfo+= $allIComnDiskInfo
}
}
return $AllComputerInfo
}
Catch{
Write-Warning $_.Exception.Message
}
}
}
$test = Get-ComputerListnDiskInfo
running $test
$test = Get-ComputerListnDiskInfo
$test
disksInfo : {#{PBusy=8,148; VolumeName=; Busy=10,306; Pfree=91,853; Free=116,178; Device=C:; Size=126,483; OPStatus=O; HStatus=H}}
Name : DC2012
OS : Windows Server 2012 R2 Standard
IPV4 : 192.168.1.251
IPV6 : fe80::cd63:76bf:3d2b:340f%12
And running
$test | Export-Csv here.csv
I got this:
#TYPE System.String
"Length"
"6"
Why is happening this?
Why I don't get all this info?
And how should I search the info contained in the "diskInfo" variable
I tried to pass this $test variable to another function to format it and It seem not to work:
Thank you in advance for the answers
To start out with, you aren't just outputting a custom object, or an array of custom objects. But that's not the first problem I see. The first problem I see is that you have this big function that has a parameter, and then you do this:
$test = Get-ComputerListnDiskInfo
So you call that function with no arguments, so it has no computer to run it against. Some of the parts of the function will probably default to the local computer, but will they all? I don't know, maybe.
So what does $test actually contain? An array. Of what? Well, the first thing that the function outputs is a string:
Write-Output "$PhysicalDisk.count"
So the first item in your array is a string. Then you build a bunch of custom objects and arrays, and what not, and you Return those. Great, the next item in your $test array is a custom object. But $test is not an array of custom objects, or a single custom object, it is an array with a variety of things within it.
That is why Export-CSV will not work.
Basically the issue is this one:
I have an system.object[] in the output while using CSV.
object or similar output when using export-csv