如何在Powershell中将模板与CSV文件组合在一起

时间:2017-02-14 15:41:04

标签: powershell

我想要组合一个如下所示的模板:

grant $privs 
   on $table 
   to $user;

使用如下所示的CSV文件:

privs,table,user
ALL,Employees,DBA
READ,Employees,Analyst
"READ, WRITE", Employees, Application
ALL,Departments,DBA
READ,Departments,"Analyst, Application"

生成如下所示的SQL脚本:

grant ALL 
   on Employees 
   to DBA;

grant READ 
   on Employees 
   to Analyst;

grant READ, WRITE 
   on Employees 
   to Application;

grant ALL 
   on Departments 
   to DBA;

grant READ 
   on Departments 
   to Analyst, Application;

模板有三个参数,看起来像Powershell变量。 CSV文件有足够的数据 指定模板的五个副本。在现实生活中,它将更像200份。

我还希望能够将相同的技术应用于各种CSV文件,其中大部分都是如此 不要来自数据库。我想使用各种模板,其中大部分都没有 生成SQL。出于这个原因,我想要一种处理纯文本文件的技术 附加到数据库。

注意:我在问这个问题,以便为社区提供答案。

1 个答案:

答案 0 :(得分:1)

我写了一个函数,Expand-Csv,这样做。这是:

        string sqlInsertStmt = "INSERT INTO PRODUCT (id,name,price) VALUES (@id, @name, @price)";
        string connectionString = "sqlserver connection string";

        //sample connection string can be like
        //connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=False;User Id=userid;Password=password;MultipleActiveResultSets=True";

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            foreach (var product in CSVProducts)
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sqlInsertStmt;
                    cmd.Parameters.AddWithValue("@id", product.Id);
                    cmd.Parameters.AddWithValue("@name", product.Name);
                    cmd.Parameters.AddWithValue("@val", product.Price);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch(SqlException e)
                    {
                        //log exception and handle error
                    }
                }
            }
        }

在手头的情况下,电话会是这样的:

<#  This function is a table driven template tool. 

    It generates output from a template and
    a driver table.  The template file contains plain
    text and embedded variables.  The driver table 
    (in a csv file) has one column for each variable, 
    and one row for each expansion to be generated.

    12/12/2016

#>

function Expand-csv {
   [CmdletBinding()]
   Param(
      [Parameter(Mandatory=$true)]
      [string] $driver,
      [Parameter(Mandatory=$true)]
      [string] $template
   )
   Process
   {
      $pattern = (Get-Content $template) -join "`n"

      Import-Csv $driver | % {
         foreach ($p in $_.psobject.properties) {
            Set-variable -name $p.name -value $p.value
            }
         $ExecutionContext.InvokeCommand.ExpandString($pattern) 
      }
   }
}

将进入控制台的输出重定向到文件。

我尝试过使用它在Powershell中生成脚本, 但要谨慎一点。 ExpandString做了一些相同的处理 Invoke-Command会这样做,所以你可能会得到不良后果。我只用它 对于最简单的PS代码,比如对一些外部应用程序的一系列调用。