I will try my best to ask the question.
Here is an abstract of the function.
Dim testPath = "Test-Path 'H:\General\H5841\"
Dim removeDir = "Remove-Item 'H:\General\H5841\"
result = RunScript($"{testPath}{payType}_{payrunNum}_{trials}_{ProcessingDate_DTP.Text}'")
If String.Compare(result, "True") Then
RunScript($"{removeDir}{payType}_{payrunNum}_{trials}_{ProcessingDate_DTP.Text}'")
Output_RTB.Text = "Folder Deleted"
Else
Output_RTB.Text = "Folder Not Found"
End If
First, the function tests if the path is valid. Below is what the result will equal and it is working in Powershell, true if folder is found, else false. This is working.
Test-Path 'H:\General\H5841\G7_999_Final_29.03.24'
However, say when I tests it, the folder exists, and I run this function, it deletes the folder and prompts Folder Deleted but when I try to simulate that the folder is not there, it returns as False but it still shows Folder Deleted, instead of Folder Not Found.
When I start off without creating the folder, it returns False and Folder Not Found. I am not sure why this is behaving like this.
I also tried the conventional way of result is "True" and it is will go into the False condition despite the folder is there. I used MsgBox to prompt the result variable and also used a textbox to test for white spacing and it appears none.
If result Is "True" Then
RunScript($"{removeDir}{payType}_{payrunNum}_{trials}_{ProcessingDate_DTP.Text}'")
Output_RTB.Text = "Folder Deleted"
Else
Output_RTB.Text = "Folder Not Found"
End If
PS: the curly braces are string interpolation that grab strings from variables and form controls in VB.net before converting into a PowerShell command.
Do you know why VB.net does not do logical comparison properly or is there a different approach I can take?
Thanks in advance
Why are you using PowerShell for that? Can't you just do something like this:
Option Strict On
Imports System.IO
Public Class Form1
Private Sub btnOkay_Click(sender As Object, e As EventArgs) Handles btnOkay.Click
Dim folderPath As String = txtFolderPath.Text
Output_RTB.Text = TryDeleteFolderAndReportSuccess(folderPath)
End Sub
Private Shared Function TryDeleteFolderAndReportSuccess(folderPath As String) As String
Try
If DeleteFolder(folderPath) Then Return $"Folder '{folderPath}' deleted."
Return $"Folder '{folderPath}' not found!"
Catch ex As Exception
Return $"Folder '{folderPath}' could not be deleted! The following error occurred: {ex.Message}"
End Try
End Function
Private Shared Function DeleteFolder(folderPath As String) As Boolean
Try
Directory.Delete(folderPath, recursive:=True)
Return True
Catch ex As DirectoryNotFoundException
Return False
End Try
End Function
End Class