您好我正在尝试编写一个powershell脚本来在Windows7终极机器上创建mdf文件(sqlserver数据库文件)的备份
但是当我运行我的脚本时它会显示错误:
New-Object : Cannot find type [Microsoft.SqlServer.Management.Smo.Backup]: make sure the assembly
is loaded.
At C:\Users\abc\tmp.ps1:5 char:23
+ $dbBackup = new-object <<<< ("Microsoft.SqlServer.Management.Smo.Backup")
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
Property 'Database' cannot be found on this object; make sure it exists and is settable.
At C:\Users\abc\tmp.ps1:8 char:11
+ $dbBackup. <<<< Database = "ds"
+ CategoryInfo : InvalidOperation: (Database:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\Users\abc\tmp.ps1:11 char:28
+ $dbBackup.Devices.AddDevice <<<< ("D:\backups\BLACKSWASTIK.bak", "File")
+ CategoryInfo : InvalidOperation: (AddDevice:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Property 'Action' cannot be found on this object; make sure it exists and is settable.
At C:\Users\abc\tmp.ps1:14 char:11
+ $dbBackup. <<<< Action="Database"
+ CategoryInfo : InvalidOperation: (Action:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\Users\abc\tmp.ps1:17 char:20
+ $dbBackup.SqlBackup <<<< ($s)
+ CategoryInfo : InvalidOperation: (SqlBackup:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
这是我的代码:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "localhost\sqlexpress2008"
$dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
#Set the Database property to Northwind
$dbBackup.Database = "bs"
#Add the backup file to the Devices collection and specify File as the backup type
$dbBackup.Devices.AddDevice("D:\backups\BLACKSWASTIK.bak", "File")
#Specify the Action property to generate a FULL backup
$dbBackup.Action="Database"
#Call the SqlBackup method to generate the backup
$dbBackup.SqlBackup($s)
此代码在xp机器上工作正常,但我想在windows7终极机器上运行它有什么需要改变吗?请建议......
答案 0 :(得分:0)
在运行SQL Server Powershell时查看this article from MSDN。它为您提供了先决条件以及一个很好的脚本,您可以运行加载所有必需的程序集和命名空间。然后,您可以将其DotSource到您的脚本中,以便您访问SMO。
对于我的环境,我使用了这个脚本,稍微调整了一下,并创建了一个PowerShell module,以便将代码放入我的脚本中更容易。
答案 1 :(得分:0)