首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >找不到Powershell将输出变量导出到文件

找不到Powershell将输出变量导出到文件
EN

Stack Overflow用户
提问于 2020-10-24 11:49:18
回答 2查看 147关注 0票数 0

我有下面的脚本,当我尝试发送输出结果时,它不会转到文件中,因此txt文件是空的,如果你能告诉我哪里失败了,我将不胜感激。

代码语言:javascript
复制
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")
EN

回答 2

Stack Overflow用户

发布于 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

票数 0
EN

Stack Overflow用户

发布于 2020-10-24 12:06:33

您没有将任何内容提供给Out-File发送。A foreach(...)语句不会生成管道输出。即使是这样,您实际上也没有将它们链接在一起。将foreach循环的输出赋给一个变量,然后通过管道将该变量传递给Out-File。实际上,我建议您使用Set-Content

代码语言:javascript
复制
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"
}

作为替代,您可以使用管道。

代码语言:javascript
复制
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行中引用了自动变量$_,它没有引用任何内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64509781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档