4
\$\begingroup\$

I have a GUI file which is currently being ran by VBS, but I have a few issues:

PowerShell v2 is what is being run on every machine and I cant change that, runs very slow on first time launch. it takes about 10secs then my .ps1 will run, which can take another 10secs depending on the speed, but on second run it loads promptly, but this program shouldn't be run twice.

Is there anything I can consider adding to avoid doing what it does at the beginning?

My other issue which is a related to the first part, I have just started to program and was hoping someone can have a look at my code to remove unnecessary code that can slow the program from loading.

I have a few important information on it so i would need to remove most stuff, like server details, which wont make it run. I hope its OK.

try{

# Solves issue to determine if powershell is running Single threaded appartment (STA) or Multi threaded appartment (MTA)
# some com-objects don't work in MTA such as webbrowser in our case.
# https://social.technet.microsoft.com/Forums/office/en-US/4d19737b-8fa8-4696-b4f8-d1afa03f2b47/singol-thread-error-sta-when-open-script-by-powershell?forum=ITCG

if ([System.Threading.Thread]::CurrentThread.ApartmentState -eq [System.Threading.ApartmentState]::MTA)
{
    powershell.exe -Sta -File $MyInvocation.MyCommand.Path
    return
}

# loading message
cp "\\10.10.67.173\Templates$\Scripts\Resources\LoadingPrompt.hta" "c:\temp"
C:\temp\LoadingPrompt.hta

###########Control Console Window####################
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Show-Console {
   $consolePtr = [Console.Window]::GetConsoleWindow()
   #5 show
   [Console.Window]::ShowWindow($consolePtr, 5)
}
function Hide-Console {
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}
####################################################

# Initial Load functions
Function GetUsername{
    # Gets username of logged in user
    $global:username = $env:username

    # Go get employeeID
    GetEmployeeID
}
Function GetEmployeeID{
    # Get employeeid via ADSI not getaduser
    $strFilter = "(&(objectCategory=User)(samaccountname=$username))"
    $root = [ADSI]"LDAP://" 
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry
    $search = new-Object System.DirectoryServices.DirectorySearcher
    $search.SearchRoot = $objDomain
    $Search.Filter = $strFilter
    $Search.SearchScope = "Subtree"
    $Results = $search.findAll()
    ForEach ($Result In $Results){
        $Global:EmployeeID = $Result.Properties.employeeid
        #$Global:EmployeeID = "0000076776"
    }
}
Function GetArgosDetails{
    # Get the users details from Argos
    $adOpenStatic = 3
    $adLockOptimistic = 3
    $ArgosID = "PERSONNE____________$employeeID"
    $objConnection = New-Object -comobject ADODB.Connection
    $objRecordset = New-Object -comobject ADODB.Recordset

    # Connection to the server
    $objConnection.Open("server details")

    # Check if the connection was established
    if($objConnection.state -eq 0){
        # Could not establish connection
        write-host 'Could not establish connection to Argos, please try again later.'
    }
    else{
        # Searching for specific criteria
        $objRecordSet.Open("SELECT * FROM view_pgcd WHERE (IdPersonne LIKE '$ArgosID')", $objConnection, $adOpenStatic, $adLockOptimistic)              
        # Check if data was found
        if($objRecordset.EOF -eq $True){
            # No Data found
            write-host 'Cannot find details matching in Argos'
        }
        else{
            # Get and set data
            $objRecordset.MoveFirst()
            try{$global:lastName = $objRecordset.Fields.Item("Nom").Value } catch{$global:lastName = ""} 
            try{$global:firstName = $objRecordset.Fields.Item("Prenom").Value   } catch{$global:firstName = ""}    
            try{$global:Department = $objRecordset.Fields.Item("affectation").Value  } catch{$global:Department = ""} 
            try{$global:Company = $objRecordset.Fields.Item("employeur").Value } catch{$global:Company = ""} 
            try{$global:addressSiteName = $objRecordset.Fields.Item("NomSite").Value } catch{$global:addressSiteName = ""} 
            try{$global:addressBuilding = $objRecordset.Fields.Item("Voie").Value } catch{$global:addressBuilding = ""} 
            try{$global:addressStreet = $objRecordset.Fields.Item("Complement").Value } catch{$global:addressStreet = ""} 
            try{$global:addressTown = $objRecordset.Fields.Item("Ville").Value } catch{$global:addressTown = ""} 
            try{$global:addressPostcode = $objRecordset.Fields.Item("CodePostal").Value } catch{$global:addressPostcode = ""} 
            try{$global:EmailAddress = $objRecordset.Fields.Item("mail").Value} catch{$global:EmailAddress = ""} 
            try{$global:Landline = $objRecordset.Fields.Item("telFixe").Value } catch{$global:Landline = ""} 
            try{$global:Mobile = $objRecordset.Fields.Item("telMobile").Value } catch{$global:Mobile = ""} 
            try{$global:PrimaryAssignment = $objRecordset.Fields.Item("Affectation").Value} catch{$global:PrimaryAssignment = ""} 
            $objRecordset.Close()
        }
        # Searching for specific criteria
        $objRecordSet.Open("SELECT * FROM view_personne_org_fonction WHERE ((IdPersonne LIKE '$ArgosID') AND (TypeRelation LIKE 'M') AND (LibelleFonction NOT LIKE ''))", $objConnection, $adOpenStatic, $adLockOptimistic)              
        # Check if data was found
        if($objRecordset.EOF -eq $True){
            # No Data found
            write-host 'Cannot find any details regarding Jobtitle or Department.'
            $global:jobtitle = ""
        }
        else{
            # Get and set data
            try{$global:jobtitle = $objRecordset.Fields.Item("LibelleFonction").Value} catch{$global:jobtitle = ""}  
            #$global:Department = $objRecordset.Fields.Item("organisation").Value  
        }
    }
    # Close connections
    $objRecordset.Close()
    $objConnection.Close()
}

# Determine Company based on Argos user
Function DetermineCompany{
    # Function is based on the user who is logged on.
    switch("$Company"){
        "Bouygues UK"{
        $global:sigcompany = "BYUK"
            If(((Import-Csv $csvAssignmentTVL -Delimiter ";") -match $PrimaryAssignment) -and ($PrimaryAssignment -notlike "")){

                $global:sigcompany = "TVL"
            }
            else{
                $global:sigcompany = "BYUK"
            }     
        }# Company
        #"BOUYGUES DEVELOPMENT"{$global:sigcompany = "BYUK"} # Company
        "Bouygues E&S FM UK"{$global:sigcompany = "BYES"}
        "Bouygues Energies & Services"{$global:sigcompany = "BYES"}
        "Bouygues E&S UK"{$global:sigcompany = "BYES"}
        #"LEADBITTER"{$global:sigcompany = "Leadbitter"}
        #"THOMAS VALE"{$global:sigcompany = "TVL"}# Company
        "STRUCTIS UK"{$global:sigcompany = "BYES"}
        default {"Cannot Determine the Company - Will Set to Default: Bouygues UK"
         $global:sigcompany = "BYUK"}
    }
}

Function DetermineUsernameCompany{
    # Function is based on the username given.
    switch($sigcompany){
        "BYUK"{$global:sigusernamecompany = "Bouygues UK"}
        "TVL"{$global:sigusernamecompany = "Thomas Vale"}
        "BYES"{$global:sigusernamecompany = "Bouygues Energies & Services"}
        "Structis UK"{$global:sigusernamecompany = "Bouygues Energies & Services"}
        "Structis"{$global:sigusernamecompany = "Bouygues Energies & Services"}
        default {"error - oh no3"}
    }
}

# Transfers From Server to TEMP
Function TransferTemplate{
    # Determine the company template to use
    Switch($sigcompany){
        "BYUK" {$global:path = "\\10.10.67.173\Templates$\Templates\BYUK\"} 
        "BYUKDEV" {$global:path = "\\10.10.67.173\Templates$\Templates\BYUKDEV"} 
        "Denne" {$global:path = "\\10.10.67.173\Templates$\Templates\Denne"} 
        "Leadbitter" {$global:path = "\\10.10.67.173\Templates$\Templates\Leadbitter"} 
        "TVL" {$global:path = "\\10.10.67.173\Templates$\Templates\TVL"} 
        "BYES" {$global:path = "\\10.10.67.173\Templates$\Templates\BYES"} 
        "STUK" {$global:path = "\\10.10.67.173\Templates$\Templates\BYES"} 
        default {"Please Choose the appropriate company."}
    }
    # Create a temp folder to store the html to be modified
    $Global:tempdest = "C:\Temp\Template"
    $check = Test-Path -PathType Container $tempdest
    if($check -eq $false){
        New-Item "$tempdest" -type Directory
    }
    # Transfer template to temp data
    mkdir $tempdest -Force >> $null
    $objShell = New-Object -ComObject 'Shell.Application'
    $objFolder = $objShell.NameSpace($tempdest)
    $objFolder.copyhere($path,0x310)
    # Make Copy of template from temp location 
    $Global:ctempdest = "C:\Temp\Template\$($sigcompany)copy"
        $check = Test-Path -PathType Container $ctempdest
        if($check -eq $false){
            New-Item "$ctempdest" -type Directory
        }
        $objShell = New-Object -ComObject 'Shell.Application'
        $objFolder = $objShell.NameSpace($ctempdest)
        $objectfolder2 = $objshell.Namespace("$tempdest\$sigcompany")
    $objFolder.copyhere($objectfolder2.Items(),0x310)
}

# Makes copy of file from Server
Function UseApprTemplate{
    # Replace accordingly
    switch ($sigcompany){ 
        "BYES" {BYES} 
        "BYUK" {BYUK}
        "BYUKDEV" {BYUKDEV} 
        "Denne" {Denne}
        "Leadbitter" {Leadbitter} 
        "TVL" {TVL}
        "STUK" {BYUK} 
        default {"Please Choose the appropriate company."}
    }
}

# Template Replacememts
Function Defaultreplace ($var){
    $wholeline = "<td width=19 style=`'width:14.4pt;padding:1.5pt 0cm 1.5pt 0cm`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; mso-fareast-language:EN-GB;mso-no-proof:yes`'><!--[if gte vml 1]><v:shapetype id=`"_x0000_t75`" coordsize=`"21600,21600`" o:spt=`"75`" o:preferrelative=`"t`" path=`"m@4@5l@4@11@9@11@9@5xe`" filled=`"f`" stroked=`"f`"> <v:stroke joinstyle=`"miter`"/> <v:formulas> <v:f eqn=`"if lineDrawn pixelLineWidth 0`"/> <v:f eqn=`"sum @0 1 0`"/> <v:f eqn=`"sum 0 0 @1`"/> <v:f eqn=`"prod @2 1 2`"/> <v:f eqn=`"prod @3 21600 pixelWidth`"/> <v:f eqn=`"prod @3 21600 pixelHeight`"/> <v:f eqn=`"sum @0 0 1`"/> <v:f eqn=`"prod @6 1 2`"/> <v:f eqn=`"prod @7 21600 pixelWidth`"/> <v:f eqn=`"sum @8 21600 0`"/> <v:f eqn=`"prod @7 21600 pixelHeight`"/> <v:f eqn=`"sum @10 21600 0`"/> </v:formulas> <v:path o:extrusionok=`"f`" gradientshapeok=`"t`" o:connecttype=`"rect`"/> <o:lock v:ext=`"edit`" aspectratio=`"t`"/> </v:shapetype><v:shape id=`"Picture_x0020_5`" o:spid=`"_x0000_i1033`" type=`"#_x0000_t75`" style=`'width:12pt;height:12pt;visibility:visible; mso-wrap-style:square`'> <v:imagedata src=`"newBYUKSig_files/image001.jpg`" o:title=`"`"/> </v:shape><![endif]--><![if !vml]><img width=16 height=16 src=`"newBYUKSig_files/image001.jpg`" v:shapes=`"Picture_x0020_5`"><![endif]></span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td> <td width=112 style=`'width:83.65pt;padding:1.5pt 1.5pt 1.5pt 1.5pt`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; color:#262626;mso-themecolor:text1;mso-themetint:217`'>TELE</span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td> <td width=19 style=`'width:14.15pt;padding:1.5pt 0cm 1.5pt 0cm`'> <p class=MsoNormal align=right style=`'margin-bottom:0cm;margin-bottom: .0001pt;text-align:right;line-height:normal`'><span style=`'font-size: 9.0pt;font-family:`"Tahoma`",sans-serif;mso-fareast-language:EN-GB; mso-no-proof:yes`'><!--[if gte vml 1]><v:shape id=`"Picture_x0020_6`" o:spid=`"_x0000_i1032`" type=`"#_x0000_t75`" style=`'width:8.25pt; height:13.5pt;visibility:visible;mso-wrap-style:square`'> <v:imagedata src=`"newBYUKSig_files/image002.jpg`" o:title=`"`"/> </v:shape><![endif]--><![if !vml]><img width=11 height=18 src=`"newBYUKSig_files/image002.jpg`" v:shapes=`"Picture_x0020_6`"><![endif]></span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td> <td width=121 style=`'width:90.7pt;padding:1.5pt 1.5pt 1.5pt 1.5pt`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; color:#262626;mso-themecolor:text1;mso-themetint:217`'>MOB</span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td>"
    $tele_line = "<td width=19 style=`'width:14.4pt;padding:1.5pt 0cm 1.5pt 0cm`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; mso-fareast-language:EN-GB;mso-no-proof:yes`'><!--[if gte vml 1]><v:shapetype id=`"_x0000_t75`" coordsize=`"21600,21600`" o:spt=`"75`" o:preferrelative=`"t`" path=`"m@4@5l@4@11@9@11@9@5xe`" filled=`"f`" stroked=`"f`"> <v:stroke joinstyle=`"miter`"/> <v:formulas> <v:f eqn=`"if lineDrawn pixelLineWidth 0`"/> <v:f eqn=`"sum @0 1 0`"/> <v:f eqn=`"sum 0 0 @1`"/> <v:f eqn=`"prod @2 1 2`"/> <v:f eqn=`"prod @3 21600 pixelWidth`"/> <v:f eqn=`"prod @3 21600 pixelHeight`"/> <v:f eqn=`"sum @0 0 1`"/> <v:f eqn=`"prod @6 1 2`"/> <v:f eqn=`"prod @7 21600 pixelWidth`"/> <v:f eqn=`"sum @8 21600 0`"/> <v:f eqn=`"prod @7 21600 pixelHeight`"/> <v:f eqn=`"sum @10 21600 0`"/> </v:formulas> <v:path o:extrusionok=`"f`" gradientshapeok=`"t`" o:connecttype=`"rect`"/> <o:lock v:ext=`"edit`" aspectratio=`"t`"/> </v:shapetype><v:shape id=`"Picture_x0020_5`" o:spid=`"_x0000_i1033`" type=`"#_x0000_t75`" style=`'width:12pt;height:12pt;visibility:visible; mso-wrap-style:square`'> <v:imagedata src=`"newBYUKSig_files/image001.jpg`" o:title=`"`"/> </v:shape><![endif]--><![if !vml]><img width=16 height=16 src=`"newBYUKSig_files/image001.jpg`" v:shapes=`"Picture_x0020_5`"><![endif]></span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td> <td width=112 style=`'width:83.65pt;padding:1.5pt 1.5pt 1.5pt 1.5pt`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; color:#262626;mso-themecolor:text1;mso-themetint:217`'>TELE</span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td>"
    $mob_line =  "<td width=19 style=`'width:14.15pt;padding:1.5pt 0cm 1.5pt 0cm`'> <p class=MsoNormal align=right style=`'margin-bottom:0cm;margin-bottom: .0001pt;text-align:right;line-height:normal`'><span style=`'font-size: 9.0pt;font-family:`"Tahoma`",sans-serif;mso-fareast-language:EN-GB; mso-no-proof:yes`'><!--[if gte vml 1]><v:shape id=`"Picture_x0020_6`" o:spid=`"_x0000_i1032`" type=`"#_x0000_t75`" style=`'width:8.25pt; height:13.5pt;visibility:visible;mso-wrap-style:square`'> <v:imagedata src=`"newBYUKSig_files/image002.jpg`" o:title=`"`"/> </v:shape><![endif]--><![if !vml]><img width=11 height=18 src=`"newBYUKSig_files/image002.jpg`" v:shapes=`"Picture_x0020_6`"><![endif]></span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td> <td width=121 style=`'width:90.7pt;padding:1.5pt 1.5pt 1.5pt 1.5pt`'> <p class=MsoNormal style=`'margin-bottom:0cm;margin-bottom:.0001pt; line-height:normal`'><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif; color:#262626;mso-themecolor:text1;mso-themetint:217`'>MOB</span><span style=`'font-size:9.0pt;font-family:`"Tahoma`",sans-serif`'><o:p></o:p></span></p> </td>"
    $emptyfield = '<TD>&nbsp;</TD><TD>&nbsp;</TD>'

    $var = $var -replace "$tempfirstName",$TextBoxfname.text
    $var = $var -replace "$templastName",$TextBoxlname.text
    $var = $var -replace "$tempPOSITION",$objTextBoxjtitle.text
    if($objComboBoxRD.text -eq "None - Please Leave Blank"){
        $var = $var -replace "$tempMANREGDEPT", " "
    }else{
        $var = $var -replace "$tempMANREGDEPT",$objComboBoxRD.text
    }
    if(($ByukLandline -like "") -and ($ByukMobile -like "")){ # - - 
        Write-host "- -"
        $var = $var-replace[regex]::escape($wholeline), "$emptyfield"
    }elseif(($ByukLandline -like "") -and ($ByukMobile -notlike "")){ # - +
        Write-host "- +"
        $var = $var-replace[regex]::escape($wholeline),$mob_line 
        $var = $var-replace[regex]::escape($tempMOB), "$ByukMobile"
    }elseif(($ByukLandline -notlike "") -and ($ByukMobile -like "")){ # + -
        Write-host "+ -"
        $var = $var-replace[regex]::escape($wholeline), "$tele_line"
        $var = $var-replace[regex]::escape($tempTELE), "$ByukLandline"
    }else{ # + +
        Write-host "+ +"
        $var = $var-replace[regex]::escape($tempTELE), "$ByukLandline"
        $var = $var-replace[regex]::escape($tempMOB), "$ByukMobile"    }
    $var = $var -creplace $tempEMAIL,($TextBoxEmailAddress.text).ToLower() 
    $ByukAddress = "$($TextBoxBuilding.Text) $([char]"|") $($TextBoxStreet.text) $([char]"|") $($TextBoxTown.text) $([char]"|") $($TextBoxPostcode.Text)"
    $var = $var -replace "$tempADDRESS","$ByukAddress"
    return $var
}
Function BYESreplace ($var){
    $var = $var -Creplace 'NAME',"$FullName"#
    $var = $var -replace "$tempPOSITION",$objTextBoxjtitle.text #
    $var = $var -creplace "$tempQUALIFICATION",$TextBoxQUALIFICATION.text
    $var = $var -Creplace "$tempBYESCompany","$sigusernamecompany" 
    $var = $var -replace $TempTELEPHONEMOBILE,$Contact
    $var = $var -creplace $tempEMAIL,($TextBoxEmailAddress.text).ToLower() #
    $var = $var -Creplace $tempWEBSITEADDRESS,"www.bouygues-es.co.uk"
    $var = $var -Creplace "$tempADDRESS","$ByesAddress"#
    return $var
}

Function BYUK{
    # Format Landline
    $Global:Landline = $TextBoxLandline.text
    FormatLandline
    if(($Landline -like $null) -OR ($fLandline -like $null)){
        $Global:ByukLandline = ""
    }
    else{
        $Global:ByukLandline = "$($fLandline)"
    }

    # Format Mobile
    $Global:Mobile = $TextBoxMobile.text
    FormatMobile
        if(($Mobile -like $null) -OR ($fmobile -like $null)){
        $Global:ByukMobile = ""
    }
    else{
        $Global:ByukMobile = "$($fMobile)"
    }

    # Combine the Address
    $Global:ByukAddress = "$($TextBoxBuilding.Text) $([char]"|") $($TextBoxStreet.text) $([char]"|") $($TextBoxTown.text) $([char]"|") $($TextBoxPostcode.Text)"

    # Define the locations for templates
    $global:htmdest = (Get-ChildItem "$ctempdest\$byukhtm.htm").FullName
        $global:rtfdest = (Get-ChildItem "$ctempdest\$byukhtm.rtf").FullName
    $global:textdest = (Get-ChildItem "$ctempdest\$byukhtm.txt").FullName

    $Global:savedhtm = $htmdest
    $Global:sigcompany = "BYUK"
    $Global:defaultsave = $BYUKhtm

    # HTM Replace
    $var = (Get-Content $htmdest)
    (Defaultreplace $var) | set-content $htmdest

    # RTF Replace
    $var = (Get-Content $RTFDEST) 
    (Defaultreplace $var) | set-content $RTFDEST

    # Attempt to set Text file
    "$($TextBoxfname.text) $($TextBoxlname.text)
    $($objTextBoxjtitle.text)
    $($objComboBoxRD.text)`n
    $($TextBoxEmailAddress.text)
    $($ByukLandline)
    $($ByukMobile)
    $($ByukAddress)" -replace("    ","") | set-content $textdest

}
Function Denne{
 #Same as BYUK
}
Function Leadbitter{
 #Same as BYUK

}
Function TVL{
 #Same as BYUK

}
Function BYDEV{
 #Same as BYUK

}
Function BYES{
  #Same as BYUK
   }


#Region - WESTERN, Central, South, South east, (HO)Housing London, (CN)Construction london
Function DetermineRegion{
    #Import data from CSVRegion
    $Global:importRegions = Import-Csv $csvRegion -Delimiter ";"

    #Compare each value from CSV with the Argos deparment/region
    if($importRegions -match $Department){
        #We have a match, fill the Combo box
        ComboBoxRegion
        #Set the Radio button to Region and fill it with Argos Department/Region
        $Global:radiobuttonR.Checked = $true 
        $Global:objComboBoxRD.text = $Department
        $global:R = $true
    }
    else{
        $global:R = $False
    }
}
Function ComboBoxRegion{
    #Clear Combobox of its predified values
    $Global:objComboBoxRD.items.clear() 

    #Clear the text on the combobox - first items shown
    $objComboBoxRD.text = $null

    # Add items to Combo box
    Import-Csv -Delimiter ";" -Path $csvRegion | % {$objComboBoxRD.Items.Add($_.Region)}
    $global:objComboBoxRD.text = $($(Import-Csv -Delimiter ";" -Path $csvRegion)[0] | select -expand Region) 
}

#Detpartment - Communications, legal, HR
Function DetermineDepartment{
    #Import data from CSVRegion
    $Global:importDepartments = Import-Csv $csvDepartment -Delimiter ";" 
    $Department = $Department -replace "BYUK - ", ""
    #Compare each value from CSV with the Argos deparment/region
    if($importDepartments -match $Department){
        #We have a match, fill the Combo box
        ComboBoxDepartment
        #Set the Radio button to Region and fill it with Argos Department/Region
        $Global:radiobuttonD.Checked = $true 
        $Global:objComboBoxRD.text = $Department
        $global:D = $true
    }
    else{
        $global:D = $False
    }
}
Function ComboBoxDepartment{
    #Clear Combobox of its predified values
    $Global:objComboBoxRD.items.clear()

    #Clear the text on the combobox - first items shown
    $objComboBoxRD.text = $Null

    # Add items to Combo box
    Import-Csv -Delimiter ";" -Path $csvDepartment | % {$objComboBoxRD.Items.Add($_.Department)}
    $global:objComboBoxRD.text = $($(Import-Csv -Delimiter ";" -Path $csvDepartment)[0] | select -expand Department)
}

# Address Functions
Function AddressChecked{
    if($Global:radiobuttonArgos.Checked -eq $true ){
        DisableAddressbox
        $objLabelOffice.visible = $false
        $objComboBoxOffice.visible = $false 
        $TextBoxBuilding.Text = $addressBuilding
        $TextBoxStreet.Text = $addressStreet
        $TextBoxTown.Text = $addressTown
        $TextBoxPostcode.Text = $addressPostcode
    }
    if($Global:radiobuttonOffice.Checked -eq $true){
        DisableAddressbox
        $objLabelOffice.visible = $true
        $objComboBoxOffice.visible = $true
        $objComboBoxOffice.items.clear()
        $objComboBoxOffice.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
        # Get the data from the csvOffice - towns
        import-Csv -Delimiter ";" -Path $csvOffice | % {$objComboBoxOffice.Items.Add($_.addressTown)} 
    }
    if($Global:radiobuttonOther.Checked -eq $true){
        EnableAddressbox
        $objLabelOffice.visible = $False
        $objComboBoxOffice.visible = $False 
    }

}
Function EnableAddressbox{
    $TextBoxBuilding.enabled = $True
    $TextBoxStreet.enabled = $True
    $TextBoxTown.enabled = $True
    $TextBoxPostcode.enabled = $True
}
Function DisableAddressbox{
    $TextBoxBuilding.enabled = $false
    $TextBoxStreet.enabled = $false
    $TextBoxTown.enabled = $false
    $TextBoxPostcode.enabled = $false
}
Function ChangeComboOffice{
    # Import from CSV and fill the Combobox
    $importoffice = Import-Csv $csvOffice -Delimiter ";"
    $importoffice -match "$SelectedOffice" | ? {
        $TextBoxBuilding.Text = $_ | select -expand addressBuilding
        $TextBoxStreet.Text = $_ | select -expand addressStreet
        $TextBoxTown.Text = $_ | select -expand addressTown
        $TextBoxPostcode.Text = $_ | select -expand addressPostcode
    }
}

# Format Mobile and Landline
Function FormatMobile{
# Remove +44 from phone numbers
$Mobile = $Mobile -replace "\+44"
$Mobile = $Mobile -replace "\+ 44"
$Mobile = $Mobile -replace "\++44"
$Mobile = $Mobile -replace "\++ 44"
# Strip any undesired characters 
$Mobile = $Mobile -replace "[ ).(-+]"
# Check to see if there is a 0 before the number
if($Mobile -notmatch '^0'){$Mobile = "0$($Mobile)"}

# This uses full codes from http:#www.area-codes.org.uk/formatting.shtml
    switch -regex ("$Mobile"){
    }

}
Function FormatLandline{
}


Function UpdateSignature{

    # Update if there has been a change on Company
    $selectedCompany = $objComboBox.text
    switch("$selectedCompany"){
        "Bouygues UK"{
            if($selectedCompany -eq $tempcompany){
                $Global:tempcompany = $selectedCompany
                Updateandreplace
            }
            else{
                $Global:tempcompany = $selectedCompany
                $Global:sigcompany = "BYUK"
                TransferTemplate
                Updateandreplace
            }
        }
        "Bouygues Energies & Services"{
            if($selectedCompany -eq $tempcompany){ 
                $Global:tempcompany = $selectedCompany
                Updateandreplace
            }
            else{
                $Global:tempcompany = $selectedCompany
                $Global:sigcompany = "BYES"
                TransferTemplate
                Updateandreplace
            }
        }
        "BOUYGUES DEVELOPMENT"{
            if($tempcompany -notlike "$selectedCompany"){            
                $ComboBoxEntity.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
                $ComboBoxEntity.enabled = $false
                TransferTemplate
                $webBrowser1.URL = $htmdest
                $groupboxPreviewPane.Controls.Add($webBrowser1)
            }
        }
        "Thomas Vale"{
            if($selectedCompany -eq $tempcompany){            
                $Global:tempcompany = $selectedCompany
                Updateandreplace
            }
            else{
                $Global:tempcompany = $selectedCompany
                $Global:sigcompany = "TVL"
                TransferTemplate
                Updateandreplace
            }
        }
        "STRUCTIS UK"{
            if($tempcompany -notlike "$selectedCompany"){            
                $ComboBoxEntity.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
                $ComboBoxEntity.enabled = $false
                $Global:sigcompany = "BYES"
                TransferTemplate
                $Global:tempCompany = $objComboBox.text            

                $webBrowser1.URL = $htmdest
                $groupboxPreviewPane.Controls.Add($webBrowser1)
            }
        }
        default {"error - Selected no company for combobox"}
    } 
    $webBrowser1.URL = "$savedhtm"
    $groupboxPreviewPane.Controls.Add($webBrowser1)     
}
Function Updateandreplace{
    MakeTemplateCopy
    UseApprTemplate
    $webBrowser1.URL = "$savedhtm"
    $groupboxPreviewPane.Controls.Add($webBrowser1)
}
Function MakeTemplateCopy{
    # Make Copy of template from temp location 
    $Global:ctempdest = "C:\Temp\Template\$($sigcompany)copy"
        $check = Test-Path -PathType Container $ctempdest
        if($check -eq $false){
            New-Item "$ctempdest" -type Directory
        }
        $objShell = New-Object -ComObject 'Shell.Application'
        $objFolder = $objShell.NameSpace($ctempdest)
        $objectfolder2 = $objshell.Namespace("$tempdest\$sigcompany")
    $objFolder.copyhere($objectfolder2.Items(),0x310)
}

Function onExit{
    $OUTPUT = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to close the application?" , "Status" , 4)  
    if ($OUTPUT -eq "YES" ){
        remove-item "C:\Temp\Template" -Recurse
        remove-item "C:\temp\LoadingPrompt.hta" -Recurse
        $objForm.Close()
    }
    else{     
        # Do Nothing
    }
}


# Validation
Function Validation{
    <#
    #FirstName
    if($TextBoxfname.Text -eq ""){
        $ErrorProviderfn.SetError($TextBoxfname, "Please use 5 Digit Corporate Number")
    }else{
        $ErrorProviderfn.clear()
    }  

    #LastName
    if($TextBoxlname.Text -eq ""){
        $ErrorProviderln.SetError($TextBoxlname, "Please use 5 Digit Corporate Number")
    }else{
        $ErrorProviderln.clear()
    }  
    #>
    #Company 
    if($objComboBox.Text -eq ((Import-Csv -Delimiter ";" -Path "$csvCompany")[0] | select -expand Company)){
        $ErrorProviderco.SetError($objComboBox, "Please use 5 Digit Corporate Number")
    }else{
        $ErrorProviderco.clear()
    }  

    #RDCombo
    if((($objComboBoxRD.Text -eq ((Import-Csv -Delimiter ";" -Path "$csvRegion")[0] | select -expand Region)) -OR ($objComboBoxRD.Text -eq ((Import-Csv -Delimiter ";" -Path "$csvDepartment")[0] | select -expand Department)))){
       #Remove Region or Department if BYES
        if($objComboBox.text -eq "Bouygues Energies & Services"){
            $ErrorProviderrd.clear()
        }
        else
        {
            $ErrorProviderrd.SetError($objComboBoxRD, "Please choose either a Business Area or a Support Service")
        }

    }else{
        $ErrorProviderrd.clear()
    }  

    #JobTitle
    if($objTextBoxjtitle.Text -eq ""){
        $ErrorProviderjt.SetError($objTextBoxjtitle, "Missing Job Title")

    }else{
        $ErrorProviderjt.clear()
    }  

    #Building
    if($TextBoxBuilding.Text -eq ""){
        $ErrorProviderbu.SetError($TextBoxBuilding, "Missing Building Address")
    }else{
        $ErrorProviderbu.clear()
    }  

    #Street
    if($TextBoxStreet.Text -eq ""){
        $ErrorProviderst.SetError($TextBoxStreet, "Missing Street Address")
    }else{
        $ErrorProviderst.clear()
    }  

    #Town
    if($TextBoxTown.Text -eq ""){
        $ErrorProviderto.SetError($TextBoxTown, "Missing Town Address")
    }else{
        $ErrorProviderto.clear()
    }  

    #Postcode
    if($TextBoxPostcode.Text -eq ""){
        $ErrorProviderpc.SetError($TextBoxPostcode, "Missing Postcode Address")
    }else{
        $ErrorProviderpc.clear()
    }  
    <#
    #Mobile
    if($TextBoxMobile.Text -eq ""){
        $ErrorProvidermb.SetError($TextBoxMobile, "If you do not have a Mobile, please ignore")
    }
    else{
        $ErrorProvidermb.clear()
    }  

    #Landline
    if($TextBoxLandline.Text -eq ""){
        $ErrorProviderll.SetError($TextBoxLandline, "If you do not have a Landline, please ignore")
    }
    else{
        $ErrorProviderll.clear()
    }  
    #>
    #Email    
    if($TextBoxEmailAddress.Text -eq ""){
        $ErrorProviderem.SetError($TextBoxEmailAddress, "Missing Email Address")
    }
    else{
        $ErrorProviderem.clear()
    }    
}

################################################START###################################

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

# Create a GUI Form
$Global:objForm = New-Object System.Windows.Forms.Form
$objForm.AutoSize = $true
#$objForm.ControlBox = $false
$objForm.Text = "Signature"
$objForm.StartPosition = "CenterScreen"
$objForm.BackColor = "white"

# Name of Signature htm
$Global:byukhtm = "NewBYUKSig"
$Global:Dennehtm = "NewDenneSig"
$Global:Leadbitterhtm = "newLeadbittersig"
$Global:Tvlhtm = "newTVLsig"
$Global:Bydevhtm = "newBydevsig"
$Global:Byeshtm = "newBYESSig"

# Set CSV locations
$Global:csvRegion = "\\10.10.67.173\Templates$\Scripts\Documents\Region.csv"
$Global:csvOffice = "\\10.10.67.173\Templates$\Scripts\Documents\Office.csv"
$Global:csvDepartment = "\\10.10.67.173\Templates$\Scripts\Documents\Department.csv"
$Global:csvCompany = "\\10.10.67.173\Templates$\Scripts\Documents\Company.csv"
$Global:csvProjectOffice = "\\10.10.67.173\Templates$\Scripts\Documents\ProjectOffice.csv"
$Global:csvAssignmentTVL = "\\10.10.67.173\Templates$\Scripts\Documents\AssignmentTVL.csv"

# Set temps data to null.
$Global:tempCompany = ""
$Global:tempRD = ""
$Global:tempOffice = ""

# Set Replaced values
$Global:tempfirstName = "firstName"
$Global:templastName = "lastName"
$Global:tempPOSITION = "POSITION"
$Global:tempMANREGDEPT = "MANREGDEPT"
$Global:tempTELE = "TELE"
$Global:tempMOB = "MOB"
$Global:tempEMAIL = "EMAIL"
$Global:tempADDRESS = "ADDRESS"

$Global:tempBYESCompany = "COMPANY"
$Global:tempQUALIFICATION = "QUALIFICATION"
$Global:tempWEBSITEADDRESS = "WEBSITEADDRESS"
$Global:tempTELEPHONEMOBILE = "TELEPHONEMOBILE"

# Define ErrorProviders 
$Global:ErrorProviderfn = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderln = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderco = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderrd = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderjt = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderbu = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderst = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderto = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderpc = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderof = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProvidermb = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderll = New-Object System.Windows.Forms.ErrorProvider
$Global:ErrorProviderem = New-Object System.Windows.Forms.ErrorProvider

###########################################################################

# Link to Toolbar: https://adminscache.wordpress.com/2014/08/03/powershell-winforms-menu/
#TOOLBAR MENU
$statusLabel = New-Object System.Windows.Forms.ToolStripStatusLabel
$file2 = (Get-item "\\10.10.67.173\Templates$\Scripts\Resources\Structis.png")
$img2 = [System.Drawing.Image]::Fromfile($file2);

$MS_Main = new-object System.Windows.Forms.MenuStrip
$HelpToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$AboutToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$editionToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$GuideToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
# MS_Main
$MS_Main.Items.AddRange(@($HelpToolStripMenuItem))
$MS_Main.Location = new-object System.Drawing.Point(0, 0)
$MS_Main.Name = "MS_Main"
$MS_Main.Size = new-object System.Drawing.Size(354, 20)
$MS_Main.TabIndex = 0
$MS_Main.Text = "menuStrip1"

# Menu Options - Help
$HelpToolStripMenuItem.DropDownItems.AddRange(@(
$AboutToolStripMenuItem,$GuideToolStripMenuItem))
$HelpToolStripMenuItem.Name = "HelpToolStripMenuItem"
$HelpToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$HelpToolStripMenuItem.Text = "&Help"

# Menu Options - Help / About
$AboutToolStripMenuItem.Name = "AboutToolStripMenuItem"
$AboutToolStripMenuItem.Size = new-object System.Drawing.Size(152, 20)
$AboutToolStripMenuItem.Image = [System.Drawing.SystemIcons]::Information
$AboutToolStripMenuItem.Text = "&About"
$AboutToolStripMenuItem.ShortcutKeys = "Control, H"
$AboutToolStripMenuItem.Add_Click({
    $statusLabel.Text = "About"
    # About Form Objects
    $aboutForm          = New-Object System.Windows.Forms.Form
    $aboutFormExit      = New-Object System.Windows.Forms.Button
    $aboutFormImage     = New-Object System.Windows.Forms.PictureBox
    $aboutFormNameLabel = New-Object System.Windows.Forms.Label
    $aboutFormText      = New-Object System.Windows.Forms.Label

    # About Form
    $aboutForm.AcceptButton  = $aboutFormExit
    $aboutForm.CancelButton  = $aboutFormExit
    $aboutForm.BackColor = "white"
    $aboutForm.ClientSize    = "350, 130"
    $aboutForm.ControlBox    = $false
    $aboutForm.ShowInTaskBar = $false
    $aboutForm.StartPosition = "CenterParent"
    $aboutForm.Text          = "About"
    $aboutForm.Add_Load($aboutForm_Load)

    # About PictureBox
    $aboutFormImage.Image    = $img2
    $aboutFormImage.Location = "5, 30"
    $aboutFormImage.SizeMode = "StretchImage"
    $aboutForm.Controls.Add($aboutFormImage)

    # About Text Label
    $aboutFormText.Location = "110, 40"
    $aboutFormText.Size     = "500, 50"
    $aboutFormText.Text     = "Signature Script `n`rCreated By: Visar Baci and John Pearce `n`r Version 1.0"
    $aboutForm.Controls.Add($aboutFormText)

    # About Exit Button
    $aboutFormExit.Location = "135, 90"
    $aboutFormExit.Text     = "OK"
    $aboutForm.Controls.Add($aboutFormExit)
    #$aboutForm.TopMost = $true
    [void]$aboutForm.ShowDialog()
    $statusLabel.Text = "Ready"
})

$GuideToolStripMenuItem.Name = "AboutToolStripMenuItem"
$GuideToolStripMenuItem.Size = new-object System.Drawing.Size(152, 20)
$GuideToolStripMenuItem.Image = [System.Drawing.SystemIcons]::Information
$GuideToolStripMenuItem.Text = "&Guide"
$GuideToolStripMenuItem.ShortcutKeys = "Control, G"
$GuideToolStripMenuItem.Add_Click({Invoke-Item \\10.10.67.173\Templates$\Scripts\Documents\Guide.docx})

$objForm.Controls.Add($MS_Main)
$objForm.MainMenuStrip = $MS_Main

#Initial Load of information: Get users login, Get the users details from Argos, determine company, Transfer the template, Load resources
GetUsername
GetArgosDetails
DetermineCompany
TransferTemplate
DetermineUsernameCompany

#GROUPBOX PREVIEWBOX
$Global:groupboxPreviewPane = New-Object System.Windows.Forms.GroupBox
$groupboxPreviewPane.Location = New-Object System.Drawing.point(50,400) 
$groupboxPreviewPane.size = New-Object System.Drawing.Size(750,180) 
$groupboxPreviewPane.text = "Preview Box" 
$objForm.Controls.Add($groupboxPreviewPane) 

#WEBBROWSER SIGNITURE DISPLAY
$Global:webBrowser1 = New-Object System.Windows.Forms.WebBrowser
$webBrowser1.Location = New-Object System.Drawing.point(5,15) 
$webBrowser1.size = New-Object System.Drawing.Size(730,150) 

#LABELS FISTNAME
# Add a Text label- First Name
$Global:objLabelfname = New-Object System.Windows.Forms.Label
$objLabelfname.Location = New-Object System.Drawing.Size(50,35) #(x,y)
$objLabelfname.Size = New-Object System.Drawing.Size(70,20)
$objLabelfname.Text = "First Name:"
$objForm.Controls.Add($objLabelfname)

#TEXTBOX FIRSTNAME
# Add a text box to the Userform First Name
$Global:TextBoxfname = New-Object System.Windows.Forms.TextBox
$TextBoxfname.Location = New-Object System.Drawing.Point(130,35)
$TextBoxfname.Size = New-Object System.Drawing.Size(200,20)
$TextBoxfname.Text = "$firstName"
$TextBoxfname.enabled = $false
$objForm.Controls.Add($Global:TextBoxfname)

#LABEL LASTNAME
# Add a Text label- Last Name
$Global:objLabellname = New-Object System.Windows.Forms.Label
$objLabellname.Location = New-Object System.Drawing.Size(400,35)
$objLabellname.Size = New-Object System.Drawing.Size(70,20)
$objLabellname.Text = "Last Name:"
$objForm.Controls.Add($objLabellname)

#TEXTBOX LASTNAME
# Add a text box to the Userform Last Name
$Global:TextBoxlname = New-Object System.Windows.Forms.TextBox
$TextBoxlname.Location = New-Object System.Drawing.Point(480,35)
$TextBoxlname.Size = New-Object System.Drawing.Size(200,20)
$TextBoxlname.Text = "$lastName"
$TextBoxlname.enabled = $false
$objForm.Controls.Add($TextBoxlname)

#LABEL COMPANY
# Add a Text label- Company
$Global:objLabelCompany = New-Object System.Windows.Forms.Label
$objLabelCompany.Location = New-Object System.Drawing.Size(50,65) #(x,y)
$objLabelCompany.Size = New-Object System.Drawing.Size(70,20)
$objLabelCompany.Text = "Company:"
$objForm.Controls.Add($objLabelCompany)

#COMBOBOX COMPANY
$Global:objComboBox = New-Object System.Windows.Forms.Combobox
$objComboBox.Location = New-Object System.Drawing.Size(130,65)
$objComboBox.Size = New-Object System.Drawing.Size(200,20)
$objComboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$objComboBox.DropDownHeight = "60"

#Import the Company CSV onto the Combobox
Import-Csv -Delimiter ";" -Path $csvCompany| % {$objComboBox.Items.Add($_.Company)}
$objComboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$objComboBox.text = "$sigusernamecompany"
$sigusernamecompany
$Global:tempCompany = $sigusernamecompany
$objForm.Controls.Add($objComboBox)

# LABEL JOBTITLE
$Global:objLabelJobtitle = New-Object System.Windows.Forms.Label
$objLabelJobtitle.Location = New-Object System.Drawing.Size(400,65)
$objLabelJobtitle.Size = New-Object System.Drawing.Size(70,20)
$objLabelJobtitle.Text = "Job Title:"
$objForm.Controls.Add($objLabelJobtitle)

# TEXTBOX JOBTITLE
$Global:objTextBoxjtitle = New-Object System.Windows.Forms.TextBox
$objTextBoxjtitle.Location = New-Object System.Drawing.Size(480,65)
$objTextBoxjtitle.Size = New-Object System.Drawing.Size(200,20)
$objTextBoxjtitle.Text = "$jobtitle"
$objTextBoxjtitle.enabled = $false
$objForm.Controls.Add($objTextBoxjtitle)

#GROUPBOX QUALIFICATION 
$Global:groupboxQUALIFICATION = New-Object System.Windows.Forms.GroupBox
$groupboxQUALIFICATION.Location = New-Object System.Drawing.Size(50,95) 
$groupboxQUALIFICATION.size = New-Object System.Drawing.Size(325,80) 
$groupboxQUALIFICATION.text = "Qualification" 
$objForm.Controls.Add($groupboxQUALIFICATION) 
$groupboxQUALIFICATION.visible = $false

#RADIOBUTTON QUALIFICATIONMANUAL
$Global:radiobuttonQMANUAL = New-Object System.Windows.Forms.RadioButton 
$radiobuttonQMANUAL.Location = new-object System.Drawing.Point(15,15) 
$radiobuttonQMANUAL.size = New-Object System.Drawing.Size(130,20) 
$radiobuttonQMANUAL.Text = "Manual Entry" 
$radiobuttonQMANUAL.checked = $True
$groupboxQUALIFICATION.Controls.Add($radiobuttonQMANUAL)

#RADIOBUTTON QUALIFICATION NONE
$Global:radiobuttonQNONE = New-Object System.Windows.Forms.RadioButton
$radiobuttonQNONE.Location = new-object System.Drawing.Point(150,15)
$radiobuttonQNONE.size = New-Object System.Drawing.Size(120,20)
$radiobuttonQNONE.Text = "None"
$groupboxQUALIFICATION.Controls.Add($radiobuttonQNONE)

#TEXTBOX QUALIFICATION
$Global:TextBoxQUALIFICATION = New-Object System.Windows.Forms.TextBox
$TextBoxQUALIFICATION.Location = New-Object System.Drawing.Size(15,45)
$TextBoxQUALIFICATION.Size = New-Object System.Drawing.Size(280,20)
$TextBoxQUALIFICATION.Text = " "
$TextBoxQUALIFICATION.enabled = $true
$groupboxQUALIFICATION.Controls.Add($TextBoxQUALIFICATION)

#GROUPBOX Regions/Department 
$Global:groupboxRD = New-Object System.Windows.Forms.GroupBox
$groupboxRD.Location = New-Object System.Drawing.Size(50,95) 
$groupboxRD.size = New-Object System.Drawing.Size(325,80) 
$groupboxRD.text = "Business Area/Support Sevice" 
$objForm.Controls.Add($groupboxRD) 
$groupboxRD.visible = $false

#RADIOBUTTON REGION 
$Global:radiobuttonR = New-Object System.Windows.Forms.RadioButton 
$radiobuttonR.Location = new-object System.Drawing.Point(15,15) 
$radiobuttonR.size = New-Object System.Drawing.Size(120,20) 
$radiobuttonR.Text = "Business Area" 
$groupboxRD.Controls.Add($radiobuttonR)

#RADIOBUTTON DEPARTMENT
$Global:radiobuttonD = New-Object System.Windows.Forms.RadioButton
$radiobuttonD.Location = new-object System.Drawing.Point(150,15)
$radiobuttonD.size = New-Object System.Drawing.Size(120,20)
$radiobuttonD.Text = "Support Service"
$groupboxRD.Controls.Add($radiobuttonD)

#COMBOXBOX Region/Department
$Global:objComboBoxRD = New-Object System.Windows.Forms.Combobox 
$objComboBoxRD.Location = New-Object System.Drawing.Point(15,45)
$objComboBoxRD.Size = New-Object System.Drawing.Size(280,20)
$objComboBoxRD.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$objComboBoxRD.DropDownHeight = "60"
$groupboxRD.Controls.Add($objComboBoxRD)

If($department -ne $null){
    #Determine if user has Argos details on Region
    DetermineRegion
    #Determine if user has Argos details on Department
    DetermineDepartment

    if(($R -eq $false) -AND ($D -eq $false)){
    write-host "RD are both false?"
    #set Business Area as Default.
    $radiobuttonR.checked = $true
    ComboBoxRegion
    $groupboxRD.Controls.Add($radiobuttonR)
    }
}
else{
    #set Business Area as Default.
    $radiobuttonR.checked = $true
    ComboBoxRegion
    $groupboxRD.Controls.Add($radiobuttonR)
}

#Remove Region or Department if BYES
if($objComboBox.text -eq "Bouygues Energies & Services"){
    $groupboxQUALIFICATION.visible = $True
}
else
{
    $groupboxRD.visible = $True
}

#GROUPBOX ARGOS 
$Global:groupboxArgos = New-Object System.Windows.Forms.GroupBox
$groupboxArgos.Location = New-Object System.Drawing.Size(400,95) 
$groupboxArgos.size = New-Object System.Drawing.Size(300,80) 
$groupboxArgos.text = "Powered by Argos" 
$objForm.Controls.Add($groupboxArgos) 

# LABEL ARGOS
$Global:objLabelArgos = New-Object System.Windows.Forms.Label
$objLabelArgos.Location = New-Object System.Drawing.Size(15,35)
$objLabelArgos.Size = New-Object System.Drawing.Size(170,20)
$objLabelArgos.Text = "Click here to update your details"
$groupboxArgos.Controls.Add($objLabelArgos)

#IMAGE ARGOS HYPERLINK
$file = (Get-item "\\10.10.67.173\Templates$\Scripts\Resources\Argos.png")
$img = [System.Drawing.Image]::Fromfile($file);
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Location =  New-Object System.Drawing.Size(185,25)
$pictureBox.Size = New-Object System.Drawing.Size(110,35)
$pictureBox.Image = $img
$pictureBox.add_Click({[system.Diagnostics.Process]::start("http://argos.bouygues-construction.com/")})
$groupboxArgos.controls.add($pictureBox)

#GROUPBOXES MAINADDRESS 
$Global:groupboxMainAddress = New-Object System.Windows.Forms.GroupBox
$groupboxMainAddress.Location = New-Object System.Drawing.point(50,190) 
$groupboxMainAddress.size = New-Object System.Drawing.Size(650,125) 
$groupboxMainAddress.text = "Main Address" 
$objForm.Controls.Add($groupboxMainAddress) 

#LABELS OFFICE 
# Add a Text label- Office
$Global:objLabelOffice = New-Object System.Windows.Forms.Label
$objLabelOffice.Location = New-Object System.Drawing.point(350,30)
$objLabelOffice.Size = New-Object System.Drawing.Size(70,20)
$objLabelOffice.Text = "Office:"
$groupboxMainAddress.Controls.Add($objLabelOffice)
$objLabelOffice.visible = $false

#LABEL BUILDING
# Add a Text label- Building
$Global:objLabelBulding = New-Object System.Windows.Forms.Label
$objLabelBulding.Location = New-Object System.Drawing.point(10,60)
$objLabelBulding.Size = New-Object System.Drawing.Size(70,20)
$objLabelBulding.Text = "Building:"
$Global:groupboxMainAddress.Controls.Add($objLabelBulding)

#LABEL STREET
# Add a Text label- Street
$Global:objLabelStreet = New-Object System.Windows.Forms.Label
$objLabelStreet.Location = New-Object System.Drawing.point(350,60)
$objLabelStreet.Size = New-Object System.Drawing.Size(70,20)
$objLabelStreet.Text = "Street:"
$Global:groupboxMainAddress.Controls.Add($objLabelStreet)

#LABEL TOWN
# Add a Text label- Town
$Global:objLabelTown = New-Object System.Windows.Forms.Label
$objLabelTown.Location = New-Object System.Drawing.point(10,90)
$objLabelTown.Size = New-Object System.Drawing.Size(70,20)
$objLabelTown.Text = "Town:"
$Global:groupboxMainAddress.Controls.Add($objLabelTown)

#LABEL POSTCODE
# Add a Text label- Postcode
$Global:objLabelPostcode = New-Object System.Windows.Forms.Label
$objLabelPostcode.Location = New-Object System.Drawing.point(350,90)
$objLabelPostcode.Size = New-Object System.Drawing.Size(70,20)
$objLabelPostcode.Text = "Postcode:"
$Global:groupboxMainAddress.Controls.Add($objLabelPostcode)

#TEXTBOX BUILDING
# Add a text box to the Userform Building
$Global:TextBoxBuilding = New-Object System.Windows.Forms.TextBox
$TextBoxBuilding.Location = New-Object System.Drawing.Size(80,60)
$TextBoxBuilding.Size = New-Object System.Drawing.Size(200,20)
$TextBoxBuilding.Text = "$AddressBuilding"
$groupboxMainAddress.Controls.Add($TextBoxBuilding)
#################################################################################################### need to make it work
<#
$TextBoxBuilding_OnTextInput={
    UpdateSignature
}
$TextBoxBuilding.OnTextInput($TextBoxBuilding_OnTextInput)
#>
#OnPropertyChanged
#################################################################################################### need to make it work


#TEXTBOX STREET
# Add a text box to the Userform Street
$Global:TextBoxStreet = New-Object System.Windows.Forms.TextBox
$TextBoxStreet.Location = New-Object System.Drawing.Size(430,60)
$TextBoxStreet.Size = New-Object System.Drawing.Size(200,20)
$TextBoxStreet.Text = "$addressStreet"
$groupboxMainAddress.Controls.Add($TextBoxStreet)

#TEXTBOX TOWN
# Add a text box to the Userform Town
$Global:TextBoxTown = New-Object System.Windows.Forms.TextBox
$TextBoxTown.Location = New-Object System.Drawing.Size(80,90)
$TextBoxTown.Size = New-Object System.Drawing.Size(200,20)
$TextBoxTown.Text = "$AddressTown"
$groupboxMainAddress.Controls.Add($TextBoxTown)

#TEXTBOX POSTCODE
# Add a text box to the Userform Postcode
$Global:TextBoxPostcode = New-Object System.Windows.Forms.TextBox
$TextBoxPostcode.Location = New-Object System.Drawing.Size(430,90)
$TextBoxPostcode.Size = New-Object System.Drawing.Size(200,20)
$TextBoxPostcode.Text = "$AddressPostcode"
$groupboxMainAddress.Controls.Add($TextBoxPostcode)

#RADIOBOX ARGOS
$Global:radiobuttonArgos = New-Object System.Windows.Forms.RadioButton 
$radiobuttonArgos.Location = new-object System.Drawing.Point(10,30) 
$radiobuttonArgos.size = New-Object System.Drawing.Size(140,20) 
$radiobuttonArgos.Checked = $true 
$radiobuttonArgos.Text = "Populate From Argos" 
$groupboxMainAddress.Controls.Add($radiobuttonArgos) 

#RADIOBOX OFFICE
$Global:radiobuttonOffice = New-Object System.Windows.Forms.RadioButton 
$radiobuttonOffice.Location = new-object System.Drawing.Point(150,30) 
$radiobuttonOffice.size = New-Object System.Drawing.Size(80,20) 
$radiobuttonOffice.Text = "Main Office" 
$groupboxMainAddress.Controls.Add($radiobuttonOffice) 

# Determine whether to show the R/D or Qualification
if($objComboBox.text -eq "Bouygues Energies & Services"){
        $radiobuttonOffice.enabled = $false
    }
else
{
       $radiobuttonOffice.enabled = $True

    }
#RADIOBOX OTHER
$Global:radiobuttonOther = New-Object System.Windows.Forms.RadioButton 
$radiobuttonOther.Location = new-object System.Drawing.Point(250,30) 
$radiobuttonOther.size = New-Object System.Drawing.Size(120,20) 
$radiobuttonOther.Text = "Other" 
$groupboxMainAddress.Controls.Add($radiobuttonOther) 

#COMBOBOX OFFICE
$Global:objComboBoxOffice = New-Object System.Windows.Forms.Combobox
$objComboBoxOffice.Location = New-Object System.Drawing.point(430,30)
$objComboBoxOffice.Size = New-Object System.Drawing.Size(200,20)
$groupboxMainAddress.Controls.Add($objComboBoxOffice)
$objComboBoxOffice.DropDownHeight = "60"
#Remove Region or Department if BYES

#This should identify which option is ticked and then disable or enable Office combobox and label if not Office.
AddressChecked

#LABEL LANDLINE
# Add a Text label- Landline
$Global:objLabelLandline = New-Object System.Windows.Forms.Label
$objLabelLandline.Location = New-Object System.Drawing.Size(50,350)
$objLabelLandline.Size = New-Object System.Drawing.Size(70,20)
$objLabelLandline.Text = "Landline:"
$objForm.Controls.Add($objLabelLandline)

#Format Landline
FormatLandline 

#TEXTBOX LANDLINE
# Add a text box to the Userform Landline
$Global:TextBoxLandline = New-Object System.Windows.Forms.TextBox
$TextBoxLandline.Location = New-Object System.Drawing.point(130,350)
$TextBoxLandline.Size = New-Object System.Drawing.Size(200,20)
$TextBoxLandline.Text = "$fLandline"
$TextBoxLandline.enabled = $false

$objForm.Controls.Add($TextBoxLandline)

#LABEL MOBILE
# Add a Text label- Mobile
$Global:objLabelMobile = New-Object System.Windows.Forms.Label
$objLabelMobile.Location = New-Object System.Drawing.Size(50,320)
$objLabelMobile.Size = New-Object System.Drawing.Size(70,20)
$objLabelMobile.Text = "Mobile:" 
$objForm.Controls.Add($objLabelMobile)

#Format Mobile
FormatMobile

#TEXTBOX MOBILE
# Add a text box to the Userform Mobile
$Global:TextBoxMobile = New-Object System.Windows.Forms.TextBox
$TextBoxMobile.Location = New-Object System.Drawing.point(130,320)
$TextBoxMobile.Size = New-Object System.Drawing.Size(200,20)
$TextBoxMobile.Text = "$fMobile"
$TextBoxMobile.enabled = $false
$objForm.Controls.Add($TextBoxMobile)

#LABEL EMAILADDRESS
# Add a Text label- Email Address
$Global:objLabelemail = New-Object System.Windows.Forms.Label
$objLabelemail.Location = New-Object System.Drawing.Size(400,320)
$objLabelemail.Size = New-Object System.Drawing.Size(70,20)
$objLabelemail.Text = "Email:"
$objForm.Controls.Add($objLabelemail)

#TEXTBOX EMAILADDRESS
# Add a text box to the Userform Email Address
$Global:TextBoxEmailAddress = New-Object System.Windows.Forms.TextBox
$TextBoxEmailAddress.Location = New-Object System.Drawing.point(480,320)
$TextBoxEmailAddress.Size = New-Object System.Drawing.Size(200,20)
$TextBoxEmailAddress.Text = "$EmailAddress"
$objForm.Controls.Add($TextBoxEmailAddress)

#BUTTON UPDATE
# Add Update Button
$Global:UpdateButton = New-Object System.Windows.Forms.Button
$UpdateButton.Location = New-Object System.Drawing.Size(480,350)
$UpdateButton.Size = New-Object System.Drawing.Size(75,25)
$UpdateButton.Text = "Update"
$objForm.Controls.Add($UpdateButton)
$comboCompany = $objComboBox.text

#BUTTON SAVE
# Add an Save Button
$Global:SaveButton = New-Object System.Windows.Forms.Button
$SaveButton.Location = New-Object System.Drawing.Size(650,580)
$SaveButton.Size = New-Object System.Drawing.Size(150,25)
$SaveButton.Text = "Save"

#BUTTON EXIT
# Add an Exit button
$Global:ExitButton = New-Object System.Windows.Forms.Button
$ExitButton.Location = New-Object System.Drawing.Size(630,350)
$ExitButton.Size = New-Object System.Drawing.Size(75,25)
$ExitButton.Text = "Exit"
$objForm.Controls.Add($ExitButton)

#LABEL USERNAME
# Add a Text label- username
$Global:objLabelusername = New-Object System.Windows.Forms.Label
$objLabelusername.Location = New-Object System.Drawing.Size(50,590)
$objLabelusername.Size = New-Object System.Drawing.Size(70,25)
$objLabelusername.Text = "Username:"
$objForm.Controls.Add($objLabelusername)

#TEXTBOX USERNAME
# Add a text box to the Userform Email Address
$Global:TextBoxusername = New-Object System.Windows.Forms.TextBox
$TextBoxusername.Location = New-Object System.Drawing.point(125,585)
$TextBoxusername.Size = New-Object System.Drawing.Size(200,25)
$TextBoxusername.Text = "$username"
$objForm.Controls.Add($TextBoxusername)

#BUTTON USERNAME
# Add an username Button
$Global:usernameButton = New-Object System.Windows.Forms.Button
$usernameButton.Location = New-Object System.Drawing.Size(335,580)
$usernameButton.Size = New-Object System.Drawing.Size(150,25)
$usernameButton.Text = "Update Via Username"
$objForm.Controls.Add($usernameButton)

Validation
Updateandreplace
$webBrowser1.IsWebBrowserContextMenuEnabled = $false

$objForm.add_FormClosing([System.Windows.Forms.FormClosingEventHandler]{
$Global:ConfirmClose = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to exit the application?", "", 4) 
    if ($ConfirmClose -ne "YES"){
        $_.Cancel = $true
    }
})
# Show form
$objForm.Add_Shown({$objForm.Activate()})
#$objForm.TopMost = $true
[void] $objForm.ShowDialog()

#TOOLTIP##########
#$ToolTip = New-Object System.Windows.Forms.ToolTip 
#$ToolTip.SetToolTip($TextBoxfname, "Enter Your first name")
#$objForm.Controls.Add($ToolTip)

}
catch{
    Write-Host "Caught the exception";
    Write-Host $Error[0].Exception;
}
\$\endgroup\$
3
  • 4
    \$\begingroup\$ As Ken White said on Stack Overflow: Can you avoiding it having to initialize everything (including the .NET framework) when it's run the first time? No. - that said, I'm sure we can help improve the script itself. \$\endgroup\$ Commented Oct 2, 2015 at 16:53
  • \$\begingroup\$ I probably can, but I am not sure if this is going to make it better in PS v2. Is there any major ones I can remove that you can show me as I am not sure i would be doing this right? And apologies as I am still new at this if you can show me an example that would be great. \$\endgroup\$
    – Visar Baci
    Commented Oct 6, 2015 at 8:43
  • \$\begingroup\$ @VisarBaci What Mat's Mug was implying is that some of the startup cost cannot be deferred and will always cause you speed decreases the first launch. \$\endgroup\$ Commented Dec 10, 2016 at 4:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.