Trying to get the status of mirrored databases using powershell - sql-server

I am trying to test the following script in powershell which gets the status of the mirrored databases.
#SQL Variables
$sqlservers = "APNSQL01"
#SQL database mirroring status
$body +=echo "------------Originating Server-----------"`r`n""`r`n""
Import-Module "sqlps" -DisableNameChecking
$body +=echo "--------Status of mirrored databases---------"`r`n""`r`n""
foreach ($server in $sqlservers){
$body +=echo "Database mirroring state on $server
"
$body += Invoke-Sqlcmd -Query "USE master
SELECT sys.database_mirroring.mirroring_state_desc
,sys.databases.name
FROM sys.database_mirroring INNER JOIN sys.databases ON sys.database_mirroring.database_id=sys.databases.database_id
WHERE mirroring_state_desc IS NOT NULL" -ServerInstance "$server" | out-string
}
When I run this code, I get the following 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 C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At C:\Users\ctxadmin\Desktop\SQL.ps1:20 char:11
+ $body += Invoke-Sqlcmd -Query "USE master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
My SQL server is a STANDARD database. It has no mirror. Is that the issue?
What might the error be?

Related

Invoke-Sqlcmd error in Loop, No error once?

If I run this .ps1 script-
$secID = Invoke-Sqlcmd -ServerInstance "MyDBServer" -Database "MyDataBase"-Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host "MyDataBase"
Write-Host $secID.SysID
I get the following on the console with no error -
MyDataBase
18
However if I try this same query in a for loop in a larger script -
$dbservers = #('DataBaseServer1', 'DataBaseServer2')
foreach ($dbserver in $dbservers)
{
$databases = Get-SqlDatabase -ServerInstance $dbserver | Where-Object { $_.Name -Match '\d{3,4}' -and $_.Name -notlike '*test*'}
foreach ($database in $databases)
{
$secID = Invoke-Sqlcmd -ServerInstance $dbserver.Name -Database $database.Name -Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host $database.Name
Write-Host $secID.SysID
}
}
I get the correct query result but errors preceding it on the console -
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 \SQL.ps1:28 char:13
+ ... $secID = Invoke-Sqlcmd -ConnectionString $ConnectionString -Query ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At \SQL.ps1:28 char:13
+ ... $secID = Invoke-Sqlcmd -ConnectionString $ConnectionString -Query ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand*
MyDataBase
18
Why do I get errors when running it in the loop versus running it one time? Also why does the query work even though I get an error? I think I am missing something any help would be greatly appreciated!
I think its because you are calling property Name on a String, effectively returning nothing. try this (I just deleted the calling of the property $dbserver.Nameto $dbserver):
$dbservers = #('DataBaseServer1', 'DataBaseServer2')
foreach ($dbserver in $dbservers)
{
$databases = Get-SqlDatabase -ServerInstance $dbserver | Where-Object { $_.Name -Match '\d{3,4}' -and $_.Name -notlike '*test*'}
foreach ($database in $databases)
{
$secID = Invoke-Sqlcmd -ServerInstance $dbserver -Database $database.Name -Query "SELECT SysID FROM dbo.SecurityLevels WHERE LEVELNAME LIKE '%User%';"
Write-Host $database.Name
Write-Host $secID.SysID
}
}
The error must be because its looking for a DB instance "" and it doesn't find it, and the query might still go though because the the first server might not have an instance, or because those values were already loaded into the properties from before. But I'm just speculating, haven't really used this cmdlets.
PS: if you want to avoid calling empty properties add Set-StrictMode -Version 2 to your script, example:
PS > $text = "This is just a string"
PS > $text.AnyProperty
PS > Set-StrictMode -Version 2
PS > $text.AnyProperty
The property 'AnyProperty' cannot be found on this object. Verify that the property exists.
At line:1 char:1
+ $text.AnyProperty
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
Hope it helps.

Database Back Up using Powershell

I am trtying to take back up using poweshell
Below is the command which we are trying to execute,
Backup-SqlDatabase -ServerInstance "SERVER\DEFAULT" -Database "AFC" -BackupFile "\\REMOTESERVER\temp123\$dbName.bak"
However when we are trying to execute the same we are getting below error
Backup-SqlDatabase : Failed to connect to server 10.254.5.37\DEFAULT.
At line:1 char:1
+ Backup-SqlDatabase -ServerInstance "10.254.5.37\DEFAULT" -Database "A ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Backup-SqlDatabase], ConnectionFailureException
+ FullyQualifiedErrorId : Microsoft.SqlServer.Management.Common.ConnectionFailureException,Microsoft.SqlServer.Man
agement.PowerShell.BackupSqlDatabaseCommand
However when we are trying to execute Get-ChildItem command we are gettting names of all databases.
Please help us.
Regards,
Pradeep

Get-SqlInstance connection failure

Test-Connection reaches the server successfully. What might be the root cause of:
>Get-SqlInstance -ServerInstance 'DEVSQL02'
Get-SqlInstance : Failed to connect to server DEVSQL02.
At line:1 char:1
+ Get-SqlInstance -ServerInstance 'DEVSQL02'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DEVSQL02:String) [Get-SqlInstance], ConnectionFailureException
+ FullyQualifiedErrorId : ConnectionToServerFailed,Microsoft.SqlServer.Management.PowerShell.GetSqlInstanceCommand
From help Get-SqlInstance.
SYNTAX
Get-SqlInstance [[-Credential] <PSCredential>] [-ConnectionTimeout <Int32>] [-Script] [-ServerInstance <String[]>] [-Confirm] [-WhatIf] [<CommonParameters>]
Must PowerShell Remoting be enabled? Is port 1433 involved?
Using PowerShell 5.1.14409.1018 on Windows 7 Professional.
SqlServer module 21.1.18068.

SQL Server PowerShell error Get-ChildItem

I try to get backup from SQL databases with this PowerShell code:
Set-Location "SQLSERVER:\SQL\computer\distance\Databases"
foreach ($database in (Get-ChildItem)) {
$dbName = $database.Name
Backup-SqlDatabase -Database $dbName -BackupFile "E:\bu\$dbName"
}
In a virtual server it works.
When I go to SQLSERVER:\SQL\computer\distance\Databases location and take ls
it show my databases and sucessfully takes backups.
But in another server in my workplace it gives this error:
Get-ChildItem : SQL Server PowerShell provider error: Failed to read child items.
[Failed to connect to server computer\instance. --> Login failed for user
'work\sql'.]
At line:1 char:23
+ ForEach($database in (Get-ChildItem))
+ ~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (SQLSERVER:\SQL\...\instance\Databases:SqlPath) [Get-ChildItem], GenericProviderException
+ FullyQualifiedErrorId : CannotReadChildItems,Microsoft.PowerShell.Commands.GetChildItemCommand
and when in SQLSERVER:\SQL\computer\distance\Databases directory I do ls it gives this error:
ls : SQL Server PowerShell provider error: Failed to read child items. [Failed to
connect to server computer\instance. --> Login failed for user 'work\sql'.]
At line:1 char:1
+ ls
+ ~~
+ CategoryInfo : ReadError: (SQLSERVER:\SQL\...\instance\Databases:SqlPath) [Get-ChildItem], GenericProviderException
+ FullyQualifiedErrorId : CannotReadChildItems,Microsoft.PowerShell.Commands.GetChildItemCommand
computer\instance: I changed for this example.

Exception calling ".ctor" with "2" argument(s): "SetParent failed for Database 'XXX' ."

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?
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

Resources