2013-04-09 94 views
0

使用Powershell,我執行一個SQL腳本,該腳本返回SQL Server Management Studio選項卡「消息」中生成的腳本。但是我無法在PowerShell中獲得它。如何在PowerShell中獲取SQL Server Management Studio選項卡消息?

當我這樣做:

$ps = [PowerShell]::Create() 
[ref]$e = New-Object System.Management.Automation.Runspaces.PSSnapInException 
$ps.Runspace.RunspaceConfiguration.AddPSSnapIn("SqlServerCmdletSnapin100", $e) | Out-Null 
$ps.AddCommand("Invoke-Sqlcmd").AddParameter("ServerInstance", "localhost").AddParameter("Database", "MyDatabase").AddParameter("InputFile", "D:\MyScript.sql").AddParameter("Verbose") 
$ps.Invoke() 
$ps.Streams 
$ps.Streams.Verbose | % { $_.Message | Out-File -Append D:\SqlLog.txt } 

我得到這個錯誤:

PS D:\NEMO\Scripts\Database> $ps.Invoke() 
Exception calling "Invoke" with "0" argument(s): "Object reference not set to an instance of an object." 
At line:1 char:11 
+ $ps.Invoke <<<<() 
    + CategoryInfo   : NotSpecified: (:) [], ParentContainsErrorRecordException 
    + FullyQualifiedErrorId : DotNetMethodException 

謝謝您的幫助。

回答

1

因此,使Powershell輸出消息並不那麼簡單,它只適用於我認爲的命令行。試試這個

write-host $line 
    Start-Transcript $outputfilepath 
    $ScriptParams = "DatabaseName=$line" " 
    Invoke-Sqlcmd -ServerInstance $SQLInstance -Username $SQLAdminUser -Password $SQLAdminPwd -InputFile "D:\File.sql" -verbose -Variable $ScriptParams 
    Stop-Transcript 
相關問題