【问题标题】:Sqlcmd : invalid argument path string PowershellSqlcmd:无效的参数路径字符串Powershell
【发布时间】:2022-01-18 16:33:12
【问题描述】:

我尝试了很多解决方案,但我无法解决我的问题。

我想执行这个 PowerShell 命令:

sqlcmd -S localhost\SQLEXPRESS -U sa -P mypassword 
       -v db="school" bakfile="C:\Users\xal\Documents\backup.bak" -i restore.sql

但我得到一个错误:

Sqlcmd:« :\Users\xal\Documents\backup.bak »:无效参数。

如您所见,路径参数bakfile 被截断。我不知道为什么。

这是我想用变量执行的 SQL 脚本:

USE MASTER

RESTORE DATABASE $(db)
FROM DISK = $(bakfile)
WITH REPLACE;

【问题讨论】:

  • 除了在没有续行的情况下分布在两行之外(我假设您这样做是为了便于阅读),您的命令行没有明显的问题;因此,需要更多信息来诊断问题。

标签: powershell parameters arguments sqlcmd


【解决方案1】:

我无法解决这个问题,所以我创建了一个 C# 可执行文件来做同样的事情。

我发现我们可以使用SqlCommand 来实现同样的目的:

conn = new SqlConnection($"Data Source ={server};Initial Catalog={dbname};" +
    $ "Persist Security Info=True;User ID={id};Password={password}");

conn.Open();

SqlCommand cmd = new SqlCommand($"USE MASTER RESTORE DATABASE {dbname} FROM DISK = '{bakPath}' WITH REPLACE;", conn);
cmd.ExecuteNonQuery();
conn.Close();

这是我的 .exe 的代码:

static void Main(string[] args) {
  string server;
  string dbname;
  string id;
  string password;
  string bakPath;

  SqlConnection conn;

  if (args.Length > 0) {
    server = args[0];
    dbname = args[1];
    id = args[2];
    password = args[3];
    bakPath = args[4];
    try {
      Console.WriteLine("#--------------------------------------------------#");
      Console.WriteLine("server=" + server);
      Console.WriteLine("dbname=" + dbname);
      Console.WriteLine("id=" + id);
      Console.WriteLine("password=" + password);
      Console.WriteLine("bakfile=" + bakPath);
      Console.WriteLine("#--------------------------------------------------#");
      Console.WriteLine("Processing restoration...");
      conn =
        new SqlConnection($"Data Source ={server};Initial Catalog={dbname};" +
          $ "Persist Security Info=True;User ID={id};Password={password}");

      conn.Open();

      SqlCommand cmd = new SqlCommand($"USE MASTER RESTORE DATABASE {dbname} FROM DISK = '{bakPath}' WITH REPLACE;", conn);
      cmd.ExecuteNonQuery();
      conn.Close();
      Console.ForegroundColor = ConsoleColor.Green;
      Console.WriteLine("Restoration done !");
      Console.ForegroundColor = ConsoleColor.White;
    } catch (Exception ex) {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine("Error :" + ex.Message);
      Console.ForegroundColor = ConsoleColor.White;
    }

  } else {
    Console.WriteLine("You need to pass the arguments required")
  }

}

我现在可以运行带有参数的 .exe。

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2011-06-23
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多