我有下面的脚本,当我尝试发送输出结果时,它不会转到文件中,因此txt文件是空的,如果你能告诉我哪里失败了,我将不胜感激。
Clear-Content .\telnet.txt
Write-host "Prueba de conexión de puertos"
'-'*30
' '*25
$test = @('WEB:google.com:443','WEBSERVER_HTTP:www.noticias3d.com:80')
Foreach ($t in $test)
{
$description = $t.Split(':')[0]
$source = $t.Split(':')[1]
$port = $t.Split(':')[2]
Write-Host "Conectando a $description host $source puerto $port"
try
{
$socket = New-Object System.Net.Sockets.TcpClient($source, $port)
$_.Message
}
catch [Exception]
{
Write-Host $_.Exception.GetType().FullName
Write-Host $_.Exception.Message
}
Out-File -FilePath telnet.txt
Write-Host "Revisado`n"
}
#$wsh = New-Object -ComObject Wscript.Shell
#$wsh.Popup("Finalizado checklist de Plataforma")发布于 2020-10-24 12:04:15
根据out-file帮助:
The Out-File cmdlet sends output to a file
在您的示例中,您没有提供任何输出,因此您得到的只是一个空文件。试一试
"my file content" | Out-File -FilePath telnet.txt
或者只使用重定向操作符:
"my file content" > telnet.txt
发布于 2020-10-24 12:06:33
您没有将任何内容提供给Out-File发送。A foreach(...)语句不会生成管道输出。即使是这样,您实际上也没有将它们链接在一起。将foreach循环的输出赋给一个变量,然后通过管道将该变量传递给Out-File。实际上,我建议您使用Set-Content。
Clear-Content .\telnet.txt
Write-host "Prueba de conexión de puertos"
'-'*30
' '*25
$test = @('WEB:google.com:443','WEBSERVER_HTTP:www.noticias3d.com:80')
$result = Foreach ($t in $test)
{
$description = $t.Split(':')[0]
$source = $t.Split(':')[1]
$port = $t.Split(':')[2]
Write-Host "Conectando a $description host $source puerto $port"
try
{
$socket = New-Object System.Net.Sockets.TcpClient($source, $port)
$_.Message
}
catch [Exception]
{
Write-Host $_.Exception.GetType().FullName
Write-Host $_.Exception.Message
}
$result | Set-Content -FilePath telnet.txt
Write-Host "Revisado`n"
}作为替代,您可以使用管道。
Clear-Content .\telnet.txt
Write-host "Prueba de conexión de puertos"
'-'*30
' '*25
$test = @('WEB:google.com:443','WEBSERVER_HTTP:www.noticias3d.com:80')
$test | ForEach-Object {
$description = $_.Split(':')[0]
$source = $_.Split(':')[1]
$port = $_.Split(':')[2]
Write-Host "Conectando a $description host $source puerto $port"
try
{
$socket = New-Object System.Net.Sockets.TcpClient($source, $port)
$_.Message
}
catch [Exception]
{
Write-Host $_.Exception.GetType().FullName
Write-Host $_.Exception.Message
}
} | Set-Content -FilePath telnet.txt
Write-Host "Revisado`n"您还在$_.Message行中引用了自动变量$_,它没有引用任何内容。
https://stackoverflow.com/questions/64509781
复制相似问题