当我在SQL Server Management Studio中运行BACKUP DATABASE landofbeds TO DISK = 'c:\temp\backups\lob_backup.bak'
时,它会创建一个备份并正常工作。
我想创建一个执行此操作的PowerShell脚本,以便我写完:
$Server = 'localhost'
$Database = '<DbName>'
$Filepath = 'c:\temp\backups\lob_backup.bak'
$Query = "BACKUP DATABASE '$Database' TO DISK = '$Filepath'"
Invoke-Sqlcmd -ServerInstance $Server -Database $Database -Query $Query
尖括号中的任何内容(<>
)都是实际数据的占位符。
这会返回错误:
Invoke-Sqlcmd : Cannot open database "<DbName>" requested by the login. The login failed. Login failed for user '<ComputerName\Account>'. At line:6 char:1 + Invoke-Sqlcmd -ServerInstance $Server -Database $Database -Query $Que ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException + FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
答案 0 :(得分:0)
我遇到了相同的问题,但有相同的错误。 我知道登录有效,我必须自己使用正确的凭据登录到SSMS。
$thisSrvr = hostname
$cred_SQL = get-credential -userName "username" -message "Creds to Run the SQL Backup"
$SqlServer = (Get-SqlDatabase -Credential $cred_SQL -ServerInstance $thisSrvr).name
$date = get-date -UFormat "%Y%m%d"
$backups = "D:\"
Foreach ($db in $SQLServer){
$pw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cred_SQL.Password)) #converts SecureString PW to Plain Txt.
$ASver = (Invoke-SQLCmd -Query "getting app version info" -ServerInstance $thisSrvr -UserName $cred_SQL.UserName -Password $pw -Database $DB).version -replace "\.", "-"
$BAKFile = $db + "_ROLE_" + $ASVer + "_" + $date + ".bak"
$BAKStr = $backups + $BAKFile
Backup-SqlDatabase -Credential $cred_SQL -ServerInstance $thisSrvr -Database $db -BackupAction "Database" -BackupFile $BAKStr -CompressionOption "On" -Initialize | out-null
}
Clear-Variable pw -Scope Global
我不确定该去哪里查看SSMS中的日志信息,但是我可以自己搜索。 我唯一想到的原因可能是登录名对此数据库没有权限?但是我发现这很奇怪,因为这种登录是创建数据库的登录。