How to create / generate Bearer token with PowerShell? - azure-active-directory

How to create / generate Bearer token with PowerShell?
I need to find out a way to generate the bearer token with PowerShell.

$ADAuthorityURL = "https://login.windows.net/common/oauth2/authorize/"
$resourceURL = "https://AQAEducation.onmicrosoft.com/<<AppRegistrion(1)>>"
$AADuserName = "your_user_name#xyz.onmicrosoft.com"
$AADpassword = "<<PASSWORD>>"
$AADClientID="<<Application Id of AppRegistrion(1)>>"
Write-Host "Retrieving the AAD Credentials...";
$credential = New-Object UserPasswordCredential($AADuserName, $AADpassword);
$authenticationContext = New-Object AuthenticationContext($ADAuthorityURL);
$authenticationResult = [AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authenticationContext, $resourceURL, $AADClientID, $credential).Result;
$authenticationResult.AccessToken

Related

Powershell - Ingesting API json results into SQL Server table

Looking for some help with ingesting data retrieved from an API endpoint and inserting it into SQL Server. This endpoint returns json.
I'm trimming the script to make this more readable. The script gets the data I'm requesting, the issues is the insert into the SQL table.
# Pass the `Authorization` header value with the payload we calculate from the id + secret
$Time = Invoke-RestMethod -Uri $TimeCardURL -Method Get -Header #{ Authorization = "Bearer ${AuthorizationValue}" } -Body $Body -Certificate $Cert -ContentType 'application/json'
$Time.teamTimeCards | Select-Object associateOID,timeCards
#SQL authentication and insert $Result data
$serverName = "sql-server"
$databaseName = "database"
$tableName = "table"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
foreach($ID in $associateOID){
$insertquery="
INSERT INTO $tableName
([associateOID],[timeCards])
VALUES
('$associateOID','$timeCards')"
$Command.CommandText = $insertquery
$Command.ExecuteNonQuery()
}
$Connection.Close();
It's trying to load the entire object $associateOID into the column, which is resulting in a "String or binary data would be truncated in table 'database.table', column 'associateOID'. Truncated value: '1 2 3 4 5 6 7 8'. The statement has been terminated."
I'm guessing there is an issue with this section of the script
$Time.teamTimeCards | Select-Object associateOID,timeCards
I rewrote your code to use another source of data, but you probably get the idea:
$output = Get-Process | Select-Object Handles, Id, ProcessName
echo($output)
foreach($value in $output){
$id = $value.Id
$name = $value.ProcessName
$insertquery="
INSERT INTO $tableName
([ID],[Name])
VALUES
('$id','$name')"
echo($insertquery)
}

How to pass csv file as query param in api call using powershell

I have developed two simple PS scripts that work fine separately. Script1 connects to a DB, run a sql query and save the output (only one column that is a list of the project names) as csv file. Script2 connects to an endpoint using API calls and prints the details of a projects. I use script1's output as script2's input manually. I have tried a couple of different ways to automate this process but I haven't been able to get it to work. Does anyone know how can I pass the csv file as query param in api call?
Here is what I have so far:
This is Script1:
#SQL Connection variables
$Server = "my server"
$DBName = "db name"
$credential = Import-CliXml -Path "C:\Test\MyCredential.xml"
$User = $Credential.UserName
$PW = $credential.GetNetworkCredential().Password
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = "Server = $Server; Database = $DBName; User ID = $User; Password = $PW;"
$Connection.Open()
#$Connection.State
$SqlQuery = "select from table example"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $Connection
$SqlCmd.CommandText = $SqlQuery
$CxSqlCmd.CommandTimeout = 0
#Creating sql adapter
$SqlAdapter = New-Object System.Data.sqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
#Creating Dataset
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | export-csv -Path $OuputFile -NoTypeInformation
The output for script 1 is 11223344, So I use this project name as my input or query param in my second script.
And this is Script2:
$credential = Import-CliXml -Path "C:\Test\MyCredential2.xml"
$credential = Import-CliXml -Path "C:\Test\MyCredential2.xml"
$APIKEY = $credential.GetNetworkCredential().Password
$token = "APIKEY " + "$APIKEY"
$Params = #{
uri = 'https:myendpoint/search?name=11223344'
Headers = #{'Authorization' = "API KEY $token"}
Method ='GET'
ContentType = 'application/json'
}
$Response = Invoke-RestMethod #Params
I really appreciate it if someone can help me with this.

Livestream data from SQL to Power BI online service using PowerShell or other options

I have an assignment to setup a live Power BI online service tile using live data streaming from SQL table. The data in the table updates every few seconds. Here is what I got so far using PowerShell.
But it appears to be not refreshing the data set every few seconds. What am I missing?
DO
{
$SqlServer = 'ServerName';
$SqlDatabase = 'DBName';
$sleepDuration = 3
$SqlConnectionString = 'Data Source={0};Initial Catalog={1};Integrated Security=SSPI' -f $SqlServer, $SqlDatabase;
$SqlQuery = "SELECT * FROM MyTable;";
$SqlCommand = New-Object -TypeName System.Data.SqlClient.SqlCommand;
$SqlCommand.CommandText = $SqlQuery;
$SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $SqlConnectionString;
$SqlCommand.Connection = $SqlConnection;
$SqlConnection.Open();
$SqlDataReader = $SqlCommand.ExecuteReader();
##you would find your own endpoint in the Power BI service
$endpoint = "......My PowerBI Service Push URL.........."
#Fetch data and write out to files
while ($SqlDataReader.Read()) {
$payload =
#{
"Col1" =$SqlDataReader['Col1']
"Col2" =$SqlDataReader['Col2']
}
Invoke-RestMethod -Method Post -Uri "$endpoint" -Body (ConvertTo-Json #($payload))
# Sleep for a second
Start-Sleep $sleepDuration
}
$SqlConnection.Close();
$SqlConnection.Dispose();
} While (1 -eq 1)

Sorting array values using Powershell

I'm trying to output a list of items pulled from an API we use to connect to our MDM console. I have two functions, both of which work together and I can see all the data in the output of the script, however, I would like to sort this data into a .csv file using the variable names from one of the functions as the column headers. I'm new to PS and have been pulling my hair out.
I can see that the variable is an array and all the values in there, but have zero idea how to sort if or if there is a better way to grab the data I need.
#Current MDM Environment
$ev = "Q"
#Define MDM credentials to match environment from above
if($ev -eq "Q")
{
$Code = 'VbvmMGOV0Pd2lF4GurpBqnwD/R6mFmUKI6z3CKAY5tw='
$ui = 'MDMqualserver'
}
else{$Code = 'Pe8w/3jDREgse2gUu3UYZ28FHeafg0xcheu/AYwJ6PE='
$ui = 'MDMprodserver'}#>
#API Auth for MDM Console
$Auth = Get-Content -path 'C:\ProgramData\ScriptAuth\mobilityapi.txt'
$Contenttype = 'application/json'
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy')
$path = "C:\users\username\desktop\$currentDate.csv"
Function get_all
{
$array =#()
#Define URL
$url = "https://$ui.company.gov/api/mdm/devices/extensivesearch?
pagesize=10000"
#Define Headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],
[String]]"
$headers.Add("aw-tenant-code", $Code)
$headers.Add("Authorization", $Auth)
#Send Rest Request
try{
$response = Invoke-RestMethod -uri $url -Headers $headers}
catch{
$error = "BDevice Info Not Found"}
#Close Connection
$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($url)
$SSP = $ServicePoint.CloseConnectionGroup("")
#Parse Device Info
$data = $response.DeviceExtensiveSearchResult.Devices.DeviceDetailsExt
$data | foreach {
$serial = $_.SerialNumber
$array += $serial
}
return $array
}
Function get_devattrib
{
Param([string]$serial)
$array = #()
#Define URL
$url = "https://$ui.company.gov/api/mdm/devices?
searchby=Serialnumber&id=$serial"
#Define Headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],
[String]]"
$headers.Add("aw-tenant-code", $Code)
$headers.Add("Authorization", $Auth)
$headers.Add("Content-Type", $Contenttype)
#Send Rest Request
try{
$response = Invoke-RestMethod -uri $url -Headers $headers}
catch{
return $false}
#Close Connection
$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($url)
$ServicePoint.CloseConnectionGroup("")
#Parse Device Info (#removed .Device from $data = $response.Device)
$data = $response
$data | foreach {
$ownership = $_.Ownership
$friendlyname = $_.DeviceFriendlyName
$platform = $_.Platform
$model = $_.Model
$snumber = $_.AssetNumber
$username = $_.UserName
$mac = $_.MacAddress
$phone = $_.PhoneNumber
$lastseen = $_.LastSeen
$enrollstatus = $_.EnrollmentStatus
$compliance = $_.ComplianceStatus
return [datetime]$lastseen, $ownership, $friendlyname, $platform, $model,
$snumber, $serial, $username, $mac, $phone, $enrollstatus, $compliance
}
}
$devices = #()
$getdevices = #()
$devices = get_all
foreach ($device in $devices){
$getdevices += get_devattrib $device
}
$getdevices
The output of the data looks like this for each device in our console (I have made the info generic to hide company data):
True
Wednesday, September 5, 2018 8:33:21 PM Corporate Owned username - assetnumber Apple iPad Pro with Wi-Fi + Cellular (128 GB Space Gray) asset number serial nubmer username mac address phonenumber Enrolled NonCompliant
A. I don't understand why I get "true" at the beginning of the output for each device in the console and the space afterwards (which seems to come with the [datetime])
B. I don't understand how to place all this data in a .csv file. I do have a path defined before the functions and know how to use export-csv, but the data that it sends to the file appears as just #TYPE System.Boolean so I'm assuming there is something wrong with my last variable. Whew.
You can sort with Sort-Object.
$ArrayOfStrings = 's', 't', 'a', 'c', 'k'
$ArrayOfStrings | Sort-Object

how to backup multiple databases in a script

I need to back up several powershell databases that are on the same server in Azure.
I currently have a script that helps me make backups but individually,
apart I must keep changing the names of the backups
This is my code:
Import-Module $PSScriptRoot\..\util\utilConnection.ps1;
Import-Module $PSScriptRoot\..\util\utilDate.ps1;
#Import-Module $PSScriptRoot\..\logging\Logging_Functions.ps1;
Import-Module AzureRM.sql
$TIMESTAMP = getTimeStamp;
#$LogPath = getPathLog;
#$logFileName = "prueba_jobDatabaseBackup.log";
#Log-Start -LogPath $LogPath -LogName $logFileName -ScriptVersion "1.5"
#return;
#Login-AzureRmAccount
loginRMAccount;
#Set subscription Azure
prueba;
Write-Output "";
#Create credential Source DB Server (QA)
#$myPasswordDB = ConvertTo-SecureString $SQL_ACCOUNT_PASSWORD_QA -AsPlainText -Force;
#$myCredentialDB = New-Object System.Management.Automation.PSCredential ($SQL_ACCOUNT_NAME_QA, $myPasswordDB);
#$sqlCredential = Get-Credential -Credential $myCredentialDB;
#Create credential Source DB Server (Prod)
$myPasswordDB = ConvertTo-SecureString $SQL_ACCOUNT_PASSWORD_QA -AsPlainText -Force;
$myCredentialDB = New-Object System.Management.Automation.PSCredential ($SQL_ACCOUNT_NAME_QA, $myPasswordDB);
$sqlCredential = Get-Credential -Credential $myCredentialDB;
$resourceGroup = "resGroupDB";
$serverName = "domserverqa";
$database = "prueba"; **// here I have to change the name of the backup file**
$primarykey = $STORAGE_ACCOUNT_BACKUP_KEY; #strdatabasebackup
$StorageUri = ("https://strdatabasebackup.blob.core.windows.net/strdatabasebackupblob/(2018-01-09-07:00)dbdom_buin.bacpac"); // here I also have to change the final name individually for each database
#$sqlCredential = getCredentialSQLServerQA; #SQL Server target
$SQL_SERVER_FULLNAME_QA = getSQLServerFullNameAzureQA;
$TIMEOUT = 300;
$importRequest = New-AzureRmSqlDatabaseImport –ResourceGroupName $resourceGroup –ServerName $serverName –DatabaseName $database –StorageKeytype StorageAccessKey –StorageKey $primarykey -StorageUri $StorageUri -AdministratorLogin $sqlCredential.UserName –AdministratorLoginPassword $sqlCredential.Password –Edition Basic –ServiceObjectiveName basic -DatabaseMaxSizeBytes 2147483648 # 2GB -> 2 * 1024 MB -> 2 * 1024 * 1024 KB -> 2 * 1024 * 1024 * 1024 Bytes
$importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink;
while ($importStatus.Status -eq "InProgress")
{
$importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink;
Write-Output ".";
[System.Threading.Thread]::Sleep(2000);
}
[System.Threading.Thread]::Sleep(4000);
How can I implement a foreach or array to put all the databases together and back them up one by one without having to do it manually?
If someone has any ideas please help me thanks
Pass you DBNames as a list to a ForLoop or a funciton
Just pass in a list of database names in a ForLoop, passing the dbname in a variable to your code.
$AzureDBNames = 'AzureDB01','AzureDB01','AzureDB01'
ForEach ($AzureDBName in $AzureDBNames)
{
# Code begins here
"Backing up $AzureDBName"
}
Turn your code into a function with a parameter that accepts one or more db names.
Function New-AzureDBBackup
{
[CmdletBinding()]
[Alias('NABB')]
Param
(
[string[]]$AzureDBNames
)
# Code begins here
}
New-AzureDBBackup -AzureDBNames 'AzureDB01','AzureDB01','AzureDB01'
Read the online help on:
About_Functions
About_For
About_Loops
About_Variables

Resources