c# - 带换行符的查询无法在 PowerShell 中执行

标签 c# sql-server powershell

我正在使用 Microsoft.SqlServer.Management.SMO 程序集在 PowerShell 中自动执行一些数据库任务。由于某种原因,执行带有换行符的查询似乎不起作用。但是,我还在 C# 中重现了完全相同的任务,它确实有效。我不确定是否存在我一直忽略的细微差异,或者在 PowerShell 中读取文件时是否存在一些奇怪的差异导致我出现问题。以下是复制所需的所有信息:

SQL 脚本 (test.sql):

select
* from INFORMATION_SCHEMA.TABLES

PowerShell(工作):

Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll'

$server = New-Object Microsoft.SqlServer.Management.SMO.Server('serverName')
$database = New-Object Microsoft.SqlServer.Management.SMO.Database($server, 'myDatabase')
$setupScript = Get-Content "$PSScriptRoot\scripts\test.sql"
$database.ExecuteNonQuery($setupScript)

这是 PowerShell 给出的错误消息:

Exception calling "ExecuteNonQuery" with "1" argument(s): "ExecuteNonQuery failed for Database 'Salesforce-Neptune'. " ---> Microsoft.SqlServer.Management.Smo.FailedOperationException: ExecuteNonQuery failed for Database 'Salesforce-Neptune'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Incorrect syntax near 'select'.

C#(可以工作):

var server = new Server("serverName");
var sql = System.IO.File.ReadAllText(@"D:\code\test.sql");
var database = new Database(server, "myDatabase");
database.ExecuteNonQuery(sql);

如果我编辑我的 test.sql 文件并将整个查询放在一行中,那么我的 PowerShell 脚本就可以运行。怎么回事?

最佳答案

or if there's some odd difference with reading a file in PowerShell that is causing me an issue

我相信这是因为 Get-Content 默认情况下将文件读取为行数组(就像 C# IIRC 中的 ReadAllLines() 一样)。

从 V3 开始,您可以使用 -Raw 开关来禁用此行为,对于 V2,您必须使用 [IO.File]::ReadAllText("file\path")

关于c# - 带换行符的查询无法在 PowerShell 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355977/

相关文章:

c# - Xamarin Studio Android 应用程序 "aapt.exe"退出,代码为 -1073741819 错误 MSB6006 :

c# - 当两者相同,未知,类型时,您可以将一个结构复制到另一个吗

c# - 如何从对象列表创建 MVC HtmlHelper 表

c# - 我可以使用 Sync Framework 同步移动、桌面和 Web 服务器数据库吗?

sql-server - SQL Server 全文搜索转义字符?

powershell - 防止在 Powershell 脚本中多次写入输出

c# - 从数据库加载 PictureBox 图像

sql-server - 从字符串转换为 uniqueidentifier 时转换失败 - 两个 GUID

javac 响应 "not a file"但文件存在

powershell - 简洁地传递函数作为参数