使用控制台应用程序通过PowerShell执行SQL脚本文件

时间:2014-07-18 13:26:33

标签: c# asp.net sql powershell connection-string

我想使用powershell文件脚本和控制台应用程序执行3个SQL文件。

我的控制台应用程序运行正常" powershell脚本"但我的问题是我应该在我的脚本(dbscript.ps1)中编写自动执行我的SQL文件。我已经看过几个例子,但不适合我的情况。

我有一个ASP.NET解决方案,我在解决方案项目中有3个SQL文件(没有子文件夹/没有子项目)。此外,我有一个项目,其中包含用于执行我的ps1文件的控制台应用程序。

我真正需要的是:

a)我在app.config中有连接字符串,可用于连接到我的本地数据库

b)我需要在dbscript.pb1中使用该连接字符串,然后我需要执行我的SQL文件(s1.sqls2.sqls3.sql位于在我的解决方案中)

我见过这个例子:

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "" // Here I should take my connection string from app.config
$conn.Open()
$sql = "" // Somehow I should take all my sql files (I don't know how to get the path for them)
 $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
$rdr = $cmd.ExecuteReader()
$test = @()
while($rdr.Read())
{
    $test += ($rdr["EMP_STATUS"].ToString())
}
Write-Output $test

那么,如何可以从app.config获取连接字符串,如何设置所有sql文件以特定顺序执行?< / p>

1 个答案:

答案 0 :(得分:4)

不是你要问的问题,但我会这样做,因为当你已经编写了一个可以为你做这个的应用程序时,处理powershell似乎更令人头痛。

//get application path and script directory
private const string scriptPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Scripts");

private void RunScripts()
{
    string[] scripts = Directory.GetFiles(scriptPath, "*.sql", SearchOption.TopDirectoryOnly);
    //name them script01.sql, script02.sql ...etc so they sort correctly
    Array.Sort(scripts);

    if (scripts.Length > 0)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionStringKey"]))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                foreach (string script in scripts)
                {
                    cmd.CommandText = File.ReadAllText(script);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}