Creation of audit via powershell fails with "SetParent Failed" - powershell

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"

Related

Need to connect to DB2 database with PowerShell

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

In PowerShell how to troubleshoot exception in DataSet.Fill?

I'm using a function I found on SO to retrieve data from SQL server and generate XML.
function Invoke-SQL {
param(
[string] $sqlCommand = $(throw "Please specify a query.")
)
$connectionString = "Data Source=$server;Initial Catalog=$database;user id=$uid;password=$pwd"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$tableOutput = $dataSet.Tables
foreach($row in $tableOutput) {
$xml = $row | ConvertTo-Xml -NoTypeInformation -Depth 1
$xml.InnerXML
}
}
It works most of the time but, occasionally, exactly the same SELECT (except for the range) from the same database and table would throw the following exception:
Exception calling "Fill" with "1" argument(s): "Incorrect syntax near '>'."
At DBTest.ps1:22 char:18
+ $adapter.Fill <<<< ($dataSet) | Out-Null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How to debug what rows and/or what data gets the Fill method to break?
As per comments, it was the SQL command itself. When you generate SQL commands make sure every variable goes through validation and sanity checks. As some comments suggested, logging queries can help with troubleshooting.

PowerShell: cannot convert type SMO.server to type SMO.server

Error I'm getting from PowerShell:
Cannot convert argument "srv", with value: "[DBADEV\SQL2008r2]", for "SqlBackup" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[DBADEV\SQL2008r2]" value of type
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:23 char:1
+ $backup.SqlBackup($srv)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I'm attempting to write a PowerShell script to restore a database from our Production box and into our DBADEV box. Below is the code I'm using which is then producing the error.
#Clear Screen
cls
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$ErrorActionPreference = "Inquire"
# Restore [SQLSRV2k8-0102\SQL2008] instance
$BackupFile = Get-ChildItem "\\NetworkShare\r`$\MSSQL10.SQL2008\MSSQL\Backup\AdventureWorks2008r2" | select -Last 1
$BackupFile
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server("DBADEV\SQL2008r2")
$res = New-Object Microsoft.SqlServer.Management.Smo.Restore
$backup = New-Object Microsoft.SqlServer.Management.Smo.Backup
$Backup.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$Backup.Database = "AdventureWorks2008r2"
$Backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$backup.Initialize = $true
$backup.SqlBackup($srv)
$srv.Databases["AdventureWorks2008r2"].Drop()
$res.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$res.Database = "AdventureWorks2008r2"
$res.NoRecovery = $true
$res.SqlRestore($srv)
The error seems a bit cryptic to me (as do most PowerShell errors). Any thoughts on why this is occurring? I'm also getting the error when I use Mike Fal's powershell script here: http://www.mikefal.net/2014/07/22/restoreautomation-powershell-module/
The one thing that seems to get me past this error is by passing "DBADEV\SQL2008r2" directly into SQLRestore,
i.e. $res.SqlRestore("DBADEV\SQL2008r2") instead of $res.SqlRestore($srv)
This now generate an error stating "Restore failed for Server 'DBADEV\SQL2008r2'
Well from my experiences this kind of errors appear because of wrong name/data type in variable.
I would try to escape \ in "DBADEV\SQL2008r2"
or try what I found on MSDN
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
Write-Host $srv.Information.Version
so it could look like
New-Object Microsoft.SqlServer.Management.Smo.Server("(DBADEV\SQL2008r2)")

Why does setting the 'QueuingEnabled' of a COM+ app remotely by powershell cause the save to fail?

I have this powershell script which is creating COM+ applications on a remote machine:
$credentials = Get-Credential -Message "Test" -User "DOMAIN\User"
$roleRM = new-pssession -computername MACHINE -credential $credentials
Invoke-Command -Session $roleRM -scriptblock `
{
$comAdmin = New-Object -ComObject ("COMAdmin.COMAdminCatalog.1")
$comApplicationCollection = $comAdmin.GetCollection("Applications")
$comApplicationCollection.Populate()
$comApplication = $comApplicationCollection.Add()
$comApplication.Value("Name") = "Server"
$comApplication.Value("ApplicationAccessChecksEnabled") = 0
$comApplication.Value("AccessChecksLevel") = (0)
$comApplication.Value("Authentication") = (1)
$comApplication.Value("Identity") = "DOMAIN\User"
$comApplication.Value("Password") = "password"
$comApplication.Value("QueuingEnabled") = 1
$comApplication.Value("QueueListenerEnabled") = 1
$comApplicationCollection.SaveChanges()
}
but when I try and run it it fails with this error:
Exception calling "SaveChanges" with "0" argument(s): "An operations error occurred.
"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : MACHINE
If I exclude this line:
$comApplication.Value("QueuingEnabled") = 1
then it saves and creates the application correctly. If I run this script locally then it creates the application correctly on the local machine with QueuingEnabled=1, but always fails when running on a remote machine.
Why might this be?
Try setting "Authentication" to 4 or 6 and see if that changes anything. See this.

Powershell CMDLET Cross Domain Managment

I'm logged in at domain "domain1" with my account. I wish via powershell to be able to update users in domain "domain2" via my supe ruser account "suaccount" with password "password1". Trust is established between the two.
Running PowerShell 2.0 and .NET 3.5 SP1
I have gotten this far:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$context = New-Object -TypeName
System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, "domain2", "OU=TestOU,DC=domain2", "suaccount", "password1"
$usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$usr.Name = "AM Test1"
$usr.DisplayName = "AM Test1"
$usr.GivenName = "AM"
$usr.SurName = "Test1"
$usr.SamAccountName = "AMTest1"
$usr.UserPrincipalName = "amtest1#mtest.test"
$usr.PasswordNotRequired = $false
$usr.SetPassword("errr")
$usr.Enabled = $true
$usr.Save()
Pretty new to PowerShell, any pointers? I want to edit/create users on the "other" domain so to speak.
I get the error:
"Exception calling "Save" with "0" argument(s): "General access denied error
"
At C:\Script\Sandbox\Morris PowerShell Application\includes\mo\mo.ps1:104 char:14
+ $usr.Save <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException"
Any pointers?
From comments: Try using for username this format domain2\username, and always use the FQDN for the domain. – Christian yesterday