Server Agent PowerShell作业步骤-调用文件和调用命令的区别

Server Agent PowerShell job step - Difference between calling a file and calling a command

我有一些简单的 PowerShell 代码可以将值插入 table:

Invoke-SqlCmd -ServerInstance myserver -Query 'insert into Database.dbo.tbl values (1)'

如果我将它保存为文件,我可以在 CmdExec 作业步骤中调用它。但是,谁能告诉我为什么我不能 运行 命令,尤其是因为它只有一行:

powershell.exe -ExecutionPolicy Bypass -Command 'Invoke-Sqlcmd -ServerInstance myserver -Query ''insert into DBADatabase.dbo.tbl values (1)'''

谁能告诉我为什么 运行ning 作为命令不起作用,但作为文件的相同代码却可以工作。任何帮助表示赞赏。

谢谢

我已经使用下面的 powershell 代码在我的服务器上创建了测试作业并且它可以工作。下图有我的工作细节。

我的测试代码

Invoke-Sqlcmd -ServerInstance 'MYSERVER' -Query 'insert into DBA_TOOLS.dbo.tbl values (1)'

您的代码 - 您在 sql 服务器周围缺少单引号 'myserver'。

Invoke-Sqlcmd -ServerInstance 'myserver' -Query ''insert into DBADatabase.dbo.tbl values (1)'

希望这对您有所帮助

您的 powershell.exe ... 命令是从 外部 PowerShell 执行的,可能是通过 cmd.exe.

在那种情况下,'...'-封闭的字符串没有语法功能,直接传递给 PowerShell,导致 it 将它们解释为包含 字符串文字 ,这只是 输出 as-is (换句话说:您的命令是 打印而不是执行).

相反,您必须使用 "..." 将要传递给 PowerShell 的命令括起来;在该字符串中,您可以自由使用 '...':

powershell.exe -ExecutionPolicy Bypass -Command "Invoke-Sqlcmd -ServerInstance myserver -Query 'insert into DBADatabase.dbo.tbl values (1)'"