Invoke-Sqlcmd not working in SQL

筅森魡賤 提交于 2020-01-17 03:07:28

问题


Im using the following command in SQL Powershell to generate csv of data returned by SQL.

Invoke-Sqlcmd -Query "myp" -ServerInstance "." | Export-Csv -Path "d:\data\MyDatabaseSizes.csv" -NoTypeInformation

The above command works perfectly fine in SQL Power Shell. but when I tried to run in from SQL using the following code

DECLARE @cmd varchar(1000)
SET @cmd = 'Invoke-Sqlcmd -Query "myp" -ServerInstance "." | Export-Csv -Path "d:\data\MyDatabaseSizes.csv" -NoTypeInformation'
EXEC xp_cmdshell @cmd

it give error that

'Invoke-Sqlcmd' is not recognized as an internal or external command,

Anyone please help me in running the command from SQL.

Thanks


回答1:


xp_cmdmshell executes Windows shell commands, not PowerShell commands. You can of course call PowerShell from within the Windows shell, for example like this:

DECLARE @cmd varchar(1000)
SET @cmd = 'Invoke-Sqlcmd -Query ''myp'' -ServerInstance ''.'' ^| Export-Csv -Path ''d:\data\MyDatabaseSizes.csv'' -NoTypeInformation'
EXEC xp_cmdshell 'powershell.exe -c "' + @cmd + '"'

Note that:

  • I have replaced the double quotes in the PowerShell command with single quotes (escaped for SQL) so I can use double quotes in the Windows command. If you need double quotes in the PowerShell, you're better off having the PowerShell script in a file to avoid all this
  • You may also need more parameters (e.g. to set the execution policy). This MSDN page has more help on PowerShell command line switches
  • Pipe characters in command line arguments need to be escaped with ^


来源:https://stackoverflow.com/questions/38097340/invoke-sqlcmd-not-working-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!