creating an output variable azure devops from the Azure SQL InlineSqlTask task - sql

I have this in yaml with azure devops :
- task: SqlAzureDacpacDeployment#1
displayName: 'Azure SQL InlineSqlTask'
inputs:
azureSubscription: 'Service Connection'
AuthenticationType: servicePrincipal
ServerName: 'xxx.database.windows.net'
DatabaseName: 'xxx-Dev'
deployType: InlineSqlTask
SqlInline: |
select name as username,
create_date,
modify_date,
type_desc,
authentication_type_desc as authentication_type
from sys.database_principals where type_desc = 'EXTERNAL_USER'
I need to be able to get the output of this t-sql command stored in a variable so i can use it later on in my pipeline. Any ideas how i get this output and store it in the variable.
I would usually use a powershell command to set the environment variable but obviously this cannot be done within this task.
Any ideas would be amazing.

I have sorted this out. So I can use a powershell script within Azure Devops so i can directly get the variable and then use the setvariable task to assign the output as an env:variable.
$query = "select name as username,
create_date,
modify_date,
type_desc,
authentication_type_desc as authentication_type
from sys.database_principals where type_desc = 'EXTERNAL_USER'"
$clientid = "guid"
$tenantid = "guid"
$secret = "guid"
$request = Invoke-RestMethod -Method POST `
-Uri "https://login.microsoftonline.com/$tenantid/oauth2/token"`
-Body #{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$clientid; client_secret=$secret }`
-ContentType "application/x-www-form-urlencoded"
$access_token = $request.access_token
$sqloutput = Invoke-Sqlcmd -ServerInstance $.database.windows.net -Database db$ -AccessToken $access_token -query $query
Write-Host "##vso[task.setvariable variable=GetVar;]$sqloutput"

Related

Invoke-ASCmd XMLA Results to storage results in Azure Data Lake with either .csv or .txt format

I've built an Azure Powershell runbook (5.0) to run a MDX query against a SSAS server , the query is just to get the partition names
SELECT
[Name]
FROM $SYSTEM.TMSCHEMA_PARTITIONS
WHERE [Name] <>'Partition'
If I run it in SSMS I get the desired results
The problem comes when I run the query using the powershell runbook because the results are basically an XMLA output
What I need is the Azure powershell runbook to extract just that column from the $Results variable and then create either a .txt file or .csv in the Azure data lake storage V2 with that data ( like the SSMS). That file will be consumed later by Data Factory.
This is the full script:
Param
(
[Parameter (Mandatory= $true)]
[String] $Query,
[Parameter (Mandatory= $true)]
[String] $OperationType,
[Parameter (Mandatory= $true)]
[String] $ServerName,
[Parameter (Mandatory= $true)]
[String] $DatabaseName,
[Parameter (Mandatory= $true)]
[String] $SecretName
)
$cred = Get-AutomationPSCredential -Name $SecretName
$Results = Invoke-ASCmd -Server $ServerName -Database $DatabaseName -Credential $cred -Query $Query
Write-Output $Results
I have reproduced in my environment and got expected results as below:
SSMS:
SELECT [Name] FROM $SYSTEM.TMSCHEMA_PARTITIONS
NOTE:
Your $Results is taking the output as string, you should be converting it to Xml using [XML] in PowerShell script.
Then use below code instead of your code :
$Results = [XML] (Invoke-ASCmd -Server $ServerName -Database $DatabaseName -Credential $cred -Query $Query)
Now use below code:
Write-Output $Results.return.root.row.Name
Output:
You need to incorporate the above 2 codes into your code.After that you need to send the output to your requirement.

PS Script to Import users from Azure SQL Table to AAD

I need help with a baseline script (if possible at all) to extract users from Azure SQL to Azure AD with the fields in the SQL tables. Is there such a way to get this into AAD, not On Premise AD? The fields are phone, department..etc However does such a way even exist? I know for On Premise yes, but I cannot seem to locate anything for Azure.
Thank you all in Advance!
to extract users from Azure SQL to Azure AD with the fields in the SQL tables
Achieving this you have to follow the below steps.
Get the user table data from the SQL table
Export the user data into csv file.
create the users in Azure AD using the csv file.
You can use the below script to export Azure SQL Table data. Then exported data can be saved in a csv file.
Import-Module sqlps
$SQLServer = "<Your Azure SQL server>"
$DatabaseName = "<Database Name>"
$ExportLocation = "<Path to Export>"
$ResourceGroupName ="<Your resource group name>"
#Select Database
Get-AzureRmSqlDatabase -ServerName $SQLServer -ResourceGroupName $ResourceGroupName | select $DatabaseName
# Get Server Instance
$ServerInstance = Get-AzureRmSqlServer -ResourceGroupName $ResourceGroupName | where {$_.ServerName -eq $SQLServer}
$params = #{
'Database' = $DatabaseName
'ServerInstance' = $ServerInstance
'Username' = '<userName>'
'Password' = '<Password>'
'Query' = 'SELECT * FROM UsersTable'
}
$userResult = Invoke-Sqlcmd #params
$result |export-csv "$ExportLocation$userinfo.csv" -notypeinformation
Fetching all information from table
# Get user information from table
$Tables = (Get-SqlDatabase -ServerInstance $ServerInstance -Name $DatabaseName).tables
foreach($table in $Tables) {
$SQLquery="select * from $($table)"
$result=invoke-sqlcmd -query $SQLquery -serverinstance $SQLServer -database $DatabaseName
Write-Host "Now Exporting Table $table"
$result |export-csv "$ExportLocation$($table.Name).csv" -notypeinformation
}
Or in an Azure portal -> Azure SQL Database -> Query Editor also you can export the csv file.
After exported the CSV file import the user information into Azure AD.
Refer Link 1 & Link 2 to import users into Azure AD

Using PS to query SQL for list of users, then disable Active Directory accounts?

I'm trying to use Powershell to query SQL database for a list of suspended users, pipe into a variable, then use that to loop through and disable those AD accounts. Here's the code I'm using... note I'm just trying to write the output now instead of making a change so I don't do anything I regret.
Import-Module ActiveDirectory
$Users = Invoke-Sqlcmd -ServerInstance 'SERVER' -Database 'NAME' -Query "SELECT EmployeeID,
EmployeeStatus FROM [NAME].[dbo].[employee] WHERE EmployeeStatus = 'S'"
foreach ($user in $users)
{
Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" `
-SearchBase "OU=Logins,DC=domain,DC=com" |
#Set-ADUser -Identity $Name -Enabled $False
Write-Verbose $User
}
The SQL query is working fine, but when I run the loop it's giving this error:
Write-Verbose : The input object cannot be bound to any parameters for
the command either because the
command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline
input.
Am I just formatting this incorrectly? Or is there another way I should be thinking of this?
Thanks in advance!
If you would like to find inactive user accounts in Active Directory, you can use the Search-ADAccount cmdlet. You need to do this use the “-AccountInActive” parameter with Search-ADAccount.
PowerShell command below:
Search-ADAccount –AccountInActive –TimeSpan 120:00:00:00 –ResultPageSize 2000 –ResultSetSize $null | ?{$_.Enabled –eq $True} | Select-Object Name, SamAccountName, DistinguishedName | Export-CSV “C:\Temp\InActiveADUsers.CSV” –NoTypeInformation
I have given timespan for 120days and export the list into csv file.

How to query a remote database with a powershell command?

I've done some research and I found the command "Invoke-Sqlcmd". I believe this is the command I want to use, but not which arguments. I've tried multiple things, but keep getting "invoke-sqlcmd : Login failed for user 'Hello'". Here is some practice data:
"Forehead" is the name of the server I am executing the PowerShell query from
"Elbow" is the name of the server that is running the SQL database
"Kitten" is the name of the database on "Elbow"
"Fluid" is the name of the table I wish to query
"Hello" is the username to log into "Elbow"
"World" is the password to log into "Elbow"
"Timmy" is the username to log into "Kitten"
"Sticky" is the password to log into "Kitten"
"SELECT * FROM Fluid" is the query I wish to run
With this information, from "Forehead" how can I execute the above query on Kitten? Is there more information I need?
Thank you for any help!
You need to pass the username, password, sql server and database to Invoke-Sqlcmd. Then your query (nice namings... :-)) should work.
$ServerInstance = 'Elbow'
$Database = 'Kitten'
$Username = 'Timmy'
$Password = 'Sticky'
$Query = 'SELECT * FROM Fluid'
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Username $Username -Password $Password -Query $Query

T-SQL file into powershell script

I have a txt file(load_check_run_bmu.sql) that contains the following sql code.
RESTORE DATABASE Address from disk='C:\dir\path\address.bmu'
Use Client
GO
Select f_name
From
cst.name
USE wage
GO
Exec sp_salary
Use Client
GO
Select f_name
From
cst.name
I then have a batch file that contains:
sqlcmd -S .\NorthWind -i"C:\scripts\load_check_run_bmu.sql"
What I need to do is be able to execute all of necessary SQL commands in a powershell script and eliminate the sql txt file and the sqlcmd batch file
I'm aware I would need the following code, but I am struggling on how to convert the T-SQL script into something usable for the $SqlCmd.CommandText variable
$sqlServer = "."
$sqlDBName = "NorthWind"
$sqlConnectionString ="Server = $sqlServer; Database = $sqlDBName; Integrated Security = True"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $sqlConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
**$SqlCmd.CommandText = [SQL Command(s)]<====( Need assistance populating this)**
$SqlCmd.Connection = $SqlConnection
$SqlCmd.Connection.Open()
$ReturnValue = $SqlCmd.ExecuteNonQuery()
$SqlCmd.Connection.Close()
Put the T-SQL .txt file into a string using double quotes " and take out the GO statements. You can also end each statement with ; to ensure queries do not get mixed up and the queries should run without failure:
$TSQLString = "RESTORE DATABASE Address from disk='C:\dir\path\address.bmu';
Use Client;
Select f_name
From
cst.name;
USE wage;
Exec sp_salary;
Use Client;
Select f_name
From
cst.name;"
Then use the string for your variable:
$SqlCmd.CommandText = $TSQLString
It also looks like you using multiple databases in the query above. If this is the case this approach might not work has you are connecting to a single database with the statement below.
$sqlConnectionString ="Server = $sqlServer; Database = $sqlDBName; Integrated Security=True"
To get round this you will need to open up a connection for each statement. So you might want to make a function that connects to a server\database and runs a given query e.g (Run-Sql would be the function you need to create).
$SQLQuery1 = "RESTORE DATABASE Address from disk='C:\dir\path\address.bmu';"
$SQLQuery2 = "Select f_name From cst.name;"
$SQLQuery3= "Exec sp_salary;"
$SQLQuery4 = "Select f_name From cst.name;"
# Run all statments
Run-SQL -query $SQLQuery1 -DB "NorthWind" -Server "."
Run-SQL -query $SQLQuery2 -DB "Client" -Server "."
Run-SQL -query $SQLQuery3 -DB "wage" -Server "."
Run-SQL -query $SQLQuery4 -DB "Client" -Server "."
Use invoke-SQLCMD
Whick is part of sqlps module