powershellsystem-administration

How to get the exit error of the prompt on a log


Got this script that checks disk space and transfers it on to a log and i want to put the error that pops on the prompt inside the log

$equipos = "D:\SCRIPTSM\AAAA\equipos.txt"
$listaEquipos = Get-Content $equipos
$fecha = (Get-Date).ToString('dd.MM.yyyy')
$espaciotxt = foreach ($equipo in $listaEquipos){
    Get-WmiObject -Class Win32_LogicalDisk -ComputerName $equipo -Filter "drivetype=3" | Sort-Object -Property DeviceID | Format-Table -Property DeviceID,
    @{name='EspacioLIBRE(MB)';expression={$_.Freespace / 1MB -as [int]}},
    @{name='TamañoDISCO(GB)';expression={$_.Size / 1GB -as [int]}},
    @{name='%Libre';expression={$_.FreeSpace / $_.Size * 100 -as [int]}}
    Write-Output "Ip del equipo : $equipo fecha del test: $fecha"
    }
$espaciotxt | Out-File C:\Users\AAAAA\Desktop\PRU.txt

Heres the exit log and where do i want to place the error prompt inside of it.

Error prompt: Get-WmiObject : RPC server is not available...

log img disk


Solution

  • I've added a Try-Catch loop & set the error preference to "Stop" on the Get-WMIObject command.

    Not sure if you want "Error Prompt:" or your own custom string, so I've added both to the catch statement.

    $Error[0] is the last Error in the Powershell session, which will be what triggered the catch statement.

    $equipos = "D:\SCRIPTSM\AAAA\equipos.txt"
    $listaEquipos = Get-Content $equipos
    $fecha = (Get-Date).ToString('dd.MM.yyyy')
    $espaciotxt = foreach ($equipo in $listaEquipos){
        Try{
            Get-WmiObject -Class Win32_LogicalDisk -ComputerName $equipo -Filter "drivetype=3" -ErrorAction Stop | Sort-Object -Property DeviceID | Format-Table -Property DeviceID,
            @{name='EspacioLIBRE(MB)';expression={$_.Freespace / 1MB -as [int]}},
            @{name='TamañoDISCO(GB)';expression={$_.Size / 1GB -as [int]}},
            @{name='%Libre';expression={$_.FreeSpace / $_.Size * 100 -as [int]}}
            Write-Output "Ip del equipo : $equipo fecha del test: $fecha"
        }
        catch{
            "Error prompt: "+[string]$Error[0].Exception.Message
            $Error[0].Exception.Message
            Write-Output "Ip del equipo : $equipo fecha del test: $fecha"
        }
    }
    $espaciotxt | Out-File C:\Users\AAAAA\Desktop\PRU.txt