I wrote a dynamic SQL to build the below query and execute it using xp_cmdshell in SQL Server
POWERSHELL -command "$d = Get-Date Get-childItem "c:\ServerManagement\Logs\SQL Server Agent" -recurse -include *.log | Where {($_.lastwritetime -le $d.Addhours(-120))} | Remove-Item -Force"
but when I run it on the command prompt, I get this error:
Get-ChildItem : A positional parameter cannot be found that accepts argument 'Agent'.
At line:1 char:19
+ ... = Get-Date; Get-childItem c:\ServerManagement\Logs\SQL Server Agent - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
My intention is to run the above code as a SQL Server Agent job with the job type as "CMDEXEC"
I am a beginner at PowerShell and couldn't figure out how to troubleshoot the above error.
Executing the PowerShell code from the Powershell ISE window works just fine. -
Any help is appreciated.