2017-10-19 63 views
0

我寫了一個動態的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 : 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

我的目的是運行上面的代碼與作業類型爲「的CmdExec」一個SQL Server代理作業

我在PowerShell和couldn初學者不知道如何解決上述錯誤。

從Powershell ISE窗口執行PowerShell代碼工作得很好。 -

任何幫助表示讚賞。

回答

1

通過在雙引號雙引號的命令被分爲三個部分

  1. 「$ d分割=獲取最新的;獲取-childItem 「
  2. C:\ ServerManagement \日誌\ SQL Server代理
  3. 」 -recurse -include * .LOG |凡{($ _ lastwritetime -le $ d.Addhours(-120))} |刪除-Item -Force「

Powershell的嘗試翻譯爲這個使用位置參數翻譯:

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

有多種方式,以避免這一點:

  1. 使用不同的報價像你這樣

    「'字符串'「

  2. 轉義內部雙引號

    「\」 字符串\ 「」

  3. 使用腳本塊,而不是引號來封裝PowerShell的部分

    powershell.exe -command { 「字符串」}

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" 
+0

(產地評論在回答能夠顯示代碼) –

1

您的整個參數用雙引號括起來。那麼你不能用雙引號包裝它的一部分,你需要單引號。或者你也可以使用回剔`轉義雙引號:

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" 
相關問題