Powershell building exe fails

Hi all,

I’m having some problems with Powershell Pro tools. Building exe always fails even with different settings. I have tried change NET Framework version, Obfuscate executable settings on and off, different powershell version. I have tried even visual studio and powershell pro tools uninstall and with different machines and still without success.

At the moment I’m running out of ideas and I am here to get some help. All was working on trial but now I have license and can’t do anything.

Forgot to give error itself:

Failed to find the developer pack for .NET Version net472. The build is likely going to fail. You can install the Developer Pack from Microsoft: Download .NET SDKs for Visual Studio
Using .NET Framework version: net472

Can you post the full build log? Sometimes I see that error and it isn’t actually causing the failure.

Yes, but where I can find it? Whats the default location?

Can you let me know which tool you are using? VS Code or Visual Studio?

Visual Studio

You will need to look at the Output window in Visual Studio. Make sure you have Build selected in the drop down.

It looks like this is succeeding. If you look near the end of the log, you’ll see that it provides a path. Can you see if the file exists in that location?

Yes, but exe isn’t working correctly. Debug in visual studio works fine but exe crashes… Any ideas?

Ah, interesting. Can you either send me the PS1 you are packaging or the exe you packaged?

support@ironmansoftware.com

I got original issue fixed. Problem was project / exe naming. Problem was space with project / exe names.

Now I got issue with ps module package… exe gives me following error: PS>TerminatingError(Import-Module): “Could not load file or assembly ‘file:///C:\Users\admmoilaro\AppData\Local\Temp\d4f0b5ef-3599-483a-a660-66737bc693d6\ActiveDirectory\Microsoft.ActiveDirectory.Management’ or one of its dependencies. The system cannot find the file specified.”
Debug: Exception Message Could not load file or assembly ‘file:///C:\Users\admmoilaro\AppData\Local\Temp\d4f0b5ef-3599-483a-a660-66737bc693d6\ActiveDirectory\Microsoft.ActiveDirectory.Management’ or one of its dependencies. The system cannot find the file specified.

can you help with that?

Weird. It seems like it’s trying to reference the AD module which it shouldn’t be doing. Let me try this. We had an issue in the past where the build would try to reference nested CS files but maybe we have a regression here.

EDIT: I can’t reproduce this. I’m importing the standard AD module and tried in both PS 5 and 7. Can you share your packaging settings and script at all?

Packaging settings:

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>6CAFC0C6-A428-4d30-A9F9-700E829FEA51</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>MyApplication</RootNamespace>
    <AssemblyName>MyApplication</AssemblyName>
    <Name>MoroApp</Name>
    <PackageAsExecutable>True</PackageAsExecutable>
    <PackageEntryPoint>MoroApp.ps1</PackageEntryPoint>
    <Bundle>True</Bundle>
    <Obfuscate>True</Obfuscate>
    <HideConsoleWindow>True</HideConsoleWindow>
    <DotNetVersion>net462</DotNetVersion>
    <PackageModules>True</PackageModules>
    <PackageType>Console</PackageType>
    <PowerShellVersion>Windows PowerShell</PowerShellVersion>
    <FileDescription>Valmet Automotive Oy</FileDescription>
    <ProductName>MoroApp</ProductName>
    <ProductVersion>1.0</ProductVersion>
    <Copyright>Roni Moilanen</Copyright>
    <ApplicationIconPath>C:\temp\VA-Production\Img\OnePlaza.ico</ApplicationIconPath>
    <StartupFile>MoroApp.ps1</StartupFile>
    <PackagePlatform>x64</PackagePlatform>
    <PowerShellArgs>-ExecutionPolicy Bypass</PowerShellArgs>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Content Include="WpfWindow1.xaml" />
    <Content Include="WpfWindow2.xaml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="MoroApp.ps1" />
    <Compile Include="WpfWindow1.xaml.ps1">
      <SubType>Code</SubType>
      <DependentUpon>WpfWindow1.xaml</DependentUpon>
    </Compile>
    <Compile Include="WpfWindow2.xaml.ps1">
      <SubType>Code</SubType>
      <DependentUpon>WpfWindow2.xaml</DependentUpon>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <Name>PresentationFramework</Name>
      <AssemblyName>
      </AssemblyName>
      <HintPath>
      </HintPath>
    </Reference>
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Target Name="Build" />
  <Import Project="$(MSBuildExtensionsPath)\PowerShell Tools for Visual Studio\PowerShellTools.targets" Condition="Exists('$(MSBuildExten
$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

Can you find something?

Hey @vascripter

Sorry for the delay. Can you let me know why you are importing the module via path? I wonder if that’s causing the problem.

What happens if you do it like this?

Import-Module  ActiveDirectory

Yeah, I tried it because that Import-Module ActiveDirectory doesn’t work and even with path same problem. This was only reason why we wanted buy this product and now it doesn’t even work…