我的powershell语法出现问题,需要进行清理



我正在使用以下PowerShell代码删除数据库服务器路径中的日志

powershell.exe -command & {
get-childitem -path "$(ESCAPE_SQUOTE(D:Microsoft SQL ServerMSSQL11.MSSQLSERVERMSSQLLog))"  -filter *_*_*_*.txt |
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | remove-item -verbose
}

它的错误如下所示

At line:1 char:25
+ powershell.exe -command & {get-childitem -path "$(ESCAPE_SQUOTE(D:Microsoft SQL ...
+                         ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double
quotation marks ("&") to pass it as part of a string.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmpersandNotAllowed

我是PowerShell的新手,认为将""添加到"&"就足够了,但它再次出错

powershell.exe : ScriptBlock should only be specified as a value of the Command parameter.
At line:1 char:1
+ powershell.exe -command "&" {get-childitem -path "$(ESCAPE_SQUOTE(D:Microsoft S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [], ParameterBindingException
+ FullyQualifiedErrorId : IncorrectValueForCommandParameter

""添加到路径中,但对没有帮助

powershell.exe -command & {get-childitem -path "$(ESCAPE_SQUOTE("D:Microsoft SQL ServerMSSQL11.MSSQLSERVERMSSQLLog"))"  -filter *_*_*_*.txt | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | remove-item -verbose}

我需要在操作系统命令exec 下从SQL代理作业调用它

有人能帮我语法吗

问候和祝福埃本

将命令传递到PowerShell CLI的-Command/-c参数时:

  • 如果从PowerShell外部的调用,请完全省略& { ... },只需指定...-永远不需要& { ... },只会产生开销。

    • 此外,如果您从cmd.exe调用(您不是(,则最安全的做法是双引号...("..."(,并将嵌入的双引转义为"(原文如此(
  • PowerShell内部的中,省略&(您确实需要{ ... }来稳健地传递命令,但这种方法仅在从PowerShell内部调用时有效(:

    • 您的错误消息表明powershell.exe确实是从PowerShell会话调用的
    • 然而,问题是既然您已经处于PowerShell会话中,为什么要调用另一个PowerShell实例作为子进程,您可以直接执行{ ... }中的语句

鉴于您的症状,我想知道您的案例中的exec命令是否真的已经使用PowerShell而不是cmd.exe作为外壳,在这种情况下,只在{ ... }中传递问题中的文本就足够了。

最新更新