【问题标题】:Is there a way to surpress all command line output, including errors, from Powershell有没有办法从 Powershell 抑制所有命令行输出,包括错误
【发布时间】:2019-10-09 07:14:09
【问题描述】:

从 Python 脚本 (subprocess.Popen) 调用 Powershell 时,我正在循环浏览 AD 域控制器列表。对于每个无法识别 AD 对象的控制器,我想抑制错误输出。

在 Powershell 命令末尾使用| Out-Null 无效。

Python 脚本:

for server in ADDomainList:
    cmd = 'powershell.exe get-ADComputer ' + hname + ' -Server ' + server + ' | Out-Null'
    subprocess.call(cmd)

从 Powershell 命令行:

get-ADComputer computer-name -Server server.domain.com

不需要的输出:

Get-ADComputer : A positional parameter cannot be found that accepts argument '?'.
At line:1 char:1
+ get-ADComputer computer-name -Server server.domain.com ?
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

返回码为 0 或 1 的结果是我在接下来的执行步骤中需要捕获的全部内容。我不希望控制台有任何输出。

【问题讨论】:

  • 将输入验证代码添加到您的 python 代码或您的 PoSh 脚本中。

标签: powershell command output line


【解决方案1】:

*> $null 一样将所有流重定向到 null。这将导致没有输出。

cmd = 'powershell.exe get-ADComputer ' + hname + ' -Server ' + server + ' *> $null'

如果您想通过管道传输到 Out-Null 或任何其他 cmdlet,您还可以将所有输出重定向到成功流,然后通过管道传输到另一个 cmdlet,如下所示:

cmd = 'powershell.exe get-ADComputer ' + hname + ' -Server ' + server + ' *>&1 | Out-Null'

Here is some more information about redirection in Powershell.

【讨论】:

    【解决方案2】:

    这是另一个利用 PowerShell 的解决方案 “尝试和捕捉”功能。通过在循环中使用它,错误的 响应被消除。

    我通过 PowerShell tr​​y and catch 找到了我需要的服务器

    cmd = 'powershell.exe try{get-ADComputer ' + hname + ' -Server 
    ' + server + ' | Out-Null}catch{}'
    

    一旦我有了正确的服务器,我就使用 '| Out-Null' 摆脱 默认的 PowerShell 输出。

    subprocess.Popen('powershell.exe get-ADComputer ' + hname + ' 
    -Server ' + sname + ' -Properties '
    'OperatingSystem,PasswordLastSet | Export-CSV adcomputer.csv - 
    Delimiter "*" -NoTypeInformation | Out-Null')
    

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 2020-06-23
      • 1970-01-01
      • 2023-04-01
      • 2019-09-22
      • 2014-10-27
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多