Diagnose SQL running from Power Shell - sql-server-2012

I am trying to run a SQL from Power Shell(which is on my windows 7 64 bit desktop) and the remote database host is MS SQL Server 2012.
The code is:
$Server= ".\DB_HOST_NAME"
$Database = "master"
$UserSqlQuery= $("select count(*) from [master].[sys].[some_table]")
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
$Datatable
return $Datatable
}
# declaration not necessary, but good practice
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Write-Host "Statistic: " $resultsDataTable
Write-Host "Message: Transaction Delay is " $resultsDataTable.Rows.Count
When I run this from Windows PowerShell, I get following errors:
Exception calling "Open" with "0" argument(s): "A network-related or
instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify
that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified)" At H:\test2.ps1:11 char:5
+ $Connection.Open()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Exception calling "ExecuteReader" with "0" argument(s): "ExecuteReader
requires an open and available Connection. The connection's current
state is closed." At H:\test2.ps1:15 char:5
+ $Reader = $Command.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader" At H:\test2.ps1:16 char:5
+ $Datatable.Load($Reader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
So the first error is at $Connection.Open() but I don't know anything about power shell to figure out what is wrong. I have tried running the same SQL on the same DB host and it does return a number.
Can I get some help to know what am I doing wrong here?

This code:
$Server= ".\DB_HOST_NAME"
should be:
$Server= "DB_HOST_NAME"
The specification ".\DB_HOST_NAME" is interpreted as a named instance (DB_HOST_NAME) running on your local box.

Related

Unable to connect to SQL server via PowerShell using secure password

I'm trying to connect to SQL server via PowerShell using the below (I'm new to this). I always get the error "login failed" when I use secure password (from Get-Credential or password stored in file). But if I pass the password as plaintext instead of secure string, it connects successfully. Could any one please suggest a method to pass secure password, ideally stored in an external file.
The code I ran and the error is below:
$cred = Get-Credential
$pwd = $cred.Password
$uid = $cred.UserName
$SQLServer = "."
$SQLDBName = "TestDB"
#Initialize connection string
$connString = "Data Source=$SQLServer;Database=$SQLDBName;User ID=$uid;Password=$pwd"
#Create a SQL connection object
$conn = New-Object System.Data.SqlClient.SqlConnection $connString
#Attempt to open the connection
$conn.Open()
if($conn.State -eq "Open")
{
# We have a successful connection here
# Notify of successful connection
Write-Host "Test connection successful"
$conn.Close()
}
Exception calling "Open" with "0" argument(s): "Login failed for user 'TestUser'."
At line:18 char:1
+ $conn.Open()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Further details of error from SQL server:
Login failed for user 'TestUser'. Reason: Password did not match that for the login provided. [CLIENT: <local machine>]
Change this
$pwd = $cred.Password
to this
$pwd = $cred.GetNetworkCredential().Password
However, I would advise against storing a plain text password in memory like this. Your method requires it to--at best--be passed as a parameter in plain text, so you need a better method.
Try using this sqlserver module which supports the -Credential parameter in the Invoke-Sqlcmd function.
I was able to pass secure string as password by adding Integrated Security = True; parameter in connection string.
Thank you.

Invoke-SqlVulnerabilityAssessmentScan SetParent failed for Database

I am in need of some help folks. We are trying to get our SQL Vulnerability Assessment to be done via batch in PowerShell. I'm having some issues setting it all up though and am hoping someone can help me out.
I've tried a few different things but end of the day, I am still getting this error:
Invoke-SqlVulnerabilityAssessmentScan : SetParent failed for Database '[master]'.
At line:1 char:1
+ Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstan ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-SqlVulnerabilityAssessmentScan], FailedOperationException
+ FullyQualifiedErrorId : Microsoft.SqlServer.Management.Smo.FailedOperationException,Microsoft.SqlServer.Management.PowerShell.VulnerabilityAssessment.InvokeVulnerabilityAssessmentScan
$cred = Get-Credential
$instance = "server\sqldb"
Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName "master"
I also tried this:
$cred = Get-Credential
$instance = "server\sqldb"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist $instance
$db = New-Object Microsoft.SqlServer.Management.Smo.Database -argumentlist $srv, "master"
Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName $db
but still gives me the same result.
Any help with this is immensely appreciated!

powershell unable to recognize parameter

I am working on powershell script for connecting to server. If I am passing server name inside script without param it's working, but if I am using input as server name it is saying "server not found". See script below:
clear
#param([string]$servername)
$filePath = "c:\temp\result.txt"
$Servername= "cx-siscsqltest\sqlinst"
#$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0)) as
#'ProductVer';"
$SqlQuery="select * from sys.sysaltfiles"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = '$Servername'; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\temp\version.csv"
#$version=System.Data.DataSet.Tables[0].Rows[0][0]
write-host $version
Above code works well without parameters, if I take servername as parameter i get the following errors:
The term 'param' is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was inclu
ded, verify that the path is correct and try again.
At D:\sysdba\install_sp.ps1:4 char:6
+ param <<<< ([string]$servername)
+ CategoryInfo : ObjectNotFound: (param:String) [], CommandNotFou
ndException
+ FullyQualifiedErrorId : CommandNotFoundException
Exception calling "Fill" with "1" argument(s): "A network-related or instance-s
pecific error occurred while establishing a connection to SQL Server. The serve
r was not found or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections. (provider: Name
d Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At D:\sysdba\install_sp.ps1:25 char:17
+ $SqlAdapter.Fill <<<< ($DataSet)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Can you please help me out?
Param() must be the first line in your script. Remove the clear and you will see in your ISE that the colour of param() will change

powershell https://outlook.office365.com/api/v1.0/me/messages

I had the below Powershell working perfectly until last November the 1st.
$url = "https://outlook.office365.com/api/v1.0/me/messages"
$date = Get-Date -Format "yyyy-MM-d"
## Get all messages that have attachments where received date is greater than $date
$messageQuery = "" + $url + "?`$select=Id&`$filter=HasAttachments eq true and DateTimeReceived ge " + $date
$messages = Invoke-RestMethod $messageQuery -Credential $cred
I get the below error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At G:\Powell\AutoetForO.ps1:23 char:13
+ $messages = Invoke-RestMethod $messageQuery -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Per my investigation; I know its not credential issues; I think they changed their API.
Running the same script with Fiddler capturing traffic I found the body of the error response was:
92
{"error":{"code":"RequestBroker-ParseUri","message":"Syntax error at position 54 in 'HasAttachments eq true and DateTimeReceived ge 2017-01-5'."}}
0
The date looked like the problem. Changing your second line to the following fixed the problem:
$date = Get-Date -Format "yyyy-MM-dd"

SETSPN Error: Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s

I am getting an error and I don't understand why? I have googled and looked as much as I can and still do not have a clear answer. Here is what I am fast with.
Checking domain DC=corp,DC=local
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s
+ CategoryInfo : NotSpecified: (Ldap Error(0x1 ...get_next_page_s:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : computer01.corp.local
Error occured when searching for existing SPN: 0x00000001
Checking domain DC=corp,DC=local
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s
+ CategoryInfo : NotSpecified: (Ldap Error(0x1 ...get_next_page_s:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : computer01.corp.local
Error occured when searching for existing SPN: 0x00000001
This is the command I am running
$comp = "computer01.corp.local"
Invoke-Command -ComputerName $comp -ScriptBlock {
Invoke-Expression "SETSPN -S MSSQLSvc/$comp:1433 CORP\user.name"
Invoke-Expression "SETSPN -S MSSQLSvc/$comp CORP\user.name"
}
The variable $comp does not exist in your remote session, ie it is $null inside your -ScriptBlock{..} statement. Try this:
$comp = "computer01.corp.local"
Invoke-Command -ComputerName $comp -ScriptBlock {
param($comp)
Invoke-Expression "SETSPN -S MSSQLSvc/$comp:1433 CORP\user.name"
Invoke-Expression "SETSPN -S MSSQLSvc/$comp CORP\user.name"
} -ArgumentList $comp
You can add Write-Host "Working on computer:$comp" below param($comp) to verify you passed variable $comp correctly.