PowerShell: Passing Credentials to CQD (Teams) - powershell

I need to pass Credentials to Powershell for CQD.
(CQD is the Office 365 "Call Quality Dashboard" for Teams).
I tried using the script from https://www.powershellgallery.com/packages/CQDPowerShell/2.0.0/Content/CQDPowerShell.psm1 or https://answers.microsoft.com/en-us/msteams/forum/all/need-connection-uri-for-creating-a-cqd-powershell/f3c9e340-bdac-47c9-af52-d47d6df49fca
But how do I bypass the login/password prompt and pass the credentials seamlessly to Powershell?
Here is my script:
function Get-CQDToken ([string]$client_id)
{
Add-Type -AssemblyName System.Web
$resourceUrl = $WebResource
$redirectUrl = "https://cqd.teams.microsoft.com/spd/"
$nonce = [guid]::NewGuid().GUID
$url = "https://login.microsoftonline.com/common/oauth2/authorize?response_type=token&redirect_uri=" +
[System.Web.HttpUtility]::UrlEncode($redirectUrl) +
"&client_id=$client_id" +
"&prompt=login" + "&nonce=$nonce" + "&resource=" + [System.Web.HttpUtility]::UrlEncode($WebResource)
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object -TypeName System.Windows.Forms.Form -Property #{ Width = 440; Height = 640 }
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property #{ Width = 420; Height = 600; Url = ($url) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
if ($Global:Uri -match "error=[^&]*|access_token=[^&]*") {$form.Close()}
}
$web.ScriptErrorsSuppressed = $true
$web.Add_DocumentCompleted($DocComp)
$form.Controls.Add($web)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog() | Out-Null
$Script:TokenLifeTime = [Web.HttpUtility]::ParseQueryString(($web.Url -replace '^.*?(expires_in.+)$','$1'))['expires_in']
$Script:Token = [Web.HttpUtility]::ParseQueryString(($web.Url -replace '^.*?(access_token.+)$','$1'))['access_token']
return ('Bearer {0}' -f $Script:Token)
}
$userName = "aaron"
$password = "Password_1234"
$configRest = Invoke-RestMethod -Uri "https://cqd.teams.microsoft.com/repository/clientconfiguration" -Method Get -SessionVariable WebSession -UserAgent "CQDPowerShell V2.0"
$WebResource = $configRest.AuthLoginResource
$AADBearerToken = Get-CQDToken $configRest.AuthWebAppClientId
$WebSession.headers.Add('Authorization',$AADBearerToken)

Please go through this ms docs.
https://techcommunity.microsoft.com/t5/teams-developer/how-to-make-source-code-from-cqdpowershell-cmdlet-acquiring/m-p/1325146
While we need to have the code running indefinitely without the user interaction. Access code works for 1hr only again have to intract again. So it won't work
If they have their own datamart and want to build their own reporting UI and customize their own reports etc - create a subscription to the call records API Working with the call records API in Microsoft Graph - Microsoft Graph v1.0 | Microsoft Docs and use that to stream the call records into their own system.

Related

how to make power shell script from qrcode desktop application

I have created desktop application with generate qr code like below
I want make a script using batch script or powershell with the qrcode.exe based on value enter url and Qr Image Name using command line.the output should be QR Code Image too.
can try with this but first import the QRCodeGenerator before running the script
#Import-Module QRCodeGenerator
[string] $webname, [string] $url, [string] $output = ".\images\"
$webname = 'Google'
$url = 'https://www.google.com'
$outputfolder = $outputfolder + $webname +'.JPG'
New-PSOneQRCodeURI -URI $url -Width 15 -OutPath $output
and then the output result will be showing as JPG type.
Install-Module -Name QRCodeGenerator
Import-Module QRCodeGenerator
Add-Type -assembly System.Windows.Forms
$qr_base_form = New-Object System.Windows.Forms.Form
$qr_base_form.Height = 150
$qr_base_form.Width = 350
$qr_base_form.Text = "QR Code Generator"
$qr_base_form.AutoSize = $true
$qr_label_url = New-Object System.Windows.Forms.Label
$qr_label_url.Location = '10,10'
$qr_label_url.Size = '100,15'
$qr_label_url.Text = "URL:"
$qr_input_url = New-Object System.Windows.Forms.TextBox
$qr_input_url.Location = '10,30'
$qr_input_url.Size = '100,25'
$qr_label_name = New-Object System.Windows.Forms.Label
$qr_label_name.Location = '10,70'
$qr_label_name.Size = '100,15'
$qr_label_name.Text = "Name:"
$qr_input_name = New-Object System.Windows.Forms.TextBox
$qr_input_name.Location = '10,90'
$qr_input_name.Size = '100,25'
$qr_png_viewer = New-Object System.Windows.Forms.PictureBox
$qr_png_viewer.Image = $img
$qr_png_viewer.SizeMode = "Autosize"
$qr_png_viewer.Anchor = "Bottom, left"
$qr_png_viewer.Location = '150,10'
$qr_button_create = New-Object System.Windows.Forms.Button
$qr_button_create.Location = '150,150'
$qr_button_create.Size = '100,25'
$qr_button_create.Text = "Create Code"
$qr_button_create.Add_Click({
$path = "H:\LIVE\" + "$name"+ ".jpg"
$urllink = $qr_input_url.Text
$name = $qr_input_name.Text
New-PSOneQRCodeURI -URI "$urllink" -Width 15 -OutPath "$path"
$img = $path
})
$qr_base_form.Controls.Add($qr_label_url)
$qr_base_form.Controls.Add($qr_input_url)
$qr_base_form.Controls.Add($qr_label_name)
$qr_base_form.Controls.Add($qr_input_name)
$qr_base_form.Controls.Add($qr_png_viewer)
$qr_base_form.Controls.Add($qr_button_create)
$qr_base_form.ShowDialog()
This code should work for you. Just try changing the variables and try running it. GUI is also included.

Powershell - How to receive large response-headers from error-response of a web-request?

I am looking for a solution to parse an error-response of a given web-service.
Below sample works great in general, but if the response is larger than 64kb then the content is not availabe in the exception at all.
I have seen some solutions recommending to use webHttpClient and increase the MaxResponseContentBufferSize here, but how can I do this for a given WebClient-object?
Is there any option to change that BufferSize globally for all net-webcalls like below TLS12-settings?
Here is my sample-code:
# using net-webclient to use individual user-side proxy-settings:
$web = new-object Net.WebClient
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "address to web-service"
try {
$response = $web.DownloadString($url)
} catch [System.Net.WebException] {
# this part needs to work even if the error-response in larger than 64kb
# unfortunately the response-object is empty in such case
$message = $_.Exception.Response
$stream = $message.GetResponseStream()
$reader = new-object System.IO.StreamReader ($stream)
$body = $reader.ReadToEnd()
write-host "#error:$body"
}
I solved it at the end by switching to system.net.httpclient.
That way I still repect any custom proxy-settings and also avoid the above mentioned 64kb-limit in any error-response. Here a sample how to use it:
$url = "address to web-service"
$cred = Get-Credential
# define settings for the http-client:
Add-Type -AssemblyName System.Net.Http
$ignoreCerts = [System.Net.Http.HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator
$handler = [System.Net.Http.HttpClientHandler]::new()
$handler.ServerCertificateCustomValidationCallback = $ignoreCerts
$handler.Credentials = $cred
$handler.PreAuthenticate = $true
$client = [System.Net.Http.HttpClient]::new($handler)
$client.Timeout = [System.TimeSpan]::FromSeconds(10)
$result = $client.GetAsync($url).result
$response = $result.Content.ReadAsStringAsync().Result
write-host $response

Powershell in UIPath. Throw : Unable to cast object of type 'Microsoft.Exchange.WebServices.Data.GetItemResponse' to type 'System.String'

I am trying to grab emails from Exchange using powershell in UI Path. When trying to return the items, I get the following error:
Throw : Unable to cast object of type 'Microsoft.Exchange.WebServices.Data.GetItemResponse' to type 'System.String'.
Even when I change the TypeArgument in UI Path. Currently I am using the Invoke power shell activity but I get the same issues using the RunPowershellScript activity. Below is a screenshot of my sequence in UI Path, my parameters, and my powershell script, Thank you!
Param(
[parameter()]
[string]$mailbox,
[parameter()]
[string]$password
)
try{
#https://forum.uipath.com/t/get-argument-from-an-process-with-exception-in-reframework/22537/4
function test-password(){
$Creds = new-object System.Net.networkCredential -ArgumentList $mailbox, $password
$mailFolder = "Inbox"
$itemView = 3
#[Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll")
$ExSer = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$ExSer.Credentials = ($Creds)
$ExSer.Url = new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$ExSer.AutodiscoverUrl($mailbox, {$true})
$setMailFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ExSer,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$logs2 += "Successfully Connected to mailbox $mailbox"
$iv = new-object Microsoft.Exchange.WebServices.Data.ItemView($itemView)
$CustomFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And)
$ifIsRead = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead,$false)
$ifFrom = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::From,"filteremail#mycompany.com")
$CustomFilter.add($ifIsRead)
$CustomFilter.add($ifFrom)
$filteredEmails = $ExSer.FindItems($setMailFolder.Id,$CustomFilter, $iv)
$psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;
#add-type "Microsoft.Exchange.WebServices.Data.GetItemResponse"
$ExSer.LoadPropertiesForItems($filteredEmails,$psPropertySet)
$item = $filteredEmails.Items[0]
return $mailbox, $item
}
test-password
}
catch{
Throw
}
I commented out the load dll as it seemed to work without it and was throwing a similar error when it hit it. The code seems to throw an error when it hits $Exser.LoadPropertyItems. I have also tried switching to Exchange 2007 etc. To clarify, when running purely powershell outside of UI Path, this code works just fine.
I figured it out....I was just being a dingus. It was trying to load an object, which was breaking it. If I saved it as a variable and then converted it within my script and returned what I needed as a string....guess what? It could understand the string. Below is my updated powershell.
Param(
[parameter()]
[string]$mailbox,
[parameter()]
[string]$password
)
try{
#https://forum.uipath.com/t/get-argument-from-an-process-with-exception-in-reframework/22537/4
function test-password(){
$Creds = new-object System.Net.networkCredential -ArgumentList $mailbox, $password
$mailFolder = "Inbox"
$itemView = 50
# Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
#[Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll")
$ExSer = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$ExSer.Credentials = ($Creds)
$ExSer.Url = new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$ExSer.AutodiscoverUrl($mailbox, {$true})
$setMailFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ExSer,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$logs2 += "Successfully Connected to mailbox $mailbox"
$iv = new-object Microsoft.Exchange.WebServices.Data.ItemView($itemView)
$CustomFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And)
$ifIsRead = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead,$true)
$ifFrom = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::From,"emailtofilterby#mycompany.com")
$CustomFilter.add($ifIsRead)
$CustomFilter.add($ifFrom)
$filteredEmails = $ExSer.FindItems($setMailFolder.Id,$CustomFilter, $iv)
$psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;
#add-type "Microsoft.Exchange.WebServices.Data.GetItemResponse"
$FilteredEmailitems = $ExSer.LoadPropertiesForItems($filteredEmails,$psPropertySet)
$EmailBody = $FilteredEmailitems.Item(0) | Select-Object -ExpandProperty Item | Select-Object -ExpandProperty Body | Select-Object -ExpandProperty Text
return $EmailBody
}
test-password
}
catch{
Throw
}

Powershell invoke-webrequest for powershell 2.0

I have created a script in powershell 5.0 that retrieves a data in the website and puts it inside a file. The following code works on windows 7 and higher since they all have .net framework 5.0. Now I was informed that i needs to run on lower windows OS such as XP. powershells in XP is 2.0, and microsoft already ended XP support. I need a powershell 2.0 code that would behaves the same as the code I have written in 5.0:
$number = 1000
$startdate = 2017-01-05
$enddate = 2017-01-11
invoke-webrequest -Uri http://192.168.1.1/form/Download?uid=$number"&"sdate=$startdate"&"edate=$enddate -OutFile D:\Timekeeping\dtr\data.dat -PassThru
There is no direct cmdlet for an alternative:
But you can use the below:
$URI1 = "<your uri>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential
# $request | Get-Member for a list of methods and properties
try
{
$requestStream = $request.GetRequestStream()
$streamWriter = New-Object System.IO.StreamWriter($requestStream)
$streamWriter.Write($body)
}
finally
{
if ($null -ne $streamWriter) { $streamWriter.Dispose() }
if ($null -ne $requestStream) { $requestStream.Dispose() }
}
$res = $request.GetResponse()
So basically we are using the Dot Net Class for it :
$request = [System.Net.WebRequest]::Create("$url")
$request.ContentType='application/json; charset=utf-8'
$request.GetResponse()
You can parse it stream wise :
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$Data=$ReadStream.ReadToEnd()
Hope it helps.

How to post a tweet to twitter using Powershell?

Has anyone used the following code? How do I make it post a tweet? I know I have to use the "$req.Context.RawUri = [Uri]'http://api.twitter.com/version/statuses/update.xml" but I can't get the "$res = [xml][DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)" right.
Add-Type -Path C:\OAuthDevDefined\DevDefined.OAuth.dll
$cons = New-Object devdefined.oauth.consumer.oauthconsumercontext
$cons.ConsumerKey = 'key'
$cons.ConsumerSecret = 'key'
$cons.SignatureMethod = [devdefined.oauth.framework.signaturemethod]::HmacSha1
$session = new-object DevDefined.OAuth.Consumer.OAuthSession $cons, $null, $null, $null
$accessToken = new-object DevDefined.OAuth.Framework.TokenBase
$at = import-cliXml C:\temp\myTwitterAccessToken.clixml
$accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
$at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret
$req = $session.Request($accessToken)
$req.Context.RequestMethod = 'GET'
$req.Context.RawUri = [Uri]'http://api.twitter.com/1/statuses/friends_timeline.xml?count=5'
$res = [xml][DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)
$res.statuses.status | % { $_.user.Name }
I use OAuth by DevDefined as well. My function looks like this:
function Post-Twitter {
param(
[Parameter(Mandatory=$true)][string]$url
)
if (!$script:accessToken) {
throw 'token is not initialized'
}
try {
$cons = New-Object devdefined.oauth.consumer.oauthconsumercontext
$cons.ConsumerKey = $consumerKey
$cons.ConsumerSecret = $consumerSecret
$cons.SignatureMethod = [devdefined.oauth.framework.signaturemethod]::HmacSha1
$session = new-object DevDefined.OAuth.Consumer.OAuthSession `
$cons,
"http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/authorize",
"http://twitter.com/oauth/access_token"
$token = Get-AccessToken
$req = $session.Request($token)
$req.Context.RequestMethod = 'POST'
$req.Context.RawUri = new-object Uri $url
[DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)
} catch {
Write-Warning "Exception: $_"
$null
}
}
Then for simplicity I pass status in query string:
add-type -assembly System.Web
$status = [system.Web.Httputility]::UrlEncode('some tweet')
Post-Twitter "http://api.twitter.com/1/statuses/update.xml?status=$status"
It seems that you know about the consumer key/secret and the token thing, so I'll leave it without further explanation.
I’ve just posted a Powershell Twitter REST API 1.1 Module on TechNet Gallery… You'll be able to post/get from Twitter API! https://goo.gl/s7pmmA