Powershell Script help/advise

Hello,

i have created the below PS script which is meant to check if any new files have been placed within a folder and if so then it launches them and displays them on our various screens. the script loops every 20 seconds and if a file already exists with that name then it ignores the reset of the script and waits another 20 seconds.

my issues is that after 20 seconds the script will close the power point show already open and then it checks and sees its not there and re-launches it. i have not specified anywhere for the code to close the application so i am confused why this is happening. can someone show me where i am going wrong please?

 
$Path = "\\10.20.92.53\DeptDrives\DisplayContent"
$Extension = ".ppsx"
$ApplicationProcessName = "POWERPNT"
$ApplicationProcess = $null

$repeat = $true
do
{
    $ApplicationProcess = $null




 
    # specify the folder that the PPS files are stored
    set-location $Path
 
    # Get a list of files in the folder
    $Files = Get-ChildItem | ? {$_.name -like "*$Extension"}
 
    # Check if the folder contains any files
    

    if ($Files)
    {

        #Delete Existing temp Files within IE Folder cache
        get-childitem -path C:\Users\DisplayBoardDS\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\ -Include * -recurse | foreach { $_.Delete()}

        # Get the most recent file
        $LatestFile = ($files | select | Sort-Object -Property lastwritetime -Descending)[0]
    

        $importLogFile = Import-Csv C:\filelog.csv

        $ApplicationProcess = Get-Process $ApplicationProcessName -ErrorAction SilentlyContinue

        if ($ApplicationProcess)
        {

            if ($importLogFile.LastWriteTime -eq $LatestFile.LastWriteTime)
            {

                "Do Nothing"
                $LatestFile | export-csv c:\filelog.csv -NoTypeInformation

            }
            else
            {
               
                # close the program gracefully
                Get-Process $ApplicationProcessName | %{ $_.closemainwindow() }  
                        
     
                # Start the file
                Start-Process -FilePath $LatestFile.FullName
                $LatestFile | export-csv c:\filelog.csv -NoTypeInformation

            }

        }
        else
        {
            Start-Process -FilePath $LatestFile.FullName
            $LatestFile | export-csv c:\filelog.csv -NoTypeInformation
        }
    }
    else
    {
        #DO NOTHING
    }

Start-Sleep -Seconds 20
}
while ($repeat -eq $true)

Open in new window

LVL 2
peggiegregAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
Did you check if C:\filelog.csv is correct? The import might fail, contain nothing, or something similar. The export/import part is the only possible reason I can see.
It is no good idea and (AFAI can see) unnecessary to export and import a date, and it is dangerous as the export can only be done as formatted text - prone to errors on compare etc. I would just keep the variable, assign $LatestFile to it in the loop as last action, as you are running an endless loop anyway.
0
peggiegregAuthor Commented:
@Qlemo - thank you for the advise i will try using variables like $latestFile. the only reason i used the CSV file is because sometimes the machine will be restarted or the script will have to stop running. on startup i want it to carry out from the last file it recorded.

i have checked and the filelog.csv is correct and gets updated but think i have just found the issue. it cant read the CSV straight away as it is being used by another process. I am not sure why this is happening. so after 20 seconds I see this:

PSError.JPG
any ideas why this is happening?
0
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
It can't be something resulting from this script. Maybe it runs twice, an antivirus application keeps a grip on the file for analysis (unlikely after 20 seconds), or something more obscure happening. You should not have any issue overwriting your CSV file here.

For now, my recommendation is to only import the CSV file content if $importLogFile is empty (not set), and then only keep the timestamp (explicitly converting it from string to date). Whether to export the file object or only the timestamp too depends on whether you need to see the last file name used for e.g. debugging. Anyway, keep the export.
That way you use the correct date format internally, rely on that, and the exported file does only matter for complete restarts of the script.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

David Johnson, CD, MVPOwnerCommented:
why are you not using a filewatcher
$folder = 'c:\scripts\test' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"


# To stop the monitoring, run the following commands:
# 
# Unregister-Event FileCreated
#

Open in new window

0
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
That would work, if combined with the action of kill and restart of PowerPoint (instead of just logging the change).
0
David Johnson, CD, MVPOwnerCommented:
Unregister-Event FileCreated -ErrorAction SilentlyContinue
#$Path = 'c:\temp\1\' 
$Path = "\\10.20.92.53\DeptDrives\DisplayContent" # Path to monitor
$ApplicationProcessName = 'POWERPNT'
$ApplicationProcess = $null

$filter = '*.ppsx'  # You can enter a wildcard filter here.
#$filter = '*.pptx'
$fsw = New-Object IO.FileSystemWatcher $path, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent -InputObject $fsw -EventName Created -SourceIdentifier FileCreated -Action {
    $LatestFile = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$LatestFile' was $changeType at $timeStamp" -fore green
    Out-File -FilePath c:\temp\outlog.txt -Append -InputObject "The file '$LatestFile' was $changeType at $timeStamp"
    #Delete Existing temp Files within IE Folder cache
    get-childitem -path C:\Users\DisplayBoardDS\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\ -Include * -recurse | ForEach-Object -Process { $_.Delete()}
    # Is PowerPoint Running?
    $ApplicationProcess = Get-Process $ApplicationProcessName -ErrorAction SilentlyContinue
    if ($ApplicationProcess)
    {
      # Yes,close the program gracefully
           $ApplicationProcess.closemainwindow()  
           Start-Sleep -Seconds 5 
    }
    $LatestFileWithPath = (Get-ChildItem -Path $Path -Filter $LatestFile).FullName
        write-host($LatestFilewithpath)
        Start-Process -FilePath $LatestFileWithPath -ErrorAction SilentlyContinue
  }

Open in new window

0
peggiegregAuthor Commented:
this is now sorted. the main reason it would not work is due to the doing a compare rather than a match. when i compare the dates in question they appear the same on face value but if you get the milliseconds you can see they are slightly out. this is why the statement says False and therefore doesn't proceed.

if you do a match rather than compare then the value is only compared down to seconds not milliseconds and therefore it says true.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.