Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host #This will Break the Webcall scripts
#https://stackoverflow.com/questions/47542628/cannot-convert-argument-second-time-in-powershell
#https://www.slipstick.com/developer/change-programmatic-access-options/

#$proxy = New-WebServiceProxy -uri "http://localhost:8080/API.asmx?WSDL" -namespace "com.api" -class "MyProxyClass"
#$proxy = New-WebServiceProxy -uri "http://localhost:8080/API.asmx?WSDL" -namespace "MyPortal" -class "MyProxyClass"




# load the required .NET types
Add-Type -AssemblyName 'Microsoft.Office.Interop.Outlook'

$GCalenderItems = $null  #Makes global Car
$End = (Get-Date).AddDays(14).ToShortDateString()
$Start = (Get-Date).AddDays(-14).ToShortDateString()

Function Get-OutlookCalendar
{
    # access Outlook object model
    $outlook = New-Object -ComObject outlook.application

    # connect to the appropriate location
    $namespace = $outlook.GetNameSpace('MAPI')
    $Calendar = [Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderCalendar


    $Filter = "[MessageClass]='IPM.Appointment' and [IsRecurring] = '$False' AND [Start] > '$Start' AND [Start] < '$End'" # AND [End] < '$End'" #AND [Start] > '$Start' AND [End] < '$End'"


    $CalenderItems = $namespace.getDefaultFolder($Calendar).Items.Restrict($Filter)
    $CalenderItems | Select-Object -Property Start, Subject
    write-host "There are $($CalenderItems.Count) calendar entries. Fetching between $($start) and $($end)"    

    #write-host "There are $($CalenderItems.Items.Count) calendar entries. Fetching between $($start) and $($end)"    
    #$folder
    #$CalenderItems | Select-Object -Property Start, End, Categories, Subject, IsRecurring, Organizer
    #$folder | gm

    return $CalenderItems
    #$dataToReturn = $folder.Items.Restrict($Filter) # | Select-Object -Property Start, End, Categories, Subject, IsRecurring, Organizer
    $folder.items | Select-Object -Property Start, Categories, Subject, IsRecurring, Organizer
    $data = $folder.items | Select-Object -Property Start, Categories, Subject, IsRecurring, Organizer
    $data | Where-Object ($_.Subject -ne "!@#!#!$") 
    $cal = $data | Where-Object ($_Subject -CContains "paceart")
    write-host "Completed"
}

$GCalenderItems = Get-OutlookCalendar

function add-appointment(){
<#
.SYNOPSIS
Creates and appointment in outlook
.DESCRIPTION
Creates an appointment in outlook in the default calendar folder
.PARAMETER TimeDate
Time and Date of the appointment. Multiple formats are accepted. Please use the one common to your region. It will create the appointment for today if no date is specified. 
.PARAMETER Location 
The message to be send.
.PARAMETER ReminderMinutesBeforeStart
Sets when to send reminder for appointment. Default is 15 minutes. 1440 minutes are in a day and 10080 minutes in a week. Set it to 0 for no reminders.
.PARAMETER Subject
The subject of the appointment.
.EXAMPLE
add-appointment -TimeDate "1/4/2015 4:30 pm" -Subject "Little Mermaid" -location "Cameo Theater" -ReminderMinutesBeforeStart 0
This example adds a appointment on 1/4/2015 at 4:30 PM with subject Little mermaid and no reminder.  
.NOTES
Requires Windows PowerShell v2 or later and Microsoft Office Outlook 2010 or later.
Outlook cannot be running when running this script.Some versions of Outlook will not close the session. Please go to taskbar and close manually in that case.  
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
$TimeDate, 
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
$Subject ,
$location,
[int]$ReminderMinutesBeforeStart = "15"
)
    $AppointmentTime = get-date $Timedate
    #Check whether Outlook is installed
    if (-not (Test-Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE")) {
    Write-Warning "Outlook is not installed. You need to install Outlook 2010 or later to use this Script."
    break
    }

    #Check if Outlook is running. 
    $OutlookState = Get-Process | Where-Object {$_.Name -eq "outlook"}
    if ($OutlookState) 
    {
        Write-Warning "Outlook is running. Please close outlook to run this script"
        break
    }
    $outlook = new-object -com Outlook.Application
    $calendar = $outlook.Session.GetDefaultFolder(9) # == olFolderCalendar 
    $appt = $calendar.Items.Add(1) # == olAppointmentItem 
    $appt.Start = [datetime]$AppointmentTime
    $appt.Subject = $subject
    $appt.Location = $location
    $appt.ReminderSet = $true
    $appt.ReminderMinutesBeforeStart =$ReminderMinutesBeforeStart
    $appt.Save() 
    $outlook.Quit() 
}



if ( !(Test-Path variable:proxy) )
{
    $proxy = New-WebServiceProxy -uri "https://MyPortal/API.asmx?WSDL" -namespace "MyPortal" -UseDefaultCredential
    #$proxy = New-WebServiceProxy -uri "http://localhost:8080/API.asmx" -namespace "MyPortal" -UseDefaultCredential
}


function AdvanceSearch-appointment(){
    $Outlook = New-Object -ComObject Outlook.Application  
    Unregister-Event *
    Register-ObjectEvent -InputObject $Outlook -EventName "AdvancedSearchComplete" -Action {
        Write-Host "ADVANCED SEARCH COMPLETE" $Args.Scope "Results: " $Args.Results

        if ($Args.Results) {  
            foreach ($result in $Args.Results) {
                write-host "=================================================="
                write-host $result.Subject
                write-host $result.ReceivedTime
                write-host $result.SenderName
                write-host "=================================================="
            }
        }
    }
    #$olFolders = “Microsoft.Office.Interop.Outlook.OlDefaultFolders” -as [type]
    $olFolders = [Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderCalendar
    $NameSpace = $Outlook.GetNameSpace(“MAPI”)
    #$Scope = $NameSpace.getDefaultFolder($olFolders::olFolderCalendar) #'Inbox'
    $Scope =  'Inbox' #$NameSpace.getDefaultFolder($olFolders) #'Inbox' #'Calendar'
    $Emails = $Outlook.AdvancedSearch( $Scope, "", $true ) #urn:schemas:calendar:subject != '%'
    #$Emails
}

$person = New-Object "MyPortal.ThePerson";
$person.FirstName = "Frederick";
$person.LastName = "DebYouSee";


$Command = New-Object "MyPortal.SystemChange";
$Command = $proxy.Jira_QueryAllOpenChangeControlsThisWeek(50);

$ol = New-Object -ComObject Outlook.Application;
$meeting = $ol.CreateItem('olAppointmentItem');
$calendar = $ol.Session.GetDefaultFolder(9) # == olFolderCalendar 
:nextCalendarItem foreach($file in $Command)
{



    [string]$MyTitle = " CC" + $file.Ticket + ": " + $file.summary;

    Write-Host $MyTitle; #$file.Ticket.ToString().Trim() ": " $file.summary.ToString().Trim();

    #$GCalenderItems | Select-Object -Property Start, Subject
    foreach ($result in $GCalenderItems) 
    {
        if ($result.Subject -like $MyTitle)
        {
            write-host "=================================================="
            write-host $result.Start
            write-host $result.End
            write-host $result.Subject
            write-host "=================================================="
            continue nextCalendarItem;
        }
    }

    Write-Host $file.PlannedStartDate;
    Write-Host $file.PlannedEndDate;



    $meeting.Subject = "$MyTitle";

    $meeting.Body = $file.description;
    $meeting.Categories = "ChangeControlReminder";
    $meeting.Location = 'Change Control Reminder';
    $meeting.ReminderSet = $true;
    $meeting.Importance = 1;
    $meeting.MeetingStatus = [Microsoft.Office.Interop.Outlook.OlMeetingStatus]::olMeeting
    #$meeting.Recipients.Add('mjones@contoso.net')
    $meeting.ReminderMinutesBeforeStart = 15 

    $StartDate = [DateTime]::Parse($file.PlannedStartDate, [System.Globalization.CultureInfo]::InvariantCulture); #$file.PlannedStartDate#DateTime.Parse() #System.Globalization.CultureInfo.InvariantCulture
    $EndDate = [DateTime]::Parse($file.PlannedEndDate, [System.Globalization.CultureInfo]::InvariantCulture); #$file.PlannedStartDate#DateTime.Parse() #System.Globalization.CultureInfo.InvariantCulture
    $duration = $EndDate - $StartDate

    $meeting.Start = $StartDate
    if ($duration.TotalHours -gt 8)
    {
        $meeting.Duration = 30
    }
    else
    {
        $meeting.Duration = $duration.TotalMinutes
    }
    #$meeting.Send()


    $appt = $calendar.Items.Add(1) # == olAppointmentItem 
    $appt.Start = $StartDate;

    if ($duration.TotalHours -gt 8)
    {
        $appt.Duration = 30
    }
    else
    {
        $appt.Duration = $duration.TotalMinutes
    }

    $appt.Subject = "$MyTitle";
    $appt.Body = $file.description;
    $appt.Location = $location;
    $appt.Categories = "ChangeControlReminder";
    $appt.Location = 'Change Control Reminder';
    $appt | gm
    $appt.ReminderSet = $false;
    $appt.Importance = 1;
    $appt.BusyStatus = [Microsoft.Office.Interop.Outlook.OlBusyStatus]::olFree;
    $appt.ReminderMinutesBeforeStart = $ReminderMinutesBeforeStart;
    $appt.Save();
}

#Invoke-Expression $Command;

#$proxy.Dispose(); #You must dispose of the proxy IN YOUR SCRIPT, powershell will not do it for you!

Leave a Reply

Your email address will not be published. Required fields are marked *