$PSScriptRoot is null on exe

Hi, i wrote a script in powershell using Windows Forms. The buttons triggers inside the Visual Studio. When i try to open the script on a terminal or the .exe the button doesn’t works.

Windows 11
Visual Studio 2022

This is my code.

. (Join-Path $PSScriptRoot ‘Form1.designer.ps1’)
$Form1_Load = {


$button1_Click = {

$button2_Click = {

Function Get-Dependencies {
$ModulesArray = “ExchangeOnlineManagement”, “AzureAD”, “ImportExcel”, “Az”, “PowerShellGet”, “MicrosoftTeams”
foreach ($module in $ModulesArray) {
if (Get-Module -ListAvailable -Name $module) {
[System.Windows.MessageBox]::Show(“Módulo $module já instalado.”,‘Warning’,‘Ok’,‘Information’)
} else {
[System.Windows.MessageBox]::Show(“Instalando módulo $module.”)
try {
Install-Module $module
} catch {
##throw $_.Exception.Message
Write-Output “”
[System.Windows.MessageBox]::Show(“Não foi possível instalar o módulo $module. Tente executar o script como administrador.”,‘Error’,‘Ok’,‘Error’)

Function Set-Authentications {
Import-Module AzureAD
try {
Connect-AzureAD -erroraction ‘silentlycontinue’
} catch {
[System.Windows.MessageBox]::Show(“Não foi possivel se autenticar! Tente executar o script novamente.”,‘Error’,‘Ok’,‘Error’)
Write-Output “”


EDIT: Looks like the $PSScriptRoot doesn’t work, it’s null.

On VS2022

On exe

Now i’m able to get this value
But none of the elements works
Only running inside the visual studio 2022

Pretty sure this is by design as it happens with other ps to exe converters as well, it makes sense as it’s a script root variable but it’s no longer a script after you convert it. You can use this instead:

$CurrentProcess = Get-WmiObject Win32_Process | Where ProcessID -match "^$($PID)$" 
If ($CurrentProcess.ProcessName -match '^Powershell.exe$|^Powershell_ise.exe')
$CurrentDIR = If ($PSScriptRoot) {$PSScriptRoot} else {Get-Location | Select - expand Path}
} else {
$CurrentDIR = Split-Path (Convert-Path ([environment]::GetCommandLineArgs())[0] 

That should work if you run it via powershell or the ise, or as an exe.