PowerShell script works in ISI, but not from command line

Greetings,

I created a simple PowerShell script that has a file select dialog box to in turn, compress the file after it is selected. This works as expected, but when I try to run the command line of powershell -file test.ps1 it receives the following error code:

You cannot call a method on a null-valued expression.
At C:\test.ps1:13 char:4
+ if($OpenFileDialog.ShowDialog() -eq “OK”)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

Code below. Any ideas on how to fix this?:

 

Function Get-FileName($initialDirectory)
{   
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = "C:\"  
 $OpenFileDialog.filter = "All files (*.*)| *.*"
 $OpenFileDialog.ShowDialog()
 $OpenFileDialog.filename
}


if($OpenFileDialog.ShowDialog() -eq "OK")


{

        # Get full path including file name
        $GetSourceFilePath = ($OpenFileDialog.filename)

        # Strip file extension from selected file so when file is compressed, it won't have the file extension as part of the compressed file
        $StripFileExtension = [System.IO.Path]::GetFileNameWithoutExtension($GetSourceFilePath)

        # Get file path without file name
        $GetFilePath = Get-ChildItem "$GetSourceFilePath"
        $DirectoryOnly = $GetFilePath.DirectoryName

        # Compress specified file and overwrite existing file if same name via the -Force option
        Compress-Archive -LiteralPath $GetSourceFilePath -CompressionLevel Optimal -DestinationPath $DirectoryOnly\$StripFileExtension".zip" -Force
}
else { Write-Host "Operation cancelled" -ForegroundColor Red

} 

The variable $OpenFileDialog will be initialized in the function Get-FileName. You will have to call this function once before you can query the variable.

Is it really necessary to cross post in different forums at the same time?
https://social.technet.microsoft.com/Forums/en-US/746c91a9-6bea-412a-877b-6fa2bdf7ab87/powershell-script-works-in-isi-but-not-from-command-line?forum=winserverpowershell#bb2fb109-4cd9-4233-80e0-4aa05bb2471c

del