Cannot run `invoke-sqlcmd` and cannot import SQL Server? - sql-server

I'm trying to run Invoke-Sqlcmd on a computer and got the following error.
PS C:\> Invoke-Sqlcmd -server server1 'select 1 a'
Invoke-Sqlcmd : The 'Invoke-Sqlcmd' command was found in the module 'SqlServer', but the module could not be loaded.
For more information, run 'Import-Module SqlServer'.
At line:1 char:1
+ Invoke-Sqlcmd -server server1 'select 1 a'
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Invoke-Sqlcmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModule
However, Import-Module failed?
PS C:\> Import-Module SqlServer
Import-Module : The following error occurred while loading the extended type data file: Error in TypeData
"Microsoft.SqlServer.Management.Smo.Agent.Job": The member LastRunDuration is already present.
Error in TypeData "Microsoft.SqlServer.Management.Smo.Agent.JobStep": The member LastRunDurationAsTimeSpan is already present.
Error in TypeData "Microsoft.SqlServer.Management.Smo.NamedSmoObject": The member DefaultKeyPropertySet is already present.
Error in TypeData "Microsoft.SqlServer.Management.Smo.NamedSmoObject": The member DefaultDisplayPropertySet is already present.
Error in TypeData "Microsoft.SqlServer.Management.Smo.NamedSmoObject": The member DefaultDisplayProperty is already present.
At line:1 char:1
+ Import-Module SqlServer
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Import-Module], RuntimeException
+ FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Found out that Set-ExecutionPolicy -ExecutionPolicy RemoteSigned resolved the problem.

Related

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.

Trying to get the status of mirrored databases using powershell

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?

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