PowerShell script works in ISI, but not from command line


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)

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

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?