PS Script to Import users from Azure SQL Table to AAD - sql

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

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.

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

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"

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

Script out all SQL objects under particular schema

Is there any way I can script out all the SQL Server objects (tables, SP, functions etc) under a schema?
In our database we have a table containing name of all the schemas and there are more than 500 schema. Some of them are for dev and some are prod. I need to script out all the objects under dev schema and create a new database.
ApexSQL Script is the tool which can be very helpful in this situation. It is the tool which creates SQL scripts for database objects, and it can script all objects into one script or all objects separately.
For this situation here is what you should do:
Select server and the database which you want to script and load them.
Go to the View tab and click the “Object filter” button, then select the “Edit filter” button:
In the Filter editor for all objects select the “Include if:” and “Click here to add filter criteria”:
Select the “Schema”, “Equals” and Enter the desired schema name, then click OK:
Click on the Home tab, check all objects and Click the “Script” button:
In the third step of the Synchronization wizard, under the Script file tab, select if you want to create one script for all objects or for each object individually from the Granularity drop down menu:
In the last step of the Script wizard click the Create button and check out the results – you will have the script which can be executed in the SQL Server Management Studio.
Thanks guys for your reply. I have solved this by generating all the scripts through SSMS and then created a schema only database. Than I dropped all the tables, views SP, functions etc those are not part of the schema I do not need.
It took me around 20 mins to do that. But after all the work is done.
This is PowerShell answer to your problem.
$Server= 'SERVER_NAME'
$Database= 'DATABASE_NAME'
$SmoScriptPath = 'SCRIPT_OUTPUT.SQL'
$Schemas = #("dlo", "deo") # include objects that fall under this schema set
$ObjectTypes = #("StoredProcedures", "Views", "Tables") #object types to be included
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
$SmoServer = new-object "Microsoft.SqlServer.Management.SMO.Server" $Server
$SmoServer.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$SmoDb = New-Object "Microsoft.SqlServer.Management.SMO.Database"
$SmoDb = $SmoServer.Databases[$Database]
$SmoScr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
$SmoScr.Server = $SmoServer
$SmoScr.Options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
$SmoScr.Options.AllowSystemObjects = $false
$SmoScr.Options.IncludeDatabaseContext = $true
$SmoScr.Options.IncludeIfNotExists = $false
$SmoScr.Options.ClusteredIndexes = $true
$SmoScr.Options.Default = $true
$SmoScr.Options.DriAll = $true
$SmoScr.Options.Indexes = $true
$SmoScr.Options.NonClusteredIndexes = $true
$SmoScr.Options.IncludeHeaders = $false
$SmoScr.Options.ToFileOnly = $true
$SmoScr.Options.AppendToFile = $true
$SmoScr.Options.ScriptDrops = $false
$SmoScr.Options.Triggers = $true
$SmoScr.Options.ExtendedProperties = $true
$SmoScr.Options.FileName = $SmoScriptPath
New-Item $SmoScr.Options.FileName -type file -force | Out-Null
Foreach ($ObjectType in $ObjectTypes) {
$Objects = $SmoDb.$ObjectType | where {$_.IsSystemObject -eq $false -and $Schemas.Contains($_.Schema)}
Foreach ($Object in $Objects | where {$_ -ne $null})
{
$SmoScr.Script($Object)
}
}
If you are looking for a solution for getting these objects scripted on a schedule and checked into a GIT Repo Automatically.
Check out the following project I have shared: https://github.com/Drazzing/mssqlobjectstogit
What you get:
Changes to MS SQL Objects over time in [GIT]
Report that shows who Added / Deleted / Changed the objects over time [CSV]
Report Example:
You can use Redgate SQL Compare
or
use management studio generate script feature.