SNair
SNair

Reputation: 85

check for text in a file on a remote machine

I am using a powershell to query a file on a remote machines C-drive and if the file exist with status 'imaging completed' it should run other checks.

$filetofind = Get-Content C:\Image.log

#Get the list down to just imagestatus and export
foreach ($line in $filetofind)
    {
    $file = $line.trim("|")
    echo $file >> C:\jenkins\imagestatus.txt
    }

But when I run below commands I am getting the error. Can anyone help ?

Get-Content : Cannot find path 'C:\Image.log' because it does not exist.
    At line:18 char:15
    + $filetofind = Get-Content C:\Image.log
    +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\Image.log:String) [Get-Content], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Upvotes: 2

Views: 15795

Answers (1)

henrycarteruk
henrycarteruk

Reputation: 13227

Test-Path will check if a file exists, and Select-String can be used to search the file for a string, using the -Quiet param will make the command return True if the string is found, rather than returning each line in the text file that includes the string.

Then using both commands in simple if statements to check their status:

$file = "C:\Image.log"
$searchtext = "imaging completed"

if (Test-Path $file)
{
    if (Get-Content $file | Select-String $searchtext -Quiet)
    {
        #text exists in file
    }
    else
    {
        #text does not exist in file
    }
}
else
{
#file does not exist
}

EDIT:

To check the file on multiple computers you need to use a foreach loop to run the code against each computer separately. The below assumes you have one hostname per line in hostnames.txt.

$hostnames = Get-Content "C:\hostnames.txt"
$searchtext = "imaging completed"

foreach ($hostname in $hostnames)
{
    $file = "\\$hostname\C$\GhostImage.log"

    if (Test-Path $file)
    {
        if (Get-Content $file | Select-String $searchtext -quiet)
        {
            Write-Host "$hostname: Imaging Completed"
        }
        else
        {
            Write-Host "$hostname: Imaging not completed"
        }
    }
    else
    {
        Write-Host "$hostname: canot read file: $file"
    }
}

Upvotes: 3

Related Questions