Home

Friday, July 13, 2018

PowerShell - Learning - Entry 1

Proof of connect for an application. This is the Main loop based on an event trigger. When new files are added to a watched directory the application will act on the file to extract useful information and propagate that to an application window for ease of viewing.

Writing the code in Sublime text 3, because it's just that great. and test running in PowerShell ISE.


#Clean up on New Run or on application Exit
if($MainLoopEvent){
    Unregister-Event $MainLoopEvent -Force
    Stop-Job $MainLoopEvent
}

##

#Dummy Data
$SearchPath="$env:USERPROFILE\Desktop"
$SubDir=$false
$MainLoopAction ={
   Get-NewSource
   Update-DataObj
   Update-AppUi
   Send-Notice
}

##
# "*.*" = All, "*." Directory
Function Make-Watcher($searchPath="$env:USERPROFILE\Desktop",$Filter="*.*", $subDir=$false) {
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = $searchPath
    $watcher.Filter = $Filter
    $watcher.IncludeSubdirectories = $subDir
    $watcher.EnableRaisingEvents = $true
    return $watcher
}

##
Function Set-WatchEvent($Object=$null,$Event="Created",$Action) {
    # Deleted, Renamed, Changed, Created; $changed = Register-ObjectEvent $watcher "Changed" -Action { write-host "Changed: $($eventArgs.FullPath)" }
    if($Object -ne $null){
        $created = Register-ObjectEvent $Object $Event -Action $Action #https://superuser.com/questions/888442/powershell-folder-monitor-batch-execution
            #$action = {Invoke-Item "D:\BATCH FILES\XXXXX.bat" -filter = "XXXXX.pdf"}
        #while ($true) {sleep 5} #Only works if external job
        return $created
    }
}

#Test Functionality
$watcher = Make-Watcher
$MainLoopEvent = Set-WatchEvent $watcher -Action $MainLoopAction

##

##

Function Send-Notice ($title="TestTracker Report",$msg="You have a waiting Action. Please Approve the Action.",$bttn='ok',$icon='Exclamation') {
    # MSDN Icon Table: https://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxicon(v=vs.110).aspx
    # TODO: Change frame, change icon to custom, change color; background, header, text
    #$wshell = New-Object -ComObject Wscript.Shell ##$wshell.Popup("Operation Completed",0,"Done",0x1)
    [System.Windows.Forms.MessageBox]::Show($msg,$title,$bttn,$icon) 
}

Function Get-NewSource {
    Write-Host (`
    "`n### `$newSource = Get-Content -Raw -Path `"`$env:USERPROFILE\Desktop\...`"",
    "`$newJson = ConvertFrom-Json `$newSource",
    "return `$newJson")
}

Function Update-DataObj {
    Write-Host "`n### DataObj = NewSourceData"
}

Function Update-AppUi {
    Write-Host "`n### AppUI = UpdatedDataObj"
}

##

No comments:

Post a Comment

Conduct: Be nice and don't advertise or plug without adding value to the conversation.