Problem accessing SQL Server from PowerShell - sql-server

I'm trying to implement a backup management script i found at http://sev17.com/2011/03/restore-and-relocate-database-files-using-powershell/
The article says it depends on SQLPSX version 2.3.2.1 or higher - I have the most current version.
attempting to execute this line:
$server = get-sqlserver $sqlserver
results in:
New-Object : Cannot find type [Microsoft.SqlServer.Management.Common.ServerConnection]: make sure the assembly containing this type is loaded.
At C:\Users\...\Documents\WindowsPowerShell\Modules\sqlserver\SQLServer.psm1:68 char:24
+ { $con = new-object <<<< ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver }
result of get-module -listAvailable
ModuleType Name ExportedCommands
---------- ---- ----------------
Script adoLib {}
Manifest Agent {Get-AgentTargetServerGroup, Get-AgentProxyAccount, Get-AgentJobSchedule...
Script ISECreamBasic {}
Script mySQLLib {}
Script OracleClient {}
Script OracleIse {}
Script PBM {}
Script PerfCounters {}
Manifest Pscx {}
Manifest Repl {Get-ReplEnumSubscriptions2, Get-ReplPublisherMonitor, Get-ReplEnumPubli...
Manifest ShowMbrs {Get-ShowMbrs, Set-ShowMbrs, New-ShowMbrs, Get-GroupUser}
Script SQLIse {}
Manifest SQLMaint {Get-SqlIndexFragmentation, New-UserMember, Invoke-SqlIndexRebuild, Get-...
Manifest SQLParser {Test-SqlScript, Out-SqlScript}
Script SQLProfiler {}
Script SQLPSX {}
Manifest sqlserver {Get-SqlScripter, Get-SqlIndexFragmentation, Remove-SqlServerRoleMember,...
Manifest SSIS {New-ISItem, Get-ISPackage, Get-ISItem, Copy-ISItemFileToSQL...}
Manifest WPK {}
Manifest AppLocker {}
Manifest BitsTransfer {}
Manifest PSDiagnostics {}
Manifest TroubleshootingPack {}
Manifest WebAdministration {}
RE: SMO
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
results:
True v2.0.50727 C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.ConnectionInfo\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.ConnectionInfo.dll
True v2.0.50727 C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Smo\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Smo.dll
True v2.0.50727 C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.SmoExtended\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.SmoExtended.dll
New-Object : Cannot find type [Microsoft.SqlServer.Management.Common.ServerConnection]: make sure the assembly containing this type is loaded.

Make sure the Assembly containing the Microsoft.SqlServer.Management.Common.ServerConnection type (which I think is Microsoft.SqlServer.ConnectionInfo) is loaded first:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")

For me works with
Import-Module -Name SqlServer
It could stay in script
NOTE:
Windows Server 2016
Before I have installed
Install-Module -Name SqlServer
With [Reflection.Assembly]::LoadWithPartialName works only on windows 10 for me.

I realize this is just about the worst answer ever but...
Seems like there might be something wrong with your SMO or something. You could try loading SP3 for SQL 2008 or just try re-installing SSMS 2008. Installing the 2008 R2 version of SSMS could be an option as well.
Again, not the greatest answer in the world but might be worth trying.

The powershell components are only installed if you have powershell 2.0 installed at the time of SSMS setup. Powershell is normally already setup on the machine unless you are using Windows Server 2008. Ensure that powershell 2.0 is installed before installing SSMS.

$sc = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
Error:
New-Object : Cannot find type [Microsoft.SqlServer.Management.Common.ServerConnection]: verify that the assembly containing this type is loaded
For this issue ,
Please Ensure micro soft sqlserver management object 2012(x64)is installed.
and go ahead check the dll files if present in given path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies"

Related

SQL Server LocalDB instance fails to be created/started on Windows 10 build 1809

We have a serious BUG reported by our clients,
regarding the WPF desktop application, which is connecting to the SQL Server 2014 Express LocalDB.
At the startup of the app, the app failed connect to the local DB.
Seems that our (CNogaMedicalLocalDB)local DB instance failed to auto start.
We manually got the local DB instance's info and we saw that the instance is in the "Stopped" state.
Usually the instance is auto start and the state should be "Running"
The local DB log didn't produced any valuable data.
In case we start the local DB manually using CMD the app works fine.
The app works fine on Windows 7, 8 and 10 except the last WIN 10 build 1809 (which is our clients platform)!
The app is being used heavily by many of our other clients around the world.
We cannot reproduce the issue in our Headquarters.
We tried to reproduce the issue on our QA platforms (Virtual Machines) running WIN-10 build 1809.
Apps Technical Details:
WPF.
EF Core version 7.0.0-rc1-final
SQL Server 2014 Express LocalDB version 12.0.2000.8.
Connection string:
data source=(LocalDb)\InstanceLocalDB; Initial Catalog = MyAppDB; Integrated Security=True; MultipleActiveResultSets=True; Connection Timeout = 10
The installation package is built with Advanced Installer version 12.3.1.
5.1. The SQL Server 2014 Express LocalDB is installed together with app and contained as a prerequisite within the installation package.
5.2. The SqlLocalDB Instance creation and starting is performed also during the application's installation via a custom action (PowerShell script which is runs at the final stage of the installation processes):
SqlLocalDB.exe create "SqlLocalDBInstance"
SqlLocalDB.exe start "SqlLocalDBInstance"
Thanks in advance.
Oleg Seider
R&D Department
CNOGA Medical Ltd.
Office: +972-4-6361080 ext.127
www.cnoga.com
According to a link posted by Nickolaj Anderson (who gives credit to a David Segura for getting to the root of this issue and wrote a blog post about it), this problem is caused by Windows 10 1809 lacking two dlls: BCP47Langs.dll and BCP47mrm.dll
The following PowerShell script is posted in the link (and here, just in case the link breaks!) to enable you to update your existing boot images that have already been reloaded from Windows ADK version 1809. It is advised that you make a backup before running the script, as I'm sure you would!
Instructions as given in Nickolaj's article:
Make sure that you have access to a Windows 10 version 1809 64-bit
ISO file and extract it’s content to a location in your site server.
Create the required folders for exporting and mounting:
C:\Temp\Mount\Source
C:\Temp\Mount\Current
C:\Temp\Export
Copy the boot.wim file from the extracted location of Windows 10
version 1809 64-bit to the C:\Temp\Export folder.
Update the $BootImagePath variable in the PowerShell script with the
local path to the boot.wim / winpe.wim found in the data source of your boot image
(remember to include the file name).
Execute the script
Script:
# Variables
$SourceMountPath = "C:\Temp\Mount\Source" # Create this folder
$BootImageMountPath = "C:\Temp\Mount\Current" # Create this folder
$SourceExportFolder = "C:\Temp\Export" # Create this folder
$SourceBootPath = "C:\Temp\Export\boot.wim" # boot.wim file copied to this location from the Windows 10 1809 x64 source media
$BootImagePath = "" # Local path to your boot.wim / winpe.wim file (not boot.PACKAGEID.wim) for your boot image in ConfigMgr
# Export winpe.wim from boot.wim from Windows 10 1809 source files
$ExportImagePath = Join-Path -Path $SourceExportFolder -ChildPath "winpe.wim"
Export-WindowsImage -SourceImagePath $SourceBootPath -DestinationImagePath $ExportImagePath -SourceIndex 1
# Mount exported WinPE image
Mount-WindowsImage -ImagePath $ExportImagePath -Index 1 -Path $SourceMountPath
# Mount boot image
Mount-WindowsImage -ImagePath $BootImagePath -Index 1 -Path $BootImageMountPath
# Copy BCP47*.dll's
$SourceFilePath = Join-Path -Path $SourceMountPath -ChildPath "Windows\System32\*"
$BootImageFilePath = Join-Path -Path $BootImageMountPath -ChildPath "Windows\System32"
Copy-Item -Path $SourceFilePath -Destination $BootImageFilePath -Filter "BCP47*.dll" -Force
# Dismount exported WinPE image
Dismount-WindowsImage -Path $SourceMountPath -Discard
# Dismount boot image
Dismount-WindowsImage -Path $BootImageMountPath -Save
Hope this works for you!
Rachel

System Variables in vNext release template

I have a vNext release template triggered by a TFS build with a component that is running a PowerShell script in a standard environment.
write-verbose "ApplicationPath = $($ApplicationPath)" -verbose
write-verbose "ApplicationPathRoot = $($ApplicationPathRoot)" -verbose
write-verbose "BuildDefinition = $($BuildDefinition)" -verbose
write-verbose "BuildDirectory = $($BuildDirectory)" -verbose
The script is displaying the system variables described in MSDN but two variables are not displayed (ApplicationPathRoot and BuildDirectory).
TFS and RM are version 12.0.31101.0 (Tfs2013.Update4)
Am I missing something or is a known problem?
It seems to be a bug; see Team Foundation Server - Build and release management forum discussion and related bug at Connect

PowerShell script result different when ran from Visual Studio

I'm running a PowerShell build script from the PostBuild event of a Visual Studio 2013 project.
The command I'm using for that is (new-lines added only for readability):
PowerShell -ExecutionPolicy ByPass -File "$(SolutionDir)..\build\build.ps1"
-SolutionFolder "$(SolutionDir)." -ProjectName "$(ProjectName)"
-OutputFolder "..\build\output" -ConfigurationName "$(ConfigurationName)"
One of the tasks of this script is to find local SQL Server instances to allow the user to attach required databases if they don't exist.
I'm using the following PowerShell code to retrieve the local instances:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null
$m = New-Object ("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") "."
if ($m.ServerInstances -eq $null -or $m.ServerInstances.Length -eq $null -or $m.ServerInstances.Length -eq 0)
{
throw New-Object [System.Exception] "No instances found."
}
$instances = $m.ServerInstances | % { ($_.Parent.Name + "\" + $_.Name) }
This is working perfectly fine when I execute the script from the command-line, but when I run the script from the PostBuild event $m.ServerInstances returns $null.
First thing that came to mind was user rights, but I checked which user is executing the script and it's the same in both command-line and VS PostBuild.
I've also tried a different approach that retrieves the available instances from the registry (as described here), with the same result; it works fine when running from command-line, but returns no instances when running from VS PostBuild.
So the question is, what's the difference between running from command-line and VS PostBuild that is causing this different behaviour?
UPDATE:
There are other parts of the script that stop functioning when running from Visual Studio.
For example creating an IIS website works fine when running the script from cmd.exe but throws an exception when ran from VS PostBuild:
Exception occurred while creating IIS site :
Retrieving the COM class factory for component with CLSID {688EEEE5-6A7E-422F-B2E1-6AF00DC944A6}
failed due to the following error :
80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
I've tried all kinds of crazy workaround, like using cmd.exe /C from VS PostBuild to execute PowerShell create a new PowerShell script that calls cmd.exe to run PowerShell.
All give the same result; the script works when called from a command prompt, but not when called from a Visual Studio PostBuild event.
Visual Studio itself is running with elevated permissions.
Also tried it without elevated permissions and that results in the same issue.
UPDATE 2:
The same problem occurs when I build the solution with MSBuild from a command prompt to trigger the PostBuild event that calls the script
It turns out that Visual Studio always executes the 32-bit PowerShell instead of the 64-bit.
Even when I specified the full path to PowerShell in the PostBuild event, it still executed the 32-bit version.
That caused a lot of the commands not to work.
I solved it by calling PowerShell with this command:
%WINDIR%\SysNative\WindowsPowerShell\v1.0\PowerShell.exe
That executes the 64-bit PowerShell on my machine and runs the script fine.
Building upon the accepted answer by Ruud van Falier, I had to use the following Prebuild event syntax so it ran on both my Dev machine AND on the Visual Studio Online Agent:
if exist %WINDIR%\SysNative\WindowsPowerShell\v1.0\PowerShell.exe (
rem BuildServer
%WINDIR%\SysNative\WindowsPowerShell\v1.0\PowerShell.exe $(SolutionDir)scripts\build\Prebuild.ps1
) else (
rem Dev workstation
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe $(SolutionDir)scripts\build\Prebuild.ps1
)
It's ugly, but it works.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

I am having trouble doing an import-module ActiveDirectory on a Server 2008 SP2 (64 bit).
NET Framework 3.5 SP1 is installed
I download the Windows6.0-KB968934-x86.msu (for ADWS)
This file did not install saying that "The update does not apply to my system"
Doing some research (http://anti-american.rssing.com/chan-2091246/all_p15.html) I installed hotfix in KB article 969166 and the above update installed.
After a reboot, I noticed that in services, Active Directory Web Services is running
I opened an administrative PS prompt and performed an Import-Module ActiveDirectory, but...
...I get:
Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory.
At line:1 char:14
+ import-module <<<< activedirectory
+ CategoryInfo : ResourceUnavailable: (activedirectory:String) [Import- Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
If its any help, here's some info in PSModule Path, modules and the version:
PS C:\Windows\system32> $env:PSModulePath
C:\Users\ischmd\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PS C:\Windows\system32> Get-Module -ListAvailable
ModuleType Name ExportedCommands
---------- ---- ----------------
Manifest BitsTransfer {}
Manifest PSDiagnostics {}
PS C:\Windows\system32> $PSVersionTable.psversion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
PS C:\Windows\system32> $host.version
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
Any help is greatly appreciated. The main purpose of this is to GET-AdUser command to automate some process but at this point, were stumped. My only conclusion is that this is not possible with Windows 2008 SP2...
AD Powershell module should be listed under installed Features. See image:
.
For non-servers this requires Remote Server Administration Tools for Windows __
Windows 7: http://www.microsoft.com/en-us/download/details.aspx?id=7887
Windows 8: http://www.microsoft.com/en-us/download/details.aspx?id=28972
Windows 10: https://www.microsoft.com/en-au/download/details.aspx?id=45520
The ActiveDirectory module for powershell can be installed by adding the RSAT-AD-Powershell feature.
In an elevated powershell window:
Add-WindowsFeature RSAT-AD-PowerShell
or
Enable-WindowsOptionalFeature -FeatureName ActiveDirectory-Powershell -Online -All
You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:
Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools
This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.
Even better use implicit remoting to use a module from another Machine!
$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM
This will allow you to use the module off a remote PC for as long as the PSSession is connected.
More Information:
https://technet.microsoft.com/en-us/library/ff720181.aspx
On Windows 10 - This happened for me after the latest update in 2020.
What solved this issue for me was running the following in PowerShell
C:\>Install-Module -Name MicrosoftPowerBIMgmt
This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the PSModulePath environment variable.
The default path should be %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
If you don't have the Active Directory module installed on your machine, you need to download the correct Remote Server Administration Tools (RSAT) package for your OS.
https://learn.microsoft.com/en-US/troubleshoot/windows-server/system-management-components/remote-server-administration-tools#rsat-for-windows-10-platform-and-tools-support-matrix
If you are running windows 10 you can download Remote Server Administration Tools for Windows 10 update from here https://www.microsoft.com/en-us/download/details.aspx?id=45520
Once installed run 'import-module ActiveDirectory' using elevated PowerShell.

SQL Azure and Powershell for DACPAC deploy

I am deploying a dacpac built on visual studio 2012 to SQL Azure using powershell and running into issues which I think could be related to some version incompatiblity. The publish works fine when I do it from visual studio but throws an exception when I do it using powershell.
Here is what I am doing in Powershell
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | out-null
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | out-null
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | out-null
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Management.Dac, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | out-null
Trap
{
PrintException($_.Exception);
$fileStream.Close()
return;
}
$sqlServerFullName = $sqlServerName + ".database.windows.net"
$serverConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection($sqlServerFullName, $adminLogin, $admingPwd)
$serverconnection.Connect()
$dacstore = New-Object Microsoft.SqlServer.Management.Dac.DacStore($serverConnection)
$fileStream = [System.IO.File]::Open($dacpacPath,[System.IO.FileMode]::OpenOrCreate)
Write-Host "Reading contents from $dacpacPath..."
$dacType = [Microsoft.SqlServer.Management.Dac.DacType]::Load($fileStream)
The last line in the code above is what is crashing with the following error (inner exception value) and not proceeding further
The stream cannot be read to construct the DacType.
There is an error in XML document (2, 2).
<DacType xmlns='http://schemas.microsoft.com/sqlserver/dac/Serialization/2012/0
2'> was not expected.
Here is the $PSVersionTable from powershell ISE that I am using
Name Value
---- -----
PSVersion 2.0
PSCompatibleVersions {1.0, 2.0}
BuildVersion 6.1.7601.17514
CLRVersion 4.0.30319.17929
WSManStackVersion 2.0
PSRemotingProtocolVersion 2.1
SerializationVersion 1.1.0.1
Wondering what could cause this issue when I deploy using Powershell when it works fine when I deploy it using visual studio 2012
P.S. - The powershell deploy works fine using the same script with a dacpac file that I found on the internet which was apparently targeted for a SQL 2005 version
If you installed latest SSDT 2015 (https://msdn.microsoft.com/en-us/mt186501). I highly recommended it because it has a lot of useful options for the Publish profile, which can be generated using Visual Studio.
You can use the following to publish your file to Azure using Powershell
$sqlpackage = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\120\sqlpackage.exe"
$dbserver = "<Azure DB Location>"
$database = "<name of DB on Server>"
# UNC Paths
$dbProfile = "<Path to your Publish Profile>"
$mydacpac = "<location of the dacpac>"
# Publish Command
& $sqlpackage /Action:Publish /tsn:$dbServer /tdn:$database /sf:$mydacpac/pr:$dbProfile /variables:myVariable=1
PS : & works like Invoke-Expression mentioned by Pradebban
Try publishing with sqlpackage.exe and Publish.xml
Invoke-Expression = "C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\sqlpackage.exe /Action:Publish /Sourcefile:<.dacpac file_path> /pr:'<Publish.xml>'"

Resources