Sql server 如何在PowerShell中获取SQL Server Management Studio选项卡消息?

Sql server 如何在PowerShell中获取SQL Server Management Studio选项卡消息?,sql-server,powershell,Sql Server,Powershell,使用Powershell,我执行一个SQL脚本,该脚本在SQLServerManagementStudio的“消息”选项卡中返回生成的脚本。但我在PowerShell里找不到 当我这样做时: $ps = [PowerShell]::Create() [ref]$e = New-Object System.Management.Automation.Runspaces.PSSnapInException $ps.Runspace.RunspaceConfiguration.AddPSSnapIn(

使用Powershell,我执行一个SQL脚本,该脚本在SQLServerManagementStudio的“消息”选项卡中返回生成的脚本。但我在PowerShell里找不到

当我这样做时:

$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
PS D:\NEMO\Scripts\Database>$PS.Invoke()
使用“0”参数调用“Invoke”时出现异常:“对象引用未设置为对象的实例。”
第1行字符:11

+$ps.Invoke所以让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