I have been able to connect to the PostgreSQL Server with OdbcConnection.
$DBConnectionString = "Driver={PostgreSQL ANSI(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
However I wish to connect to the PostgreSQL with command Invoke-Sqkcmd. I was told to always try to use the cmdlets and their commands. I tried it with:
$MyPort = '5432'
$MyUid = 'postgres'
$MyPass = 'pass'
$DBSvr = 'server'
$DBase = 'database'
$sqlcmd = 'SELECT email_addr FROM member_subscribers LIMIT 20'
$data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance $DBSvr$MyPort -Username $MyUid -Password $MyPass
Write-Output $data
However, I get the error.
Invoke-Sqlcmd : 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: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
At line:13 char:9
+ $data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At line:13 char:9
+ $data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScri
ptCommand
I know the credentials should be correct. So maybe the formatting is just wrong? I am not sure....
Invoke-SQLCmd is a SQL Server cmdlet. You can't connect to postgres using it.
Related
I'm trying to use the Set-AzSqlServerAudit PowerShell command as follows:
Set-AzSqlServerAudit -ResourceGroupName "My_RG" -ServerName "My_Server" -BlobStorageTargetState Enabled -StorageAccountResourceId "XXXXXX" -RetentionInDays 365 -PredicateExpression "[database_principal_name]= 'dbo' OR ([action_name] = 'DATABASE AUTHENTICATION FAILED' OR [action_name] = 'CREATE SERVER AUDIT SPECIFICATION' OR [action_name] = 'ALTER SERVER AUDIT SPECIFICATION' OR [action_name] = 'DROP SERVER AUDIT SPECIFICATION')"
If I limit the PredicateExpression parameter to "[database_principal_name]= 'dbo'" then it works fine, but using the expression I want results in the following error:
Set-AzSqlServerAudit : One or more errors occurred. At line:1 char:1
+ Set-AzSqlServerAudit -ResourceGroupName "My_RG" -ServerName "My_Serv...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzSqlServerAudit], AggregateException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.Auditing.Cmdlet.SetAzSqlServerAudit
I couldn't get the output for my query which I am trying to run thru PowerShell.
$connection = New-Object System.Data.OleDb.OleDbConnection("Provider=IBMDADB2;DSN=;User Id=;Password=");
$ds = New-Object "System.Data.DataSet"
$QuerySQL = "select * from omaa.status"
$da = New-Object System.Data.OleDb.OleDbDataAdapter($QuerySQL, $connection)
$da.Fill($ds)
I am getting this exception
Exception calling "Fill" with "1" argument(s): "Unspecified error"
At line:6 char:9
+ $da.Fill <<<< ($ds)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I know this is an aging thread, but maybe this will help someone. I'm using this, and it works for Oracle and DB2 connections. (Not with acceleration for DB2 though). Exports CSV, but this can be modified to convert to xlsx afterwards.
function Get-OLEDBData ($connectstring, $sql) {
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
return $dt
}
#For Oracle
$connString = "password=yourPassword;User ID=YourID;Data Source=YourServer;Provider=OraOLEDB.Oracle"
#For DB2
$connString = "Provider=DB2OLEDB.1;Network Transport Library=TCPIP;Network Address=YourIPHere;Network Port=YourPortHere;Initial Catalog=YourDatabaseHere;Package Collection=NULLID;Default Schema=SameAsYourDatabaseHere;User ID=YourID;Password=YourPassword;"
$qry= "select something from somewhere"
Get-OLEDBData $connString $qry | Export-Csv -Path C:\TargetFolder\Results.csv -Delimiter ";" -NoTypeInformation
I need to execute a query against an on-premise SQL Server 2016 instance from our Azure automation account for the purpose of sending emails based on the content in the database.
The client is unable to establish a session, it is a networking issue. I think I might be missing a middle step or have not given the SQL Server module enough information to target our on premises server.
I am using the sqlserver module
I have checked the TCP/IP settings are enabled for the on premises instance
I turned on SQL Server Browser (i do not think this is required)
I tested the code on my local Powershell ISE and it worked
I tried using Windows Auth and SQL Server auth
Code:
Import-Module sqlserver
$from = "x.y#dom.com"
$to = "email#gmail.com"
$SMTPServer = "smtp.sendgrid.net"
$SMTPPort = "587"
$username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$password = "xxxxxxxxxxx"
$subject = "Email test from Azure SMTP server"
$body = "Test email body, no content to see here!"
#$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
#$smtp.Send($From, $To, $subject, $body)
function Get-EmailBody{
}
<#
Get all emails which have been merged into the emailChangeHistory table with the flag emailSent = 0.
#>
function Get-ChangeHistory($sqlServer, $database, $emailSent = 0){
Invoke-Sqlcmd -Query "select 1" -ServerInstance "servername"
}
Get-ChangeHistory -sqlServer $null, -database $null, -emailSent $null
I get this error:
Invoke-Sqlcmd : 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL
Server)
At line:30 char:5
+ Invoke-Sqlcmd -Query "select 1" -ServerInstance "servername"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
I am using the Invoke-sqlcmd cmdlet in Powershell to run an SQL query saved in a string against a remote server.
I have included the credential parameter to ask for domain credentials to connect to the SQL instance.
I've tested this without the credential parameter; instead running the Powershell window as the user, this works fine, so I am confident that permissions for the user are set correctly.
However, I cannot get it to work with the credential parameter.
Import-Module -Name SqlServer -force
function Correct-Servername {
param(
[string] $dataSource = ".\SQL",
[string] $database = "MASTER",
[string] $sqlCommand = "sp_dropserver ##servername DECLARE #ServerName SQL_VARIANT = (SELECT serverproperty('Servername')), #SQLQuery NVARCHAR(4000); SET #SQLQuery = 'sp_addserver ''' + CONVERT(NVARCHAR(100), #SERVERNAME) + ''', ''LOCAL''' PRINT #SQLQuery EXECUTE sp_executesql #SQLQuery"
)
$cred = Get-Credential
Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Database $database -Credential $cred
}
Correct-Servername | out-file -FilePath C:\Temp\correct_servername.log
This is the error i receive:
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
Invoke-Sqlcmd : Login failed for user 'domain\user'.
At C:\Temp\Rename-Create-Replication-2.ps1:20 char:2
+ Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At C:\Temp\Rename-Create-Replication-2.ps1:20 char:2
+ Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Any assistance is appreciated.
I'm trying to create a new server audit on a WinServer 2008 R2 with the following PowerShell Script.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$server = "SM1111" #change to desired instance
$instance = "S111"
$auditName = "$instance"+"TestAudit"
$auditDir = 'F:\Microsoft SQL Server\'+$instance+'AuditTestLogsNew\'
$srv = new-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $instance
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
$newAudit.DestinationType = [Microsoft.SqlServer.Management.Smo.AuditDestinationType]::File
$newAudit.FilePath = $auditDir
$newAudit.MaximumRolloverFiles = 10
$newAudit.MaximumFileSize = 100
$newAudit.QueueDelay = 1000
$newAudit.Create()
$newAudit.Enable()
However the following line always fails:
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
I get the following error message:
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Audit 'S111TestAudit'. "
At MYFOLDER\Documents\Auditing_Test\CreateAudit.ps1:9 char:13
+ $newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I've been googling a lot, but still haven't found anything that might solve the problem, since I don't quite understand what raises the error to begin with.
I have full administrator privileges.
Any help would be appreciated!
You are missing the server name for your instance. Your variable $srv is not pointing to an actual server instance.
$server = "SM1111" #change to desired instance <- This isn't doing anything
$instance = "S111"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist "$server\$instance"