On Mar 9, 9:10*am, urkec <ur...@xxxxxx> wrote:
> I need to trap two exceptions of the same type, but I can't find a way to
> distinguish between them. So far I was only able to get the line of the
> script where exception was raised and check for variable name. Can object
> data (like for *$newinstance or $newclass) be passed to the Trap section?
> This is my code:
>
> Trap [System.Management.ManagementException]
> {
> If($_.PSBase.InvocationInfo.Line.Contains("newinstance"))
> {"The namespace exists"}
> ElseIf($_.PSBase.InvocationInfo.Line.Contains("newclass"))
> {"The class exists"}
> Else
> {"Don't know what happened"}
> Continue;
>
> }
>
> $options = New-Object System.Management.PutOptions;
> $options.Type = [System.Management.PutType]::CreateOnly;
>
> $namespace = New-Object `
> System.Management.ManagementClass `
> ("root", "__Namespace", $null);
>
> $newinstance = $namespace.PsBase.CreateInstance();
> $newinstance.Name = "MyNamespace";
> $newinstance.Put($options);
>
> $newclass = New-Object `
> System.Management.ManagementClass `
> ("root\MyNamespace", [String]::Empty, $null);
>
> $newclass["__CLASS"] = "MyClass";
> $newclass.Put($options);
>
> Thanks.
>
> --
> urkec Hi urkec,
The trick is not to use one "trap" at the top of your script, but
instead try to ensure that when your trap is invoked the scope leaves
no question as to what the problem was:
$options = New-Object System.Management.PutOptions;
$options.Type = [System.Management.PutType]::CreateOnly;
function TryPut ($wmiObj) {
trap [System.Management.ManagementException] {
write-warning "Oops! $($wmiObj.psbase.toString()) did not save
correctly."
break;
}
$wmiObj.Put($options)
}
$namespace = New-Object `
System.Management.ManagementClass `
("root", "__Namespace", $null);
$newinstance = $namespace.PsBase.CreateInstance();
$newinstance.Name = "MyNamespace";
TryPut($newinstance)
$newclass = New-Object `
System.Management.ManagementClass `
("root\MyNamespace", [String]::Empty, $null);
$newclass["__CLASS"] = "MyClass";
TryPut($newclass)
Make sense?
- Oisin
Microsoft MVP
http://www.nivot.org/