Need assistance to change powershell code

llarava
llarava used Ask the Experts™
on
The script below does a count of the existing folders and if the count is different the next time it runs then it will generate an Event ID. The problem that I have with the existing approach is that when a folder is purged/deleted the count is no longer valid and we will be a false positive.

Instead of the .count we need to find if a new folder has been created. I am not sure if there is a way to do it by date? or some other way so that when folders are deleted we don't get falser positives.

Basically the goal is to have a script which will run from SCOM the target machine (every 30 min) to verify if a new folder has been created in a specific path, if so then will generate an event ID. SCOM will monitor the event-id and generate an alert.

The script below works great, but we need to replace the count with something that will be more date oriented.

Thank you!

---------------

#requires -version 3
New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
$basecountfile = "$env:HOMEDRIVE\scripts\basecount.txt"
if (test-path -Path $basecountfile){
  # if file not found then this is the first run so there is no baseline
  # otherwise check the path and count the directories and compare against the baseline
        $previouscount = get-content -path $basecountfile
        $basecount = (get-childitem -Path \\server\folder -Recurse -Directory).count
        if ($basecount -ne $prevouscount) {
        # found a difference
          Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'
          }
  }
  #always write the count of directories, will create if not found or overwrite if found
  $basecount | out-file -FilePath $basecountfile -Force

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Maybe...something using something like this from the script below:

$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-15) }

I am not sure how to modify the original

-----------------------------------------------

$SearchPath = "\\Server\Faxes"
$PSEmailServer = "mysmtpserver.domain.com"
$EmailTo = "myemail@domain.com"
$EmailFrom = "useremail@domain.com"
$EmailSubject = "A new fax has arrived"
$EmailBody = @"
An new fax was received.  Please forward to the appropriate receipient.
You can visit the shared folder by clicking the following link:
$($SearchPath)
"@
$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-15) }

$NewHTML = @()

If ($File)
{	$SMTPBody = "`nThe following files have recently been added/changed:`n`n "
	$File | ForEach { $SMTPBody += "$($_.FullName)`n" }
	Send-MailMessage @SMTPMessage -Body $SMTPBody
	
}

ForEach($NewFax in $IncomingFaxes)
	{
	Send-MailMessage -To $EmailTo -From $EmailFrom  -Subject $EmailSubject -Body $EmailBody -BodyAsHtml
	}

Open in new window

LastWriteTime even will detect if anything is copied to that folder or edited something in there.
best is you can compare the Dir Create time and if the time is Grater then the last 30 min then the event gets logged.

as you are going to run it every 30 min we can check if any new Dir was added in Last 30 min.

$path="\\server\folder"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'}

Open in new window

Author

Commented:
What needs to be replace in the original script to include the latest code?

#requires -version 3
New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
$basecountfile = "$env:HOMEDRIVE\scripts\basecount.txt"
if (test-path -Path $basecountfile){
  # if file not found then this is the first run so there is no baseline
  # otherwise check the path and count the directories and compare against the baseline
        $previouscount = get-content -path $basecountfile
        $basecount = (get-childitem -Path \\server\folder -Recurse -Directory).count
        if ($basecount -ne $prevouscount) {
        # found a difference
          Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'
          }
  }
  #always write the count of directories, will create if not found or overwrite if found
  $basecount | out-file -FilePath $basecountfile -Force

Open in new window


Include this:

$path="\\server\folder"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'}

Open in new window

Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

this is the complete script, this is all you need to log an event if there is any new dir detected.
you can test it by creating new dir on your system drive and then run this script against the drive and you should see the event log in your application log.


New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
$path="\\server\folder"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {
write-host "New dir was setup" -f yellow
Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'
}

Open in new window

Author

Commented:
Thanks!

Getting the following error:

PS P:\> New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
$path="\\vsa3324sc\Temp"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {
write-host "New dir was setup" -f yellow
Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'
Missing closing '}' in statement block or type definition.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndCurlyBrace

Author

Commented:
missing } !!

Author

Commented:
The script runs but the event ID is not being created. I've created a new folder before running the script.

Author

Commented:
Works when I use a local path (C:\temp) and run it from within the server , but it doesn't work when I use a remote path  \\server\temp and run it remotely.
can you run the CMD Get-ChildItem \\Server\temp do you see the folder you setup ??

Author

Commented:
Getting the following :


P:\>CMD Get-ChildItem \\server\Temp
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.

P:\>
you are running it incorrectly I guess remove CMD just run

Get-ChildItem \\server\Temp

Open in new window


this should show the DIR you have created in this folder if not then set up one again and test.

Author

Commented:
I've created a new folder in C:\temp

Then ran he code below:  

New-EventLog -LogName Application -Source "WatchFolder" -ErrorAction SilentlyContinue
$path="C:\temp"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {
write-host "New dir was setup" -f yellow
Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'

Open in new window


...but the script keeps saying there is a new folder every time it runs but I have not created any new folders.
I just need to get the Event ID generated when a new folder is created since the last time the script was executed, otherwise I will always generate alerts.
Top Expert 2016

Commented:
which event log are you checking?

New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
Write-EventLog -LogName Application -Source 'MyScript' -EntryType Error -EventID 1  -Message 'Directory has been Created'

you can add the parameter -computername servername to both items

hint: powershell has a very extensive help system
use help command or get-help command
powershell is dynamic so you should run 'update-help' every once in a while.
i.e.
PS D:\Documents\WindowsPowerShell\Scripts> help new-eventlog -Examples

NAME
    New-EventLog
    
SYNOPSIS
    Creates a new event log and a new event source on a local or remote computer.
    Example 1: Create an event log and register its source
    PS C:\>New-EventLog -Source "TestApp" -LogName "TestLog" -MessageResourceFile "C:\Test\TestApp.dll"
    This command creates the TestLog event log on the local computer and registers a new source for it.
    Example 2: Add an event source to the Application log
    
    PS C:\>$file = "C:\Program Files\TestApps\NewTestApp.dll"
    PS C:\> New-EventLog -ComputerName "Server01" -Source "NewTestApp" -LogName "Application" -MessageResourceFile $file -CategoryResourceFile $file
    
    This command adds a new event source, NewTestApp, to the Application log on the Server01 remote computer.
    The command requires that the NewTestApp.dll file is located on the Server01 computer.
PS D:\Documents\WindowsPowerShell\Scripts> 

Open in new window

what's the interval between the first and 2nd run?

script checks if the folder was setup in last 30 min, so it is advised you run it on an interval of 30 min if you run the script before 30 min passed script will detect the same old folder created with the last 30 min. and will keep logging the event.

Author

Commented:
Thanks David!

The issue I am having right now is that every time I run the script it's generating a new event ID "MyScript" but I have only created a new folder. Ideally I would like to be able to report just when new folders are being created.

For example:

c:\temp\newfolder1

run script ---- Event ID generated

run script again (no folder created) --- Event ID not generated

When a new folder is created an I run the script then a new Event ID is generated.

Thanks everyone for your help!

Author

Commented:
Sunil Chauhan,

I will reduce the time to be able to easily test. That might be the issue.

Author

Commented:
One quick question -- If I wanted to replace the Write-EventLog with send an email instead what will be the best way to do it?
replace all the variable.

you should have an SMTP relay server which can accept emails from the server you are running the script on.

$EmailTo="Sender@domain.com"
$EmailFrom="recipient@domain.com"
$EmailSubject="Notification:New folder was created in the $path"
$EmailBody="New Folder was setup"
$smtp=relayserver.domain.com
$path="C:\temp"
$File = Get-ChildItem $Path -Recurse -Directory | Where { $_.CreationTime -ge [datetime]::Now.AddMinutes(-30) }
if ($file) {
write-host "New dir was setup" -f yellow
Send-MailMessage -To $EmailTo -From $EmailFrom  -Subject $EmailSubject -Body $EmailBody -BodyAsHtml -smtpServer $smtp
}

Open in new window

Author

Commented:
The issue was the timing. Thanks

Getting the same error when running the script with the email function ... I've verified the SMTPrelay servers and the settings are correct.

smtprelay.server.com : The term 'smtprelay.server.com' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Script\script2.ps1:5 char:7
+ $smtp=smtprelay.server.com
+       ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (smtprelay.server.com:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
my bad put it in Quotes

$Smtp="Relay.Domain.com"

Open in new window

Author

Commented:
Excellent - thank you!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial