Aniket Chaudhuri
Aniket Chaudhuri

Reputation: 3

How to get the filename from my code snippet in Powershell?

$dir = 'C:\ProgramData\AecorsoftDataIntegrator\logs\'

$StartTime = get-date

$fileList = (Get-ChildItem -Path $dir -Filter '2022*.log' | Sort-Object LastWriteTime -Descending | Select-Object -First 1).fullname

$message = Get-Content $fileList | Select-String -Pattern 'TCP/IP'| Select-Object -Property -FileName ##Not getting output from this variable

if ($fileList) {
    $search = (Get-Content $fileList | Select-String -Pattern 'TCP/IP').Matches.Success
    if($search) {
        "TCP/IP error message is present in the Aecorsoft Log Files : $fileList scanned at $StartTime and $message"
    } 
    else {
        "TCP/IP error message is not present in the Aecorsoft Log Files : $fileList scanned at $StartTime and $message"
    }
} 
else {
    "No matching files found in $dir"
}

Upvotes: 0

Views: 78

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 61303

I'm assuming you're looking for something similar to this, most of it is guessing since there is not much information in your question.

$dir   = 'C:\ProgramData\AecorsoftDataIntegrator\logs\'
$file  = Get-ChildItem -Path $dir -Filter '2022*.log' |
    Sort-Object LastWriteTime -Descending | Select-Object -First 1
$match = $file | Select-String -Pattern 'TCP/IP'

# if the pattern was matched in the file
if($match) {
    "TCP/IP error message is present in the Aecorsoft Log Files : {0} scanned at {1} and {2}" -f @(
        $match.Path, [datetime]::Now, $match.Line
    )
}
# if the pattern was not matched but the file exists
elseif($file) {
    "TCP/IP error message is not present in the Aecorsoft Log Files : {0} scanned at {1}" -f @(
        $file.FullName, [datetime]::Now
    )
}
# if the file does not exist
else {
    "No matching files found in $dir"
}

Regarding why FileName is not there, first of all you currently have:

Select-Object -Property -Filename

This will generate a new object with property -Filename and null value:

PS /> '' | Select-Object -Property -Filename   

-Filename
---------

The next issue is, even if using the right property name, the same would not be populated because Select-String only populates that property when reading a file, in this case, the cmdlet doing the reading is Get-Content which should not be there.

Upvotes: 1

Related Questions