can we add multiple folder path in below statement like this if we have multiple subfolder under main folder like as below
I like to say that "programming is an art". By that I mean that; in a lot of cases, there are different ways to accomplish a given task with code. A lot depends on what you are trying to accomplish, how much error checking is required, do you need to interact with a user, etc.
So yes, you could create an array of folder names and send that via a pipeline to a Remove-Item cmdlet, But given the starting point of your .bat file code, you might want to use an array and a function like this.
$FolderList = @("\AppData\Local\foldername\subfoldername1",
"\AppData\Local\foldername\subfoldername2",
"\AppData\Local\foldername\subfoldername3")
Function FolderKiller ($pThisFolder) { # the folder name is a positional parameter
write-host "Checking $pThisFolder"
if (Test-Path $pThisFolder) { # verify that the folder exists
write-host "The folder exists, attempting delete...."
try { # we want to handle errors
Remove-Item -Path $pThisFolder -Recurse -ErrorAction Stop # remove all subfolders too
Write-Host "Success!"
}
catch { # something didn't work
Write-Host "Error!!! We crashed!!!"
Write-Host $_.ErrorDetails.Message
}
} else {
write-host "That folder does not exist, try again...."
}
}
cls
while ($true) { # infinite loop that we will break out of
$menu = Read-Host "Do you want to delete Temp File ? (Y/N): "
if ($menu -match "n") { # we have a no
write-host "Okay, let's exit..."
start-sleep 5 # if we are running as a .ps1 file, delay a bit so that the user can see our message
break # break out of the while loop to finish
}
if ($menu -match "y") { # we have a yes
$Username = Read-Host "Please insert user name : "
if ($Username -eq "") { # validate inout
Write-Host "Username cannot be blank."
continue # loop again
}
foreach ($fldr in $FolderList) { # we want to delete multiple folders for this user
$TargetDir = "C:\Users\" + $username + $fldr
FolderKiller $TargetDir # Call our delete function and pass it the name of the folder
}
} else {
Write-host "Input not recognized. Please make a valid choice." # user did not enter y/n
}
}