How to query a remote database with a powershell command? - sql

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

Related

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.

Invoke multiple sql using powershell in sequence with runtime arguments

I'm trying to run sql queries in sequence. If any one of the sql query fails, then the windows powershell script should exit and send email. The log should be written to the log directory. where data= < this will passed in the run time>
Example code below:
Invoke-Sqlcmd -Query "SELECT data from emp where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from class where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from stud where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from cust where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from new where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Any help would be appreciated.
Regards,
What does it look like when "sql query fails"? You could rely on the Invoke-SqlCmd function's return, or have an expected "fail" message (or multiple messages).
I'm not familiar with Invoke-SqlCmd. Check out the MSDN page; -AbortOnError looks like it would be helpful to you, as would -ErrorLevel.
Here is an outline for a single expected error, with comment on how to extend. it's worth storing your queries in an array so that you can loop over then and break out of a loop instead of having linear code (where you have to copy and paste the check part after each invoke-sqlcmd
# string with a single error. you could use an array and add
# a foreach ($error in $errors) on the line marked #here
$expectedError = "Failed"
# Functions have to appear above where they are used
Function Check-SQLResults($result){
# a try-catch statement will execute the code in the try part, going
# to the catach part on a TERMINATING error
try{
# check each line for your expected error
foreach($line in $result){
#here
if($line -like "*$expectedError*"){
Write-Error "Something went wrong: $line" -ErrorAction Stop
}
}
# true is only returned if none of the result lines are like your error
return $true
}catch{
# false is returned if any lines contain error
return $false
}
}
# store the sql outcome in a variable so you can check it
$result = Invoke-Sqlcmd -Query "SELECT data from emp where data=;" -ServerInstance "MyComputer\MyInstance"
# using a function that tells you if the results contain an error or not is neater.
# again, this is manually dealing with errors and invoke-sqlcmd provides other options.
$resultIsErrorFree = Check-SQLResults -result $result
If(resultIsErrorFree -eq $true){
# execute next invoke-sqlcmd
}else{
# Send e-mail. $results can be added to body.
}

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

Calling sproc on SQL Azure from Invoke-Sqlcmd

The form to hit a regular sql server:
$server = "192.168.1.1"
$myDatabase = "Adventures"
$myUser = "Joe"
$myPass = "BadPass"
Invoke-Sqlcmd -ServerInstance $server -Database $myDatabase -Username $myUser -Password $myPass
For Azure SQL http://www.connectionstrings.com/sql-azure/ tells me to bracket the servername as:
[plkahglkhjl].database.windows.net
but that gets me a error message that the server can not be found or was not accessible. It's behaving as if it were a firewall blocking but I have a open connection in SSMS without problem.
Is there another set of validation/authentication that PowerShell scripts have to deal with?
thx
ConnectionStrings.com is just indicating that you need to replace those fields with your own, not that you actually need brackets.
1) You do not need to bracket your server name
plkahglkhjl.database.windows.net
2) You do need to put the server name in the UserName
Joe#plkahglkhjl
More details here: Error connecting to SQL Azure Database