从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的结果就是我需要为下一步执行捕获的所有内容。我不想要任何输出到控制台。
发布于 2019-05-23 03:40:41
将所有流重定向到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.
发布于 2019-05-24 23:25:07
这是另一个利用PowerShell“先试后接”特性的解决方案。通过在循环中使用它,可以消除错误响应。
我使用PowerShell try 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')https://stackoverflow.com/questions/56262910
复制相似问题