Powershell file output. CSV after Foreach

Asked

Viewed 226 times

1

Good afternoon! I have a simple powershell scritp that performs the connection test between Omains controllers and their respective service ports as below:

$servers = Get-Content -Path 'C:\DC Health\Domains_Controllers.txt'
$IP_TCPs = Get-Content -Path 'C:\DC Health\TCP_Ports.txt'
foreach($IP_TCP in $IP_TCPs){
foreach($server in $servers){

$socket = New-Object Net.Sockets.tcpClient

Try{
    $socket.Connect($server, $IP_TCP)
Write-Host $server $IP_TCP Conectado
}
Catch{
Write-Host $server $IP_TCP Desconectado
}

Finally{
    $socket.Close()
    $socket.Dispose()

}
}
}

I wanted to have the output in some file like . txt or . csv, but the file always comes out blank. Is there any possibility of amending or adding to this exit? Thanks in advance.

2 answers

1


Warning: Tests performed in windows 10 with powershell 5.1.

Warning: "Write-Host" does not redirect to file but to console.

Tip: The use of the "Try" clause should be avoided because it affects the "$Error" object. Whenever possible, use commands that test the situation. In your particular case, you could use "Test-Netconnection"

So I would change the internal code to:

$Resposta = ( Test-NetConnection -ComputerName $server -Port $IP_TCP ).TcpTestSucceeded
$Objeto = [PSCustomObject]@{
    Servidor = $server
    PortaTCP = $IP_TCP
    Situação = @( 'Desconectado', 'Conectado' )[ [Boolean]$Resposta ]
}
Export-Csv -InputObject $Objeto -LiteralPath '[caminho]\[nome do arquivo].csv' -Append

Now, answering your question:

1) Before the "Try" clause, create a custom object:

$Objeto = [PSCustomObject]@{
    Servidor = $server
    PortaTCP = $IP_TCP
    Situação = ''
}

2) After the socket call:

2.1) Update the object:

$Objeto.Situação = 'Conectado'

2.2) Remove the "Write-Host clause"

3) In the clause "Catch":

3.1) Update the object:

$Objeto.Situação = 'Desconectado'

3.2) Remove the "Write-Host clause"

4) In the clause "Finally", export the object to a CSV file:

Export-Csv -InputObject $Objeto -LiteralPath '[caminho]\[nome do arquivo].csv' -Append

0

To export the result directly to a text file, you can use the pipeline command Out-File

Example of use:

"$server $IP_TCP Conectado" | Out-File -FilePath "c:\\temp\\test.txt" -Append

Browser other questions tagged

You are not signed in. Login or sign up in order to post.