我正在尝试在多台计算机上查询其公共IP地址。如果使用脚本1,则一次只能查询一台计算机,并将输出保存到文件中。如果我使用具有多个计算机名的文本文件,则仅查询1或2台计算机。 (如果我按1做1,我就能查询所有计算机。)
然后我在脚本2中添加了try,catch来捕获任何不响应的计算机,但是该脚本什么也不输出。理想情况下,我想查询多台计算机并捕获任何无响应的计算机,但脚本2无法正常工作。
脚本1
$computers= Get-Content .\hostnames.txt
foreach ($computer in $computers) {
$computerSystem = (get-wmiobject Win32_ComputerSystem -Computer $computer).name
$IP=Invoke-Command -ComputerName $computer -ScriptBlock {
(Invoke-WebRequest -uri "http://smart-ip.net/myip" -UseBasicParsing).content } -ErrorAction SilentlyContinue }
$computerSystem, $ip | out-file .\output2.csv -Append
脚本2
$computernames = Get-Content .\hostnames.txt
$NotRespondingLog = ".\notresponding.log"
$data = ForEach ($Computer in $computernames) {
try{
$computerSystem = (get-wmiobject Win32_ComputerSystem -Computer $computer).name
$IP=Invoke-Command -ComputerName $computer -ScriptBlock {
(Invoke-WebRequest -uri "http://smart-ip.net/myip" -UseBasicParsing ).content } -ErrorAction SilentlyContinue
} catch{
$Computer | Out-File -FilePath $NotRespondingLog -Append -Encoding UTF8
continue } }
$data | out-file ".\output2.csv" -Append
答案 0 :(得分:1)
我认为您的代码没有发出任何东西返回到管道或文本文件。我建议我们应该重新编写一下,以便于理解。
如果您想知道为什么try/catch
未被评估,这是因为在您的Invoke-WebRequest
命令中,您将-ErrorActionPreference
设置为SilentlyContinue
。这直接告诉PowerShell我们不想评估catch块或在发生错误时发出警报。
为了清楚起见,这里我重新编写了一些代码,并添加了一个或两个步骤来发出对象,这就是使用单个$thisPC
命令的行所做的。无论是在try块内还是catch块内,我们只需创建一个新的PowerShell对象,映射属性,然后将其发送到控制台并将其添加到名为$ComputerList
的跟踪列表中即可。这是在企业就绪脚本中会看到的非常常见的模式。
$computernames = 'SomePC123','SomePC234','OfflinePC'
$ComputerList = New-Object System.Collections.ArrayList
ForEach ($Computer in $computernames) {
try{
$computerName = (get-wmiobject Win32_ComputerSystem -Computer $computer).name
$IP= Invoke-Command -ComputerName $computer -ScriptBlock {
(Invoke-WebRequest -uri "http://smart-ip.net/myip" -UseBasicParsing ).content -ErrorAction Stop
}
$thisPC = [psCustomObject]@{Name=$computerName;IP=$IP}
$thisPC
$ComputerList.Add($thisPC) | Out-Null
}
catch{
$thisPC = [psCustomObject]@{Name=$Computer;IP='Not Responding'}
$thisPC
$ComputerList.Add($thisPC) | Out-Null
}
}
$ComputerList | out-file ".\output2.csv" -Append
这是它的输出:
Name IP
---- --
SomePC234 149.178.121.237
OfflinePC Not Responding
SomePC123 48.40.234.122