Powershell将输出变量导出到文件未找到

问题描述

我有以下脚本,并且尽我所能发送输出结果,它不会转到文件,因此txt文件为空,如果您能告诉我失败的地方,我将不胜感激。 / p>

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")

解决方法

按照out-file帮助:

The Out-File cmdlet sends output to a file

在您的示例中,您没有提供任何输出,因此您只是得到一个空文件。试试

"my file content" | Out-File -FilePath telnet.txt

或仅使用重定向运算符:

"my file content" > telnet.txt

,

您没有给Out-File发送任何内容。 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,该行什么都没有引用。