2

I have a problem with running SQLPS commands to create a DB on Windows Server 2012R2 and Powershell v4

#Import SQL Server Module called SQLPS
Import-Module SQLPS -DisableNameChecking

#Your SQL Server Instance Name
$Inst = "sql03"
$Srvr = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $Inst

#database PSDB with default settings
#by assuming that this database does not yet exist in current instance
$DBName = "PSDB"
$db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database($Srvr, $DBName)
$db.Create()

#Confirm, list databases in your current instance
$Srvr.Databases |
Select Name, Status, Owner, CreateDate

I receive the below error:

New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Database 'PSDB'. "
At C:\test.ps1:11 char:7
+ $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database($Srvr, $D ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

You cannot call a method on a null-valued expression.
At C:\test.ps1:12 char:1
+ $db.Create()
+ ~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The following exception occurred while trying to enumerate the collection: "Failed to connect to server sql03.".
At C:\test.ps1:15 char:1
+ $Srvr.Databases |
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : ExceptionInGetEnumerator

Any suggestions how to fix this?

MSalem
  • 21
  • 1
  • 3
  • 1
    Do you have the correct instance name? I.e., Are you trying to access the default instance on SQL03? I think the "Failed to connect to server sql03." is where the problem is – grambo25 Jun 16 '16 at 19:48
  • I am running the command from SQL03 itself – MSalem Jun 16 '16 at 20:26
  • You can have multiple instances of SQL Server running on the same Windows Server. If you were to try to connect to your SQL Server through SSMS, what is in the Server Name field? – grambo25 Jun 16 '16 at 20:27
  • It just one instance "MSSQLSERVER" – MSalem Jun 17 '16 at 09:54
  • Did you find the solution? I'm running into the same error – spuder Oct 04 '17 at 16:49

1 Answers1

0

If you are working locally try replacing:

$Srvr = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $Inst

With:

$Srvr = new-object ('Microsoft.SqlServer.Management.Smo.Server') localhost
DBADon
  • 449
  • 5
  • 9