$Global:Current_Folder = (Get-Location).path
# Start logging
Start-Transcript -Path "C:\Temp\VAProdStore\$Env:UserName_Login.txt" -Force
Try {
Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory\ActiveDirectory.psd1
Get-Module ActiveDirectory
Get-Module –ListAvailable
} Catch {
# Advanced error
Write-Host "Debug: Exception Message $($_.Exception.Message)"
}
# Load Config
If(Test-Path "C:\Temp\VAProd"){
Write-Host "Debug:"
} Else {
New-Item -ItemType Directory -Path "C:\Temp\VAProd" -Force
Write-Host "Debug:"
Write-Host "Debug: Application temp folder created succesfully."
}
If(Test-Path "C:\Temp\VAProdStore"){
Write-Host "Debug:"
} Else {
New-Item -ItemType Directory -Path "C:\Temp\VAProdStore" -Force
Write-Host "Debug:"
Write-Host "Debug: Application temp store folder created succesfully."
}
Get-Item "C:\Temp\VAProdStore" -Force | ForEach { $_.Attributes = $_.Attributes -bor "Hidden" }
If(Test-Path -LiteralPath "C:\Temp\VAProd\Config.xml"){
$ConfigPath = "C:\Temp\VAProd\Config.xml"
$ConfigXML = [xml] (Get-Content $ConfigPath)
Foreach($Config in $ConfigXML.selectNodes("Config")){
$Global:DefaultLanguage = $Config.DefaultLanguage
$Global:SSOAutoLogin = $Config.SSOAutoLogin
$Global:SharedAccountLogin = $Config.SharedAccountLogin
$Global:OnePlazaUser = $Config.OnePlazaUser
$Global:OnePlazaPass = $Config.OnePlazaPass
$Global:PasswordNotifyDays = $Config.PasswordNotifyDays
$Global:DomainServer = $Config.DomainServer
$Global:PrintServer = $Config.PrintServer
$Global:PrinterInstallServer = $Config.PrinterInstallServer
}
Write-Host "Debug:"
Write-Host "Debug: Config file '$ConfigPath' loaded successfully."
} Else {
Write-Host "Debug: Config file wasn't loaded."
Dialog("Config file wasn't loaded. Please restart program.")
$DefaultConfig = @"
<?xml version="1.0" encoding="UTF-8"?>
<Config>
<DefaultLanguage>Finnish</DefaultLanguage>
<SSOAutoLogin>Off</SSOAutoLogin>
<SharedAccountLogin>On</SharedAccountLogin>
<OnePlazaUser></OnePlazaUser>
<OnePlazaPass></OnePlazaPass>
<PasswordNotifyDays>7</PasswordNotifyDays>
<DomainServer></DomainServer>
<PrintServer></PrintServer>
<PrinterInstallServer></PrinterInstallServer>
</Config>
"@
Set-Content "C:\Temp\VAProd\Config.xml" $DefaultConfig
$Window.Close()
}
If($SSOAutoLogin -eq "On"){
Start-Process -FilePath 'C:\Program Files (x86)\Valmet Automotive\MoroApp\MoroAppClient.exe' -WorkingDirectory $Current_Folder -Wait
}
# Finnish - Suomi
If($DefaultLanguage -eq "Finnish"){
$Global:Current_Language = "Finnish"
}
# English - Englanti
Elseif($DefaultLanguage -eq "English"){
$Global:Current_Language = "English"
}
Try {
Add-Type -AssemblyName PresentationCore, PresentationFramework
} Catch {
Write-Host "Debug: Couldn't load WPF Framework."
Dialog("Couldn't load WPF Framework.")
exit
}
$Xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="Valmet Automotive" Width="400" Height="500" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize">
<Grid Background="#ffffff">
<Image Name="VA_PictureBox" HorizontalAlignment="Left" Height="180" VerticalAlignment="Top" Width="310" Margin="56,-54,0,0" Source="https://download.logo.wine/logo/Valmet_Automotive/Valmet_Automotive-Logo.wine.png"/>
<Label Name="VA_SingInLabel" HorizontalAlignment="Left" VerticalAlignment="Top" Content="SIGN IN" Margin="158,61,0,0" FontFamily="Agency FB" FontSize="30" FontWeight="Bold" Width="90" Height="39" RenderTransformOrigin="0.406,0.064"/>
<Label Name="VA_UsernameLabel" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Sähköposti" Margin="56,95,0,0" FontFamily="Agency FB" FontSize="18" FontWeight="Bold" RenderTransformOrigin="0.521,0.21"/>
<TextBox Name="VA_UsernameBox" HorizontalAlignment="Left" VerticalAlignment="Top" Height="34" Width="275" Margin="56,123,0,0" FontFamily="Agency FB" FontSize="16"/>
<Label Name="VA_PasswordLabel" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Salasana" Margin="56,153,0,0" FontFamily="Agency FB" FontSize="18" FontWeight="Bold" RenderTransformOrigin="0.521,0.21"/>
<PasswordBox Name="VA_PasswordBox" HorizontalAlignment="Left" VerticalAlignment="Top" Height="34" Width="275" Margin="56,184,0,0" FontFamily="Agency FB" FontSize="16"/>
<Button Name="VA_SignInButton" Content="Sign In" HorizontalAlignment="Left" VerticalAlignment="Top" Width="138" Margin="132,223,0,0" Height="42" FontFamily="Agency FB" FontSize="18" Background="#010101" Foreground="#fefdff"/>
<Label Name="VA_OrLabel" HorizontalAlignment="Left" VerticalAlignment="Top" Content="OR" Margin="188,273,0,0" FontFamily="Agency FB" FontSize="30" FontWeight="Bold" Width="90" Height="39"/>
<Button Name="VA_OnePlazaButton" Content="OnePlaza" HorizontalAlignment="Left" VerticalAlignment="Top" Width="138" Margin="132,312,0,0" Height="42" FontFamily="Agency FB" FontSize="18" Background="#010101" Foreground="#fefdff"/>
<Label Name="VA_NeedHelpLabel" HorizontalAlignment="Left" VerticalAlignment="Top" Content="NEED HELP?" Margin="140,362,0,0" FontFamily="Agency FB" FontSize="30" FontWeight="Bold" Width="139" Height="42"/>
<Button Name="VA_NeedHelpButton" Content="Open Guide" HorizontalAlignment="Left" VerticalAlignment="Top" Width="138" Margin="131,398,0,0" Height="42" FontFamily="Agency FB" FontSize="18" Background="#010101" Foreground="#fefdff"/>
</Grid>
</Window>
"@
#-------------------------------------------------------------#
#----Control Event Handlers-----------------------------------#
#-------------------------------------------------------------#
# Write your logic code here
# https://vauki.sharepoint.com/sites/MBL/SitePages/ICT.aspx
# Actions
function btnSignIn_Click {
Write-Host "Debug:"
Write-Host "Debug: User clicked button 'Sign In'."
If(Test-Connection $Global:DomainServer -Quiet -Count 1){
Write-Host "Debug: Connection between computer and domain server is available."
If($VA_UsernameBox.Text -eq ""){
Dialog("Please verify your username.")
} Else {
If($VA_PasswordBox.Text -eq ""){
Dialog("Please verify your password.")
} Else {
$User = $VA_UsernameBox.Text
Write-Host "Debug: Trying to sign in '$User'."
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$Domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$User,$VA_PasswordBox.Password)
# Password need to be secure to authentication to work
$Password = ConvertTo-SecureString $VA_PasswordBox.Password -AsPlainText -Force
If($Domain.name -eq $Null){
Write-Host "Debug: Authentication failed - please verify your username and password."
Dialog("Please verify your username and password.")
} Else {
$Username = "VA\$User"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList ($Username,$Password)
Write-Host "Debug: Successfully authenticated with domain."
If($User.Contains("@")){
If(Get-ADUser -filter {(UserPrincipalName -eq $User)} | Where-Object {$_.Enabled -eq $false}){
Write-Host "Debug: $Username is disabled. Please call servicedesk: 48888."
Dialog("Your account is disabled. Please call servicedesk: 48888")
} Else {
Write-Host "Debug: $Username is not disabled."
Start-Process -FilePath 'C:\Program Files (x86)\Valmet Automotive\MoroApp\MoroAppClient.exe' -Credential $Credentials -WorkingDirectory $Current_Folder
Write-Host "Debug: Starting application."
$Window.Close()
}
} Else {
If(Get-ADUser -Identity $User | Where-Object {$_.Enabled -eq $false}){
Write-Host "Debug: $Username is disabled. Please call servicedesk: 48888."
Dialog("Your account is disabled. Please call servicedesk: 48888")
} Else {
Write-Host "Debug: $Username is not disabled."
#Invoke-Command -FilePath 'C:\VA_Production\Application.ps1' -Credential $Credentials
Start-Process -FilePath 'C:\Program Files (x86)\Valmet Automotive\MoroApp\MoroAppClient.exe' -Credential $Credentials -WorkingDirectory $Current_Folder
Write-Host "Debug: Starting application."
$Window.Close()
}
}
}
}
}
} Else {
Write-Host "Debug: Connection between computer and domain server failed. Please check your connection."
Dialog("Domain server is unavailable. Please check your connection.")
}
}
function btnOnePlaza_Click {
Write-Host "Debug:"
Write-Host "Debug: User clicked button 'OnePlaza'."
Edge("https://vauki.sharepoint.com/")
}
function btnNeedHelp_Click {
Write-Host "Debug:"
Write-Host "Debug: User clicked button 'Open Guide'."
Edge("https://oneplaza.va.local/sites/w3fmx/Shared%20Documents/Ohjeet/OnePlaza_ja_Outlook_tuotannossa_V3.pdf")
}
# Actions without controls
function LoadLanguage {
# Finnish - Suomi
If($Current_Language -eq "Finnish"){
# Main view
}
# English - Englanti
Elseif($Current_Language -eq "English"){
# Main view
}
}
function Edge($URL = 'https://vauki.sharepoint.com/'){
$software = "Microsoft Edge"
$installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName | Where {$_.DisplayName -Match $software }) -ne $null
If(-Not $installed){
Chrome($URL)
} Else {
If(Test-Path -LiteralPath "C:\Program Files\Microsoft\Edge\Application\msedge.exe"){
$EdgePath = "C:\Program Files\Microsoft\Edge\Application\msedge.exe"
Write-Host "Debug: EdgePath set to 'C:\Program Files\Microsoft\Edge\Application\msedge.exe'"
} ElseIf("C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"){
$EdgePath = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
Write-Host "Debug: ChromePath set to 'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'"
} Else {
Chrome($URL)
Write-Host "Debug: Couldn't set EdgePath."
Dialog("Please install 'Microsoft Edge' latest version from Software Center!")
Start-Process 'Softwarecenter:' -WorkingDirectory 'C:\Windows\System32'
}
$OSVersion = (Get-Itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
If($OSVersion -eq "Windows 10 Enterprise"){
$ArgumentList = '--new-window ' + $URL
} ElseIf($OSVersion -eq "Windows 7 Enterprise"){
$ArgumentList = '--new-window --allow-no-sandbox-job ' + $URL
} Else {
$ArgumentList = $URL
}
Write-Host "Debug: Edge URL set to '$URL'"
Try {
Start-Process -FilePath $EdgePath -ArgumentList $ArgumentList -WorkingDirectory 'C:\Windows\System32'
Write-Host "Debug: msedge.exe opened successfully."
} Catch {
# Advanced error
Write-Host "Debug: Microsoft Edge Exception Message $($_.Exception.Message)"
Dialog("Couldn't open Microsoft Edge for unknow reason.")
}
}
}
function Chrome($URL = 'https://vauki.sharepoint.com/'){
$software = "Google Chrome";
$installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -Match $software }) -ne $null
If(-Not $installed){
#Test if Google Chrome is installed
Write-Host "Debug: Please install '$software' from Software Center!"
Dialog("Please install '$software' from Software Center!")
Start-Process 'Softwarecenter:' -WorkingDirectory 'C:\Windows\System32'
} Else {
If(Test-Path -LiteralPath "C:\Program Files\Google\Chrome\Application\chrome.exe"){
$ChromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
Write-Host "Debug: ChromePath set to 'C:\Program Files\Google\Chrome\Application\chrome.exe'"
} ElseIf("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"){
$ChromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Write-Host "Debug: ChromePath set to 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'"
} Else {
Write-Host "Debug: Couldn't set ChromePath."
}
$OSVersion = (Get-Itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
If($OSVersion -eq "Windows 10 Enterprise"){
$ArgumentList = '--new-window ' + $URL
} ElseIf($OSVersion -eq "Windows 7 Enterprise"){
$ArgumentList = '--new-window --allow-no-sandbox-job ' + $URL
} Else {
$ArgumentList = $URL
}
Write-Host "Debug: Chrome URL set to '$URL'"
Try {
Start-Process -FilePath $ChromePath -ArgumentList $ArgumentList -WorkingDirectory 'C:\Windows\System32'
Write-Host "Debug: Chrome.exe opened successfully."
} Catch {
# Advanced error
Write-Host "Debug: Chrome Exception Message $($_.Exception.Message)"
Dialog("Couldn't open Chrome for unknow reason. Please Call Service Desk.")
}
}
}
function Dialog($Msg){
#-------------------------------------------------------------#
#----Initial Declarations-------------------------------------#
#-------------------------------------------------------------#
Add-Type -AssemblyName PresentationCore, PresentationFramework
$Xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="Valmet Automotive" Width="300" Height="250" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
<Grid Margin="0,0,0,0">
<Image Name="VA_PictureBox" HorizontalAlignment="Left" Height="168" VerticalAlignment="Top" Width="272" Margin="7,-53,0,0" Source="https://download.logo.wine/logo/Valmet_Automotive/Valmet_Automotive-Logo.wine.png" Stretch="UniformToFill"/>
<TextBlock Name="VA_InfoTextBlock" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="WrapWithOverflow" Text="Couldn't load WPF Framework." Margin="39,72,0,0" FontSize="18" FontFamily="Agency FB" Width="209" Height="72"/>
<Button Name="VA_OkButton" Content="Ok" HorizontalAlignment="Left" VerticalAlignment="Top" Width="102" Margin="93,156,0,0" Background="#000000" Foreground="#ffffff" Height="30" FontFamily="Agency FB" FontSize="18"/>
</Grid>
</Window>
"@
#-------------------------------------------------------------#
#----Control Event Handlers-----------------------------------#
#-------------------------------------------------------------#
#Write your code here
function btnOk_Click {
$Window.Close()
}
#endregion
#-------------------------------------------------------------#
#----Script Execution-----------------------------------------#
#-------------------------------------------------------------#
$Window = [Windows.Markup.XamlReader]::Parse($Xaml)
[xml]$xml = $Xaml
$xml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name $_.Name -Value $Window.FindName($_.Name) }
$VA_OkButton.Add_Click({btnOk_Click $this $_})
# Do after window is loaded
$Window.add_Loaded({
#$Window.Icon = "$Current_Folder\Img\VA-Icon.ico"
$VA_InfoTextBlock.Text = $Msg
})
$Window.ShowDialog()
}
#endregion
#-------------------------------------------------------------#
#----Script Execution-----------------------------------------#
#-------------------------------------------------------------#
Try {
$Window = [Windows.Markup.XamlReader]::Parse($Xaml)
[xml]$xml = $Xaml
$xml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name $_.Name -Value $Window.FindName($_.Name) }
} Catch {
Write-Host "Debug: Couldn't parse XAML."
Dialog("Couldn't parse XAML.")
exit
}
$VA_SignInButton.Add_Click({btnSignIn_Click $this $_})
$VA_OnePlazaButton.Add_Click({btnOnePlaza_Click $this $_})
$VA_NeedHelpButton.Add_Click({btnNeedHelp_Click $this $_})
$Global:SyncHash = [HashTable]::Synchronized(@{})
$Jobs = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new())
$initialSessionState = [initialsessionstate]::CreateDefault()
Function Start-RunspaceTask
{
[CmdletBinding()]
Param([Parameter(Mandatory=$True,Position=0)][ScriptBlock]$ScriptBlock,
[Parameter(Mandatory=$True,Position=1)][PSObject[]]$ProxyVars)
$Runspace = [RunspaceFactory]::CreateRunspace($InitialSessionState)
$Runspace.ApartmentState = 'STA'
$Runspace.ThreadOptions = 'ReuseThread'
$Runspace.Open()
ForEach($Var in $ProxyVars){$Runspace.SessionStateProxy.SetVariable($Var.Name, $Var.Variable)}
$Thread = [PowerShell]::Create('NewRunspace')
$Thread.AddScript($ScriptBlock) | Out-Null
$Thread.Runspace = $Runspace
[Void]$Jobs.Add([PSObject]@{ PowerShell = $Thread ; Runspace = $Thread.BeginInvoke() })
}
$JobCleanupScript = {
Do
{
ForEach($Job in $Jobs)
{
If($Job.Runspace.IsCompleted)
{
[Void]$Job.Powershell.EndInvoke($Job.Runspace)
$Job.PowerShell.Runspace.Close()
$Job.PowerShell.Runspace.Dispose()
$Runspace.Powershell.Dispose()
$Jobs.Remove($Runspace)
}
}
Start-Sleep -Seconds 1
}
While ($SyncHash.CleanupJobs)
}
Get-ChildItem Function: | Where-Object {$_.name -notlike "*:*"} | select name -ExpandProperty name |
ForEach-Object {
$Definition = Get-Content "function:$_" -ErrorAction Stop
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList "$_", $Definition
$InitialSessionState.Commands.Add($SessionStateFunction)
}
$Window.Add_Closed({
Write-Verbose 'Halt runspace cleanup job processing'
$SyncHash.CleanupJobs = $False
})
$SyncHash.CleanupJobs = $True
function Async($scriptBlock){ Start-RunspaceTask $scriptBlock @([PSObject]@{ Name='DataContext' ; Variable=$DataContext},[PSObject]@{Name="State"; Variable=$State})}
Start-RunspaceTask $JobCleanupScript @([PSObject]@{ Name='Jobs' ; Variable=$Jobs })
$Window.Add_SourceInitialized({
Write-Host "Debug: Window is initialized"
})
$Window.Add_Loaded({
#$Window.Icon = "$Current_Folder\Img\VA-Icon.ico"
$Window.Title = "Valmet Automotive - Loading"
LoadLanguage
})
$Window.Add_ContentRendered({
$Window.Title = "Valmet Automotive"
})
$Window.Add_Activated({
# Check connection to domain server
If(Test-Connection $Global:DomainServer -Quiet -Count 1){
Write-Host "Debug: Window is active. Connection between this machine and domain server is working."
} Else {
Write-Host "Debug: Window is active. Domain server is unavailable at the moment. Please check your connection."
Dialog("Domain server unavailable. Please check your connection.")
$Window.Close()
}
})
$Window.Add_Closed({
Write-Host "Debug: App closed."
})
# Displays GUI
$Window.ShowDialog()
# Stop logging
Stop-Transcript