Skip to content

Commit bd21da6

Browse files
authored
Update error handling in Uninstall-PSResource (#1215)
1 parent da93794 commit bd21da6

File tree

2 files changed

+83
-57
lines changed

2 files changed

+83
-57
lines changed

src/code/UninstallPSResource.cs

Lines changed: 81 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,11 @@ protected override void ProcessRecord()
100100
}
101101
else if (!Utils.TryParseVersionOrVersionRange(Version, out _versionRange))
102102
{
103-
var exMessage = "Argument for -Version parameter is not in the proper format.";
104-
var ex = new ArgumentException(exMessage);
105-
var IncorrectVersionFormat = new ErrorRecord(ex, "IncorrectVersionFormat", ErrorCategory.InvalidArgument, null);
106-
ThrowTerminatingError(IncorrectVersionFormat);
103+
ThrowTerminatingError(new ErrorRecord(
104+
new ArgumentException("Argument for -Version parameter is not in the proper format."),
105+
"IncorrectVersionFormat",
106+
ErrorCategory.InvalidArgument,
107+
this));
107108
}
108109

109110
Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool _);
@@ -124,13 +125,12 @@ protected override void ProcessRecord()
124125
return;
125126
}
126127

127-
if (!UninstallPkgHelper())
128+
if (!UninstallPkgHelper(out List<ErrorRecord> errRecords))
128129
{
129-
// any errors should be caught lower in the stack
130-
var exMessage = "Did not successfully uninstall package";
131-
var ex = new Exception(exMessage);
132-
var UninstallPackageError = new ErrorRecord(ex, "UninstallResourceError", ErrorCategory.InvalidOperation, null);
133-
WriteError(UninstallPackageError);
130+
foreach (var err in errRecords)
131+
{
132+
WriteError(err);
133+
}
134134
}
135135
break;
136136

@@ -142,20 +142,20 @@ protected override void ProcessRecord()
142142
version: inputObjectVersion,
143143
versionRange: out _versionRange))
144144
{
145-
var exMessage = String.Format("Version '{0}' for resource '{1}' cannot be parsed.", inputObj.Version.ToString(), inputObj.Name);
146-
var ex = new ArgumentException(exMessage);
147-
var ErrorParsingVersion = new ErrorRecord(ex, "ErrorParsingVersion", ErrorCategory.ParserError, null);
148-
WriteError(ErrorParsingVersion);
145+
WriteError(new ErrorRecord(
146+
new ArgumentException($"Error parsing version '{inputObj.Version}' for resource '{inputObj.Name}'."),
147+
"ErrorParsingVersion",
148+
ErrorCategory.ParserError,
149+
this));
149150
}
150151

151152
Name = new string[] { inputObj.Name };
152-
if (!String.IsNullOrWhiteSpace(inputObj.Name) && !UninstallPkgHelper())
153+
if (!String.IsNullOrWhiteSpace(inputObj.Name) && !UninstallPkgHelper(out List<ErrorRecord> InputObjErrRecords))
153154
{
154-
// specific errors will be displayed lower in the stack
155-
var exMessage = String.Format(string.Format("Did not successfully uninstall package {0}", inputObj.Name));
156-
var ex = new ArgumentException(exMessage);
157-
var UninstallResourceError = new ErrorRecord(ex, "UninstallResourceError", ErrorCategory.InvalidOperation, null);
158-
WriteError(UninstallResourceError);
155+
foreach (var err in InputObjErrRecords)
156+
{
157+
WriteError(err);
158+
}
159159
}
160160
}
161161
break;
@@ -175,26 +175,40 @@ protected override void EndProcessing()
175175

176176
#region Private methods
177177

178-
private bool UninstallPkgHelper()
178+
private bool UninstallPkgHelper(out List<ErrorRecord> errRecords)
179179
{
180180
var successfullyUninstalled = false;
181-
182181
GetHelper getHelper = new GetHelper(this);
183182
List<string> dirsToDelete = getHelper.FilterPkgPathsByName(Name, _pathsToSearch);
184183
int totalDirs = dirsToDelete.Count;
184+
errRecords = new List<ErrorRecord>();
185+
186+
if (totalDirs == 0) {
187+
string message = Version == null || Version.Trim().Equals("*") ?
188+
string.Format("Cannot uninstall resource '{0}' because it does not exist", String.Join(", ", Name)) :
189+
190+
string.Format("Cannot uninstall verison '{0}' of resource '{1}' because it does not exist", Version, String.Join(", ", Name));
185191

186-
// Checking if module or script
187-
// a module path will look like:
192+
193+
errRecords.Add(new ErrorRecord(
194+
new PackageNotFoundException(message),
195+
"ResourceNotInstalled",
196+
ErrorCategory.ObjectNotFound,
197+
this));
198+
199+
return successfullyUninstalled;
200+
}
201+
202+
// A module path will look like:
188203
// ./Modules/TestModule/0.0.1
189204
// note that the xml file is located in this path, eg: ./Modules/TestModule/0.0.1/PSModuleInfo.xml
190-
// a script path will look like:
205+
// A script path will look like:
191206
// ./Scripts/TestScript.ps1
192-
// note that the xml file is located in ./Scripts/InstalledScriptInfos, eg: ./Scripts/InstalledScriptInfos/TestScript_InstalledScriptInfo.xml
193-
194-
string pkgName;
207+
// Note that the xml file is located in ./Scripts/InstalledScriptInfos, eg: ./Scripts/InstalledScriptInfos/TestScript_InstalledScriptInfo.xml
195208

196209
// Counter for tracking current dir out of total
197210
int currentUninstalledDirCount = 0;
211+
string pkgName;
198212
foreach (string pkgPath in getHelper.FilterPkgPathsByVersion(_versionRange, dirsToDelete, selectPrereleaseOnly: Prerelease))
199213
{
200214
currentUninstalledDirCount++;
@@ -210,10 +224,18 @@ private bool UninstallPkgHelper()
210224
if (pkgPath.EndsWith(PSScriptFileExt))
211225
{
212226
successfullyUninstalled = UninstallScriptHelper(pkgPath, pkgName, out errRecord);
227+
if (errRecord != null)
228+
{
229+
errRecords.Add(errRecord);
230+
}
213231
}
214232
else
215233
{
216234
successfullyUninstalled = UninstallModuleHelper(pkgPath, pkgName, out errRecord);
235+
if (errRecord != null)
236+
{
237+
errRecords.Add(errRecord);
238+
}
217239
}
218240

219241
// if we can't find the resource, write non-terminating error and return
@@ -222,17 +244,19 @@ private bool UninstallPkgHelper()
222244
if (errRecord == null)
223245
{
224246
string message = Version == null || Version.Trim().Equals("*") ?
225-
string.Format("Could not find any version of the resource '{0}' in any path", pkgName) :
226-
string.Format("Could not find verison '{0}' of the resource '{1}' in any path", Version, pkgName);
247+
string.Format("Cannot uninstall resource '{0}' because it does not exist.", pkgName) :
248+
249+
string.Format("Cannot uninstall version '{0}' of resource '{1}' because it does not exist.", Version, pkgName);
227250

228-
errRecord = new ErrorRecord(
251+
252+
errRecords.Add(new ErrorRecord(
229253
new PSInvalidOperationException(message),
230254
"ErrorRetrievingSpecifiedResource",
231255
ErrorCategory.ObjectNotFound,
232-
this);
256+
this));
233257
}
234258

235-
WriteError(errRecord);
259+
return successfullyUninstalled;
236260
}
237261
}
238262

@@ -266,7 +290,7 @@ private bool UninstallModuleHelper(string pkgPath, string pkgName, out ErrorReco
266290
try
267291
{
268292
Utils.DeleteDirectory(pkgPath);
269-
WriteVerbose(string.Format("Successfully uninstalled '{0}' from path '{1}'", pkgName, dir.FullName));
293+
WriteVerbose(string.Format("Successfully uninstalled '{0}' from path '{1}'.", pkgName, dir.FullName));
270294

271295
successfullyUninstalledPkg = true;
272296

@@ -280,20 +304,20 @@ private bool UninstallModuleHelper(string pkgPath, string pkgName, out ErrorReco
280304
}
281305
catch (Exception e)
282306
{
283-
// write error
284-
var exMessage = String.Format("Parent directory '{0}' could not be deleted: {1}", dir.Parent.FullName, e.Message);
285-
var ex = new ArgumentException(exMessage);
286-
var ErrorDeletingParentDirectory = new ErrorRecord(ex, "ErrorDeletingParentDirectory", ErrorCategory.InvalidArgument, null);
287-
errRecord = ErrorDeletingParentDirectory;
307+
errRecord = new ErrorRecord(
308+
new ArgumentException($"Parent directory '{dir.Parent.FullName}' could not be deleted: {e.Message}"),
309+
"ErrorDeletingParentDirectory",
310+
ErrorCategory.InvalidArgument,
311+
this);
288312
}
289313
}
290314
catch (Exception err)
291315
{
292-
// write error
293-
var exMessage = String.Format("Directory '{0}' could not be deleted: {1}", dir.FullName, err.Message);
294-
var ex = new ArgumentException(exMessage);
295-
var ErrorDeletingDirectory = new ErrorRecord(ex, "ErrorDeletingDirectory", ErrorCategory.PermissionDenied, null);
296-
errRecord = ErrorDeletingDirectory;
316+
errRecord = new ErrorRecord(
317+
new ArgumentException($"Parent directory '{dir.FullName}' could not be deleted: {err.Message}"),
318+
"ErrorDeletingDirectory",
319+
ErrorCategory.PermissionDenied,
320+
null);
297321
}
298322

299323
return successfullyUninstalledPkg;
@@ -331,18 +355,20 @@ private bool UninstallScriptHelper(string pkgPath, string pkgName, out ErrorReco
331355
}
332356
catch (Exception e)
333357
{
334-
var exMessage = String.Format("Script metadata file '{0}' could not be deleted: {1}", scriptXML, e.Message);
335-
var ex = new ArgumentException(exMessage);
336-
var ErrorDeletingScriptMetadataFile = new ErrorRecord(ex, "ErrorDeletingScriptMetadataFile", ErrorCategory.PermissionDenied, null);
337-
errRecord = ErrorDeletingScriptMetadataFile;
358+
errRecord = new ErrorRecord(
359+
new ArgumentException($"Script metadata file '{scriptXML}' could not be deleted: {e.Message}"),
360+
"ErrorDeletingScriptMetadataFile",
361+
ErrorCategory.PermissionDenied,
362+
this);
338363
}
339364
}
340365
catch (Exception err)
341366
{
342-
var exMessage = String.Format("Script '{0}' could not be deleted: {1}", pkgPath, err.Message);
343-
var ex = new ArgumentException(exMessage);
344-
var ErrorDeletingScript = new ErrorRecord(ex, "ErrorDeletingScript", ErrorCategory.PermissionDenied, null);
345-
errRecord = ErrorDeletingScript;
367+
errRecord = new ErrorRecord(
368+
new ArgumentException($"Script '{pkgPath}' could not be deleted: {err.Message}"),
369+
"ErrorDeletingScript",
370+
ErrorCategory.PermissionDenied,
371+
this);
346372
}
347373

348374
return successfullyUninstalledPkg;
@@ -388,8 +414,7 @@ private bool CheckIfDependency(string pkgName, out ErrorRecord errorRecord)
388414
catch (Exception e)
389415
{
390416
errorRecord = new ErrorRecord(
391-
new PSInvalidOperationException(
392-
$"Error checking if resource is a dependency: {e.Message}."),
417+
new PSInvalidOperationException($"Error checking if resource is a dependency: {e.Message}."),
393418
"UninstallPSResourceDependencyCheckError",
394419
ErrorCategory.InvalidOperation,
395420
null);
@@ -401,7 +426,8 @@ private bool CheckIfDependency(string pkgName, out ErrorRecord errorRecord)
401426

402427
errorRecord = new ErrorRecord(
403428
new PSInvalidOperationException(
404-
$"Cannot uninstall '{pkgName}'. The following package(s) take a dependency on this package: {strUniquePkgNames}. If you would still like to uninstall, rerun the command with -SkipDependencyCheck"),
429+
$"Cannot uninstall '{pkgName}'. This package depends on the following package(s): '{strUniquePkgNames}'. If you would still like to uninstall, re-run the command with -SkipDependencyCheck."),
430+
405431
"UninstallPSResourcePackageIsaDependency",
406432
ErrorCategory.InvalidOperation,
407433
null);

test/UninstallPSResourceTests/UninstallPSResource.Tests.ps1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' {
257257
$pkg = Get-InstalledPSResource "RequiredModule1"
258258
$pkg | Should -Not -Be $null
259259

260-
$ev.FullyQualifiedErrorId | Should -BeExactly 'UninstallPSResourcePackageIsaDependency,Microsoft.PowerShell.PSResourceGet.Cmdlets.UninstallPSResource', 'UninstallResourceError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UninstallPSResource'
260+
$ev.FullyQualifiedErrorId | Should -BeExactly 'UninstallPSResourcePackageIsaDependency,Microsoft.PowerShell.PSResourceGet.Cmdlets.UninstallPSResource'
261261
}
262262

263263
It "Uninstall module that is a dependency for another module using -SkipDependencyCheck" {
@@ -296,7 +296,7 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' {
296296

297297
It "Uninstall module that is not installed should throw error" {
298298
Uninstall-PSResource -Name "NonInstalledModule" -ErrorVariable ev -ErrorAction SilentlyContinue -SkipDependencyCheck
299-
$ev.FullyQualifiedErrorId | Should -BeExactly 'UninstallResourceError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UninstallPSResource'
299+
$ev.FullyQualifiedErrorId | Should -BeExactly 'ResourceNotInstalled,Microsoft.PowerShell.PSResourceGet.Cmdlets.UninstallPSResource'
300300
}
301301

302302
# Windows only

0 commit comments

Comments
 (0)