This is part of the code I created:
$NameBackup = "Backup"
$DestinationDrive = ""
Get-CimInstance win32_logicaldisk |
ForEach-Object{
if ($_.VolumeName -match "$NameBackup"){
$DestinationDrive = "{0}{1}" -f $_.DeviceId,'\'
}
}
Basically it checks if there is any drive with the word "Backup" in the volume label and gets the letter of that drive.
Given this, I would like to create a code to stop the script and display an error message if there is more than one -match with the $NameBackup variable.
How can I do this?
CodePudding user response:
You could use -Filter
in this case, then check if the .Count
property of the returned query is greater than 1, and if it is, use throw
to halt your script. It may be also worth adding a new condition checking if $cim
is populated.
$NameBackup = "Backup"
$cim = Get-CimInstance Win32_LogicalDisk -Filter "VolumeName LIKE '%$NameBackup%'"
if($cim.Count -gt 1) {
throw "More than one Volume Detected"
}
$DestinationDrive = $cim.DeviceID '\'