Invoke-Sqlcmd not working in SQL -
im using following command in sql powershell generate csv of data returned sql.
invoke-sqlcmd -query "myp" -serverinstance "." | export-csv -path "d:\data\mydatabasesizes.csv" -notypeinformation
the above command works fine in sql power shell. when tried run in sql using 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' not recognized internal or external command,
anyone please me in running command sql.
thanks
xp_cmdmshell
executes windows shell commands, not powershell commands. can of course call powershell within windows shell, example 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 double quotes in powershell command single quotes (escaped sql) can use double quotes in windows command. if need double quotes in powershell, you're better off having powershell script in file avoid this
- you may need more parameters (e.g. set execution policy). this msdn page has more on powershell command line switches
- pipe characters in command line arguments need escaped
^
Comments
Post a Comment