【问题标题】:How can I format my string in SQL so that it is interpreted properly in Powershell?如何在 SQL 中格式化我的字符串,以便在 Powershell 中正确解释它?
【发布时间】:2017-06-07 20:58:58
【问题描述】:

我目前正在编写一个我想从 SSMS 运行的简单 SQL 脚本。该脚本应该做的是获取一个数据库,对其进行备份,然后将该备份制作为 .zip 文件。

我遇到的问题是尝试压缩备份时。我在文件开头声明了所有变量,并且我相信当我尝试执行 @sqlcmd 时,Powershell 没有正确读取该字符串。

    SET @sqlcmd = ('powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("' + @bkpath + '", "C:\'+ @fileName + '.zip")')
    PRINT @sqlcmd 
    -- this statement returns (powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip"))
    EXEC xp_cmdshell @sqlcmd   

运行此代码会在我的结果窗口中返回以下输出:

At line:1 char:47
+ [IO.Compression.ZipFile]::CreateFromDirectory(C:\Backup", C:\Scriptin ...
+                                               ~
Missing ')' in method call.
At line:1 char:56
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
At line:1 char:47
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'C:\Backup", C:\ScriptingTestDB_20170607.zip)' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
NULL

经过一些测试,我想我发现问题在于 Powershell 如何解释 SQL 字符串。由于有很多引号,即使 SQL 正确打印出字符串,当 Powershell 得到它时,格式也会变得混乱,因此需要在那里更改某些内容,但仍然不确定是什么。有谁知道我可以用来找出如何编写 SQL 代码以便 Powershell 读取以下内容的任何准则:

[IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip")

【问题讨论】:

  • xp_cmdshell 是一个命令提示符,它采用第一个引号,所有需要进入 PowerShell 的代码都需要从 cmd 解释器中转义。您需要它是 `powershell "[io..]::('c:\...', '...')"`` 其中为 cmd 解释器引用 PS 脚本,并且路径是单一的引用所以他们不会破坏双引号。因此,请转义 SQL 字符串中的单引号。然后修复您的 Add-Type 不会从一个进程延续到下一个进程的方式。这种事情就是为什么 powershell.exe 接受 BASE64 编码的命令,顺便说一句。

标签: sql powershell ssms-2016


【解决方案1】:

您需要使用\ 转义"-characters。我的工作脚本:

declare @sqlcmd varchar(1000), @bkpath nvarchar(max) = 'C:\i1\tmp', @filename nvarchar(max) = 'file'

SET @sqlcmd = 'powershell.exe Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::CreateFromDirectory(\"' + @bkpath + '\", \"C:\i1\'+ @fileName + '.zip\")'
EXEC xp_cmdshell @sqlcmd   

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 2014-09-22
    • 2018-02-18
    • 2019-08-21
    • 2014-10-12
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多