Nipun
Nipun

Reputation: 2261

Get error message details in separate varaibles

I am copying an item recursively using following code:

copy-item "D:\Work\HotfixHandling Testing\V03.02.01 Hotfixes"
-destination "D:\Work\HotfixHandling Testing\temp" -errorAction SilentlyContinue -errorVariable errors    

I get some error as destination folders already exists and get error:

Copy-Item : Item with specified name D:\Work\HotfixHandling Testing\temp\V03.02.01 Hotfixes already exists.
At D:\Work\HotfixHandling Testing\New Text Document.ps1:3 char:10
+ copy-item <<<<  "D:\Work\HotfixHandling Testing\V03.02.01 Hotfixes" -destination "D:\Work\HotfixHandling Testing\temp" -errorAction SilentlyContinue -errorVariable error
s
    + CategoryInfo          : ResourceExists: (D:\Work\HotfixH....02.01 Hotfixes:String) [Copy-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.CopyItemCommand

Now, I want to get error message, script line number and script character index seperately from error text mentioned above.

Is it possible to get these details separately?

Upvotes: 0

Views: 63

Answers (1)

PeterK
PeterK

Reputation: 3827

Once you captured the error information in the errors variable, you can access the error information you need via these properties:

# exception message, e.g. em with specified name D:\Work\HotfixHandling Testing\temp\V03.02.01 Hotfixes already exists.
$errors.Exception.Message;

# script line number, e.g. 3
$errors.InvocationInfo.ScriptLineNumber

# character offset (index) within line, e.g. 10
$errors.InvocationInfo.OffsetInLine

If you need further properties, try running $errors | Get-Member to get an idea what other properties are available.

Upvotes: 1

Related Questions