none
Need to add if else condition in expression statement RRS feed

  • Question

  • Hi All,

    I want to print if else condition in Expression statement if test-path given is present, it should print file is present or else file is not present. Please suggest on below script.

    I have tried but output is blank


    Get-Content .\computers.txt |
       Select-Object @{Name='ComputerName';Expression={$_}},
         @{Name='Online';Expression={(Test-Connection $_ -count 1 -EA 0).StatusCode -eq 0}},
         @{Name='avagnet';Expression={ Test-Path "\\$_\c`$\Program Files\avs\bin\avagent.exe"}},
         @{Name='CID';Expression={ Test-Path "\\$_\c`$\Program Files\avs\var\cid.bin"}}


    Thursday, September 26, 2019 1:08 PM

All replies

  • I'm sure there are probably more sophisticated ways but I think that could be a pretty decent way ... ;-)

    $ResultObject = New-Object System.Collections.Generic.List[object]
    
    Foreach ($ComputerName in $(Get-Content -Path .\computers.txt)) {
        $newobj = [PSCustomObject]@{
            ComputerName = $ComputerName
            Online       = ''
            AVAgent      = ''
            cid          = ''
        }
        if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
            $newobj.Online = $true
            $newobj.AVAgent = Test-Path "\\$ComputerName\c`$\Program Files\avs\bin\avagent.exe"
            $newobj.cid = Test-Path "\\$ComputerName\c`$\Program Files\avs\var\cid.bin"
        }
        else {
            $newobj.Online = $false
            $newobj.AVAgent = 'n/a'
            $newobj.cid = 'n/a'
        }
        $ResultObject.Add($newobj)
    }
    $ResultObject


    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Thursday, September 26, 2019 2:54 PM
    Thursday, September 26, 2019 2:44 PM
  • Why not just output the result objects as you generate them (why do you need to build a collection)?

    -- Bill Stewart [Bill_Stewart]

    Thursday, September 26, 2019 4:09 PM
    Moderator
  • Why not just output the result objects as you generate them (why do you need to build a collection)?
    Well ... you don't need it ... ;-)  ... that's what I meant ... there are always other ... and in my case pretty often better ways to do things.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Thursday, September 26, 2019 4:57 PM