gpt4 book ai didi

通过测试连接进行Powershell尝试/捕获

转载 作者:行者123 更新时间:2023-12-04 00:09:40 27 4
gpt4 key购买 nike

我正在尝试将脱机计算机记录在文本文件中,以便以后可以再次运行它们。似乎没有被记录或捕获。

function Get-ComputerNameChange {

[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[string[]]$computername,
[string]$logfile = 'C:\PowerShell\offline.txt'
)




PROCESS {

Foreach($computer in $computername) {
$continue = $true
try { Test-Connection -computername $computer -Quiet -Count 1 -ErrorAction stop
} catch [System.Net.NetworkInformation.PingException]
{
$continue = $false

$computer | Out-File $logfile
}
}

if($continue){
Get-EventLog -LogName System -ComputerName $computer | Where-Object {$_.EventID -eq 6011} |
select machinename, Time, EventID, Message }}}

最佳答案

try用于catch异常(exception)。您正在使用-Quiet开关,因此Test-Connection返回$true$false,并且在连接失败时不会throw异常。

做就是了:

if (Test-Connection -computername $computer -Quiet -Count 1) {
# succeeded do stuff
} else {
# failed, log or whatever
}

关于通过测试连接进行Powershell尝试/捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32637785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com