找不到接受参数的位置参数

时间:2017-10-19 10:45:38

标签: sql-server powershell

我编写了一个动态SQL来构建以下查询,并使用SQL Server中的xp_cmdshell执行它

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"

但是当我在命令提示符下运行它时,我收到此错误:

  

Get-ChildItem:找不到接受参数' Agent'的位置参数。   在行:1 char:19
  + ... =获取日期; Get-childItem c:\ ServerManagement \ Logs \ SQL Server Agent - ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
  + CategoryInfo:InvalidArgument:(:) [Get-ChildItem],ParameterBindingException
  + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

我的目的是将上述代码作为SQL Server代理作业运行,作业类型为" CMDEXEC"

我是PowerShell的初学者,无法弄清楚如何解决上述错误。

从Powershell ISE窗口执行PowerShell代码就可以了。 -

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

你的整个论点都用双引号括起来。然后你不能用双引号将它的部分包装起来,你需要单引号。或者你可以使用back-tick`:

来逃避双引号
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"

答案 1 :(得分:1)

通过双引号中的双引号,您的命令分为三部分

  1. " $ d =获取日期; Get-childItem"
  2. c:\ ServerManagement \ Logs \ SQL Server Agent
  3. " -recurse -include * .log |其中{($ _。lastwritetime -le $ d.Addhours(-120))} | Remove-Item -Force"
  4. Powershell尝试使用位置参数将其转换为:

    Get-ChildItem -Path C:\ServerManagement\Logs\SQL -Filter Server Agent
    

    有多种方法可以避免这种情况:

    1. 使用与您不同的引号

      "'字符串'"

    2. 转义内部双引号

      " \"字符串\""

    3. 使用Scriptblock而不是引号来封装Powershell部分

      powershell.exe -command {" String"}

答案 2 :(得分:0)

我通过反复试验弄明白了。我用单引号替换双引号,代码开始工作,我不知道为什么。

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"