【问题标题】:Issue with my powershell syntax to do an clean up我的 powershell 语法问题进行清理
【发布时间】:2021-08-26 15:23:44
【问题描述】:

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

powershell.exe -command & {
    get-childitem -path "$(ESCAPE_SQUOTE(D:\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Log\))"  -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 Server\MSSQL11.MSSQLSERVER\MSSQL\Log\"))"  -filter *_*_*_*.txt | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | remove-item -verbose}

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

谁能帮我看看语法

问候和祝福 埃本

【问题讨论】:

  • 您需要将整个表达式用引号括起来:powershell -command "& { ... }"

标签: sql-server powershell


【解决方案1】:

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

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

    • 此外,如果您从 cmd.exe 拨打电话(您不是),最安全的方法是 双引号 ... ("..."),并转义 embedded 双引号为\"(原文如此)。
  • inside PowerShell 中,省略 &(您确实需要 { ... } 以稳健地传递命令,但这种方法仅在从 PowerShell 内部调用时有效):

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

鉴于您的症状,我想知道您的情况下的 exec 命令是否实际上已经使用 PowerShell 而不是 cmd.exe 作为 shell,在这种情况下只传递文本 里面 { ... } 你的问题就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多