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: ( , 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 }