Get-EventLog - Foreach

Guys.
Can anyone see anything wrong with this? Basically the Computers.txt file has a list of computer names in it but when the script is run it seems to be checking the local machine and not each of the remote computers?
Any ideas?
 $computers = Get-Content "H:\Computers.txt";
 $eventID = "1000"
foreach($computer in $computers)
 Get-EventLog -LogName Application -EntryType Error | where {$_.eventID -eq $eventID} | Where {$_.message –match "Outlook"} | Format-Table -Wrap -Property MachineName, Index, TimeGenerated, EntryType, Source, InstanceID, Message -AutoSize

You never specify the -ComputerName parameter so modify it to be
Get-EventLog -ComputerName $computer -LogName Application -EntryType Error
If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.
Don't Retire Technet

Similar Messages

  • Get-EventLog System -Newest 1 is not giving any output

    Note getting any output from below script when I put Newest 1.. but when i remove Newest , i get the output.
    why so..
    I need only latest event id in output
    Get-EventLog System -Newest 1 -ComputerName (Get-Content D:\script\serverlist.txt) | Where-Object {$_.EventID
    -eq 1074} | Select-Object EventID,MachineName,TimeWritten,Message
    Please help or guide me on this

    Here is one way to seek the instance when it is a debug event.
    $EventID=1074
    $instanceID=[uint32]([uint32]1074 -bor 0x80000000)
    Get-EventLog -LogName System -InstanceID $instanceID -Newest 1
    There is one other mask that should never appear in a production system.  It is used to flag records that are inserted as test records.  THey are ued when we want to test a programms error capabillity but do not want the eventing system to retain
    them or act on them.  I believe it is 0x40000000.
    We can also cascade ID.
    $EventID=1074
    $instanceID1=[uint32]([uint32]1074 -bor 0x80000000)
    $instanceID2=[uint32]([uint32]1074 -bor 0x40000000)
    Get-EventLog -LogName System -InstanceID $instanceID1,$instanceID2 -Newest 1
    Without the Newest 1 this would return both kinds of records.
    If you can use Get-WinEvent as it mmasks all of these to use true EventID.  It is alos much faster and more flexible.  As soon as WS2003 is ended Get-Eventlog is likely to be marked "Deprecated".
    Get-Content computers.txt |
         ForEach-Object{
              get-winevent  -FilterHashtable @{Logname='System';ID=1074} -MaxEvents 1 -ComputerName $_
    ¯\_(ツ)_/¯

  • Get-eventlog

    I'm trying to read the last 7 days of relevant Security log entries on one of my DCs and I'm getting the following error. Is there a way to accommodate all the data that's being returned? I don't explicitly declare $eventlog as a particular variable type.
    Clear-Variable -name eventlog
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (eventlog:String) [Clear-Variable], ItemNotFoundException
        + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.ClearVariableCommand
    Get-EventLog : Log "Security" could not be read to completion due to the following error. This may have occurred because the log was cleared while still being read. Index 81445 is out of
    bounds.
    At D:\tsg\Documentation\Powershell Repository\adaudit.ps1:163 char:13
    + $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -In ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ReadError: (:) [Get-EventLog], ArgumentException
        + FullyQualifiedErrorId : LogReadError,Microsoft.PowerShell.Commands.GetEventLogCommand
    Get-EventLog : No matches found
    At D:\tsg\Documentation\Powershell Repository\adaudit.ps1:163 char:13
    + $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -In ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
        + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand
    ...and here's a snippet of the relevant code:
    foreach ($domaincontroller in $domaincontrollers){
    Clear-Variable -name eventlog
    #517,624,626,630,632,633,634,636,637,642,644,660,661,671
    $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -InstanceId 1102,4720,4722,4726,4728,4729,4730,4732,4733,4738,4740,4756,4757,4767 -After ((Get-Date).AddDays(-7)) | select TimeGenerated,InstanceID,Message
    # ---- Members added to Domain Local Groups ----
                    $MyReport += Get-CustomHeader "1" "Members added to Domain Local Groups on domain controller $domaincontroller"
                            $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.InstanceID -eq "4732"} | select TimeGenerated,Message 
                    $MyReport += Get-CustomHeaderClose
    $MyReport += Get-CustomHeader0Close
    $MyReport += Get-CustomHTMLClose
    Thanks in advance,
    Greg

    I ended up re-rewriting the get-eventlog line and I used the get-winevent statement with a hashtable filter instead. The processing time went from 647seconds to 4seconds against 1 DC with the new code. Additionally, the error about the Index bounds disappeared:
    $days=((Get-Date).AddDays(-7))
    foreach($domaincontrollerin$domaincontrollers){
    $eventlog
    =
    Get-WinEvent
    -ComputerName
    $domaincontroller
    -FilterHashtable@{Logname='Security';
    ID=@(1102,4720,4722,4726,4728,4729,4730,4732,4733,4738,4740,4756,4757,4767);
    StartTime=$days}|
    select
    TimeCreated,ID,Message
    #do formatting stuff here

  • How to stop get-eventlog command if it finds a hit in the date range... w/o scanning the whole thing first :-/

    Hi All, 
    I have a nice little PowerShell function that is scrubbing the eventlog for a 'positive' hit under a certain error code for each user in a defined window. 
    basically we are looking to see if they are still logging into OCS...
    Since it takes what seems like an eternity to scan the whole security log per the 'get-eventlog' statement and then evaluate it it is $true or not... i would like it to break out as soon as it finds one hit without going all the way back x days unless it
    has to.
    have been trying to use this for testing... with no avail
    if (Get-EventLog -LogName Security -ComputerName myOCSserver -after $date -InstanceId 540 -UserName "domain\myuser") {
    Write-Host -ForegroundColor Green "UserName found!... Check Passed"
    }Else {
    Write-Host -ForegroundColor Cyan "UserName not found... delete this account"
    if i run the command it will start writing each hit to the screen... i just need it to stop scanning if it finds one but not sure how to break out and now do an action since it is $true... (or $false) :)
    Thanks in advance!!!

    I'm not sure i'm understanding this correctly but i'm assuming you only care if one shows up in there at all. If so this might speed things up depending on where in the log the first entry is.
    Get-EventLog -LogName
    Security -ComputerName myOCSserver
    -after $date -InstanceId
    540 -UserName "domain\myuser" | select -first 1

  • Powershell Get-Eventlog to export logs based on target machine

    Is there a way  to export windows event logs based on target machine with powershell? 
    I want to use this code to filter or classify System Center related logs according a specific agent on a hostname.

    Get-EventLog-ComputerNameseimi-nb-LogName'Windows
    PowerShell'|Export-Csvc:\EvetLog.csv 
    Seidl Michael | http://www.techguy.at |
    twitter.com/techguyat | facebook.com/techguyat

  • Getting pcs:foreach to iterate a Javascript array

    Dear Experts,
    I've got a selection list in a content item, and I can happily use <pcs:foreach> to iterate over it.
    So now, I would like to add an additional item to that which the user has selected, or get rid of some of the items.
    I have been able to get the values that I want intop a javascript array, but <pcs:foreach> to iterate. I have tried a delimited string with both a spaces and commas, no luck.
    Any ideas on programatically editing a selection list, or getting <pcs:foreach> to deal with an array?
    Thanks!
    Rob
    PS Here's the code !
    <script>
    var NewsCategoriesToShow = myArray.split(',');
    </script>
    This fails: <pcs:foreach var="cat" expr="NewsCategoriesToShow">
    This also fails: <pcs:foreach var="cat" expr="myArray">
    Only this works: <pcs:foreach var="cat" expr="mySelectionList">
    ...

    have you tried using straight javascript or jquery to edit the selection list after it is built? like with some javascript at the bottom of the page? i'll see if i can dig up any old code to see if i find that i've done this before.

  • Strange Get-EventLog Error

    Hi, Scripting guru!
    I try to execute command:
    Get-EventLog-LogNameSecurity-Newest5
    And get error:
    Get-EventLog : Log "Security" could not be read to completion due to the following error.
    This may have occurred because the log was cleared while still being read.
    Index nnnnnnn is out of bounds.
    Security log is ok, there is a lot of events, I launch Powershell with RunAsAdministrator
    rights, but still get that error.
    Can someone help me with that error?

    What version of PowerShell and OS are you running this on and against? How quickly do your logs roll over? I know security logs have a tendency to fill up fast if you are auditing a lot of things and the max size is low.
    I think you right about problem in Security Log itself. It was larger size, that it can be, and in bottom of the log I saw some "Deleted events". When I cleaned log, commandlet Get-EventLog works fine!
    So, I still have one question - why that bloated Security Log open fine with MMC console Event Viewer and get error with PoSH commandlet?
    Not a scripting question.
    Post in the OS forum for your OS for information on how to manage event logs.  They can also help you to diagnose your system and files system which may have issues.
    ¯\_(ツ)_/¯

  • Help with Get-EventLog and where clause

    I am trying to display a list of event IDs 1123 for the past 24 hours from Server1 using Get-EvenLog.
    Using the script below I get a list of all events 1123, can someone assist with incorporating $date =  Get-Date  $date = AddDays(-1) to where clause ?
    Get-EventLog -LogName $logName -ComputerName Server1 | where {$_.eventID -eq 1123} | fl -Property timegenerated, replacementstrings, message
    Thanks

    I also want to get the events emailed to me so I added the following, but the script seems to be getting stuck at the $msgbody line. Is this not the right way to send email?
    $date =  (Get-Date).AddDays(-1)
    $msgbody = Get-EventLog
    -LogName $logname -ComputerName hqdbsp18
    | where {$_.eventID
    -eq 1123 -and $_.timegenerated
    -gt $date} | fl
    -Property timegenerated, replacementstrings, message
    send-MailMessage -To "[email protected]" -from "[email protected]" -Subject "events from the past 24 hours" -body $msgbody -SmtpServer
    mysmtpserver

  • Adf: Get Id foreach

    Hi,
    In the code below I have 3 for each as master-detail(Clients-->Proyects-->Tasks), and the tasks are drag source components.
    I'm trying programmatically to get the value of the Id of each one on Drop, I'm able to get the "Name" of each item but I have no idea of how I could get the Id
    Help please!
    <code>
    <af:forEach var="clients" items="#{bindings.ClientsView2.children}">
    <af:showDetailItem id="sdi1" disclosed="true" text="#{clients.Name}"
    immediate="true">
    <af:forEach items="#{clients.children}" var="projects">
    <af:showDetail disclosed="false" id="sd1"
    disclosedText="#{projects.Name}"
    undisclosedText="#{projects.Name}">
    <af:forEach items="#{projects.children}" var="tasks">
    <af:outputText value="#{tasks.Name}" id="ot8">
    <af:componentDragSource/>
    </af:outputText>
    </af:forEach>
    </af:showDetail>
    </af:forEach>
    </af:showDetailItem>
    </af:forEach>
    </code>
    Thanks,
    Diego Velez

    Hi Diego,
    You can add a client attribute and reference it using an af:attributeDragSource, should look like this:
    <af:outputText value="#{tasks.Name}" id="ot8">
      <af:attributeDragSource attribute="id"/>
      <af:clientAttribute name="id" value="#{tasks.Id}"/>
    </af:outputText>See this demo: http://jdevadf.oracle.com/adf-richclient-demo/faces/components/attributeDragSource.jspx
    AP

  • Foreach output from get-command, add menu item

    Hi
    I'm making a script to configure some basic settings for new servers, and one of the features in the script is to set ip-address on the network interface. 
    At some servers there are several network interfaces, and I would like to create a menu based on the output from a get-query(Get-NetAdapter | select Name). Setting the ip-addresses is okay, but I'm having a problem creating a menu.
    What I want to do: If there is more than one NIC, create a menu with each network interface.
    Any clues?

    I didn't work that in, because I had no clue what you were trying to do when I initially wrote it.
    This version returns an object that you can work with ($selectedNIC) :
    $i = 1
    $menuList = @()
    $menuList = Get-NetAdapter | ForEach {
    $props = [ordered]@{
    'NIC Number'=$i
    Name=$_.Name
    InterfaceDescription=$_.InterfaceDescription
    ifIndex=$_.ifIndex
    Status=$_.Status
    MacAddress=$_.MacAddress
    LinkSpeed=$_.LinkSpeed
    New-Object PsObject -Property $props
    $i++
    $menuList | Format-Table -AutoSize
    $nicChoice = Read-Host 'Enter the NIC Number to process'
    $selectedNIC = Get-NetAdapter -InterfaceIndex ($menuList[$nicChoice-1]).ifIndex
    $selectedNIC
    Don't retire TechNet! -
    (Don't give up yet - 12,420+ strong and growing)

  • Help with Powershell script to gather eventlogs from all Domain Controllers

    I am trying to write a script to grab the last 5 days of application, security and system logs from all domain controllers. The script runs but only pulls the logs from the local server. The $Computer variable has all of my DC's so it is querying fine. I
    assume it is an issue with my ForEach-Object line but it doesn't error out. See the script below.
    $log = "Application"
    $date = get-date -format MM-dd-yyyy
    $now = get-date
    $subtractDays = New-Object System.TimeSpan 5,0,0,0,0
    $then = $Now.Subtract($subtractDays)
    $Computers = Get-ADDomainController -filter *
    ForEach-Object -InputObject $Computers  -Process {Get-EventLog -LogName $log -After $then -Before $now -EntryType Error | select EventID,MachineName,Message,Source,TimeGenerated | ConvertTo-html | Out-File $env:TEMP\Applicationlog.htm}
    Invoke-Expression $env:TEMP\Applicationlog.htm
    Thanks,
    Rich

    Also, you're missing the -ComputerName parameter in the Get-EventLog Cmdlet. 
    I would re-write the loop part of the script like this:
    $log = "Application"
    $date = get-date -format MM-dd-yyyy
    $now = get-date
    $subtractDays = New-Object System.TimeSpan 5,0,0,0,0
    $then = $Now.Subtract($subtractDays)
    $Computers = Get-ADDomainController -filter *
    foreach ($Computer in $computers) {
    Get-EventLog -ComputerName $Computer -LogName $log -After $then -Before $now -EntryType Error |
    select EventID,MachineName,Message,Source,TimeGenerated | ConvertTo-html | Out-File .\Applicationlog.htm -append
    Invoke-Expression .\Applicationlog.htm
    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable)

  • During Foreach read another foreach - PLZ HELP!

    Hi all powershell gurus out there.
    I have a foreach which opens a URL from URLListl.txt and doing a
    Measure-command on them. The result from Measure-command writes to event-log. 
    In another text file i have country list, like:
    USA
    Canada
    Brazil
    and so on....
    I want in write eventlogs Message to read from this Text file and write it with the Measure-command result in Message part of the eventlog.
    The below is my script which works fine but it creates two entries for each URL.
    function Measure-Site
    $URLListFile = "C:\yourname\URLList.txt"
    $URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
    Foreach ($Uri in $URLList)
    $Time = Measure-Command {
    C:\yourname\MainScript.ps1}
    $Time.TotalSeconds
    $countrycode = (Get-Content c:\yourname\URLListcountry.txt)
    foreach ($SiteCode in $CountryCode)
    $LogFileExist = Get-EventLog -list | Where-Object { $_.LogDisplayName -eq "Scriptcheck" }
    if (! $LogFileExist)
    New-EventLog -LogName "Scriptcheck" -Source "Scripts"
    if ($Time.Totalseconds -lt 25)
    Write-EventLog -LogName "Scriptcheck" -Source "Scripts" -EntryType information -EventId 100 -Message " $SiteCode `nTotal Time: $Time"
    elseif ($Time.Totalseconds -gt 25)
    Write-EventLog -LogName "Scriptcheck" -Source "Scripts" -EntryType warning -EventId 101 -Message " $SiteCode `nTotal Time: $Time"
    if (Get-Process -name iexplore -ErrorAction SilentlyContinue)
    Stop-Process -Name iexplore
    Measure-Site

    Hi Arash,
    I’m writing to just check in to see if the suggestions were helpful. If you need further help, please feel free to reply this post directly so we will be notified to follow it up.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • How to get the results in one line

    Hi
    if i use the script below i get the name of path and then : and in next line i get the results.is there a way to get the results from every path after the : and not in the next line?
    another question - is there a way that the script will not show the server name on every path?
    (Get-Counter -ListSet LogicalDisk).PathsWithInstances | Get-Counter
    THC

    If you take you script and pipe it to get member, it will give you a list of various script properties.
    (Get-Counter -ListSet LogicalDisk).PathsWithInstances | Get-Counter | get-member
    You will see that the object type returned by "Get-Counter" is Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet.
    TypeName:
    Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet
    Name MemberType Definition
    Equals Method bool Equals(System.Object obj)
    GetHashCode Method int GetHashCode()
    GetType Method type GetType()
    ToString Method string ToString()
    CounterSamples Property Microsoft.PowerShell.Commands.GetCounter.Perfo...
    Timestamp Property datetime Timestamp {get;set;}
    Readings ScriptProperty System.Object Readings {get=$strPaths = ""...
    You can try grabbing different properties, and they will print out differently, displaying the data on the same line in some cases. For example, pipe your output to a "foreach-object" block, and then for each object print out the CounterSamples property.
    (Get-Counter -ListSet LogicalDisk).PathsWithInstances | Get-Counter | foreach-object { ($_).CounterSamples }
    This should all print on one line now. However, you also asked if there was a way to not have the server print out on every line. The way to control the format of these outputs is to use the "format-table" cmdlet. So you would pipe your output to format-table
    and then give it various options. This is how you would pipe it (without any options).
    (Get-Counter -ListSet LogicalDisk).PathsWithInstances |
    Get-Counter | object { ($_).CounterSamples | format-table }#OR USE YOUR ORIGINAL CODE(Get-Counter -ListSet LogicalDisk).PathsWithInstances |
    Get-Counter | format-table }
    Now, it's up to you to give format-table the options you want. With no options, output will look unchanged. To see what options are available to you, use get-help.
    get-help format-table
    I hope this helps!
    Thank for all the info...

  • Not able to Register-ObjectEvent for System.Diagnostics.Eventlog "EntryWritten" Event

    Hi,
    I'm trying to listen for an entry in an EventLog created. 
    New-EventLog -LogName TestLog -Source "MyScript" # This is my eventlog
    # And for monitoring, the code goes like this:
    $testlogs = Get-EventLog -LogName TestLog
    Register-ObjectEvent -INputObject $testlogs -SourceIdentifier NewEventLogEntry -EventName EntryWritten -Action{....some actions...}
    But I'm encountering an error:
    Register-ObjectEvent : Cannot register for event. An event with name 'EntryWritten' does not exist.
    Parameter name: eventName
    At line:1 char:1
    + Register-ObjectEvent -InputObject $testlogs -SourceIdentifier NewEventLogEntry - ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (System.Diagnostics.EventLogEntry:EventLogEntry) [Register-ObjectEvent], ArgumentExce 
       ption
        + FullyQualifiedErrorId : INVALID_REGISTRATION,Microsoft.PowerShell.Commands.RegisterObjectEventCommand
    What's wrong with this one ? Thanks in advance !

    This works for me:
    New-EventLog -LogName TestLog -Source "MyScript" # This is my eventlog
    $testlogs = Get-EventLog -List | Where-Object {$_.Log -eq 'TestLog'}
    Register-ObjectEvent -InputObject $testlogs -EventName EntryWritten -SourceIdentifier NewEventLogEntry -Action{Write-Host "New entry"}
    Write-EventLog -LogName TestLog -Source "MyScript" -EntryType Information -EventId 1 -Message "this is a test"

  • Script to get application stats running on multiple windows servers

    Hi,
     I am beginner in powershell and trying to write a script to get the different stats of an application/s running on  windows WAS server. am trying to gather all the stats into one custom object and planning the tabular output to send via html mail.
    am finding it hard to frame logic to get this done and below is piece of script. can somebody guide on this ?
    # Get the profiles list in the server
    $ppath = "profilePath"
    $profiles = Get-ChildItem "profilePath" | ForEach-Object { $_.Name }
    $SystemInfo = @()
    $profiles | ForEach-Object {$_}{
    $Obj = New-Object -TypeName PSObject
    $pathToCheck = $ppath + $_ + "application path" 
    $SerFile = "profilePath" + $_ + "service file"
    $ContFile = "profilePath" + $_ + "context file"
    if(Test-Path $pathToCheck)
    #Write-Host "Profile ==>" $_
    $Obj | Add-Member -MemberType NoteProperty -Name Profile -Value $_
    $PIDFile = $ppath + $_ + "PID file path"
    if(test-path $PIDFile)
    $ProcID = get-content $PIDFile
    #Write-Host "PID     ==>" $ProcID
    $memTmp = Get-WmiObject -class Win32_PerfFormattedData_PerfProc_Process | where{$_.idprocess -eq $ProcID} | Select WorkingSetPrivate
    $memUsage = $memTmp | Select -Expand WorkingSetPrivate
    #Write-host "Memory  ==>" $memUsage
    else{
    $ProcID = "PID Not Found"
    $Obj | Add-Member -MemberType NoteProperty -Name Memory -Value $memUsage
    if(test-path $SerFile)
    $temp = Get-ChildItem -name $SerFile
    $SerStr = $temp.Substring(0,4)
    $nm = Get-Service -name *$SerStr* | Select Name
    $name = $nm | select -expand Name
    $sts = Get-Service -name *$SerStr* | Select Status
    $status = $sts | select -expand Status
    #Write-Host "Service Name ==>" $name
    #write-host "Status " ==> $status
    else{
    $SerStr = "Service Not Found"
    $Obj | Add-Member -MemberType NoteProperty -Name Service-Name  -Value $name
    $Obj | Add-Member -MemberType NoteProperty -Name Service-Status -Value $status
    if(test-path $ContFile)
    [XML]$rav = get-content $ContFile
           $tmp1 = @($rav.GetElementsByTagName("context-root"))
           $client = $tmp1[0]."#text"
           #write-host "Environment" ==> $client
    else{
    $client = "ContextRoot Not Found"
       }$Obj | Add-Member -MemberType NoteProperty -Name Environment -Value $client
    write-output $Obj | format-table -autosize  Profile , Environment

    Hi Ravi0211,
    The script below may be helpful for you, which can filter the process based on the property "idprocess" and the services based on the service "name":
    $pids=@()
    $output=@()
    $output1=@()
    get-content d:\processid.txt|foreach{
    $pids+=$_} #store the processid as an array
    Get-WmiObject -class Win32_PerfFormattedData_PerfProc_Process | foreach{
    if ($pids -contains $_.idprocess){#filter the processid listed in the file d:\processid.txt
    $Obj = New-Object -TypeName PSObject
    $Obj | Add-Member -MemberType NoteProperty -Name idprocess -Value $_.idprocess
    $Obj | Add-Member -MemberType NoteProperty -Name Memory -Value $_.WorkingSetPrivate
    $output+=$obj}
    $services = get-content d:\service.txt
    Foreach($service in $services){
    Get-service | foreach{
    If ($_.name –like “*$service*”){#filter the service based on the service name stored in d:\service.txt
    $Obj1 = New-Object -TypeName PSObject
    $Obj1 | Add-Member -MemberType NoteProperty -Name Service-Name -Value $_.name
    $Obj1 | Add-Member -MemberType NoteProperty -Name Service-Status -Value $_.status
    $output1+=$obj1}
    $output
    $output1
    I hope this helps.

Maybe you are looking for