Capture and redirect warning messages

Hello,

I have a script that is executing a ConfigMgr cmdlet:

New-CMDeviceCollection -Name $CNAME -LimitingCollectionName "All Systems" -RefreshType Both

When executed, if a collection already exists with the provided name it outputs the following warning message:

WARNING: The collection cannot be created because a collection with the specified name already exists. Create a collection with a different name.

I would like to capture this message and redirect its output to the screen in the following format:

WARNING: $CNAME cannot be created because a collection with the specified name already exists.

I have read about using 3>&1 but I'm having trouble finding a similar example to follow. Any help is greatly appreciated!

September 9th, 2015 11:08am

Hi,

Here you go:

https://technet.microsoft.com/en-us/library/hh847746%28v=wps.630%29.aspx

Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 11:21am

Hi,

you could check the exsistance of the collection before running into that error.

Something like:

if (Get-CMDeviceCollection -Name $CNAME){
    Write-Warning "The collection cannot be created ..."
}
else {
    New-CMDeviceCollection -Name $CNAME ...
}


September 9th, 2015 11:28am

Thanks Mike. I actually found the 3>&1 redirection method from that article. However, in the example provided it is simply adding a custom warning message. I want to capture the built-in warning that New-CMDeviceCollection is using, and rewrite it in my output. I'm using Try/Catch to do so, but haven't had any luck thus far.
Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 11:36am

Does the cmdlet have a -WarningVariable parameter available? If so, you can use that to capture the warning.
September 9th, 2015 11:37am

I'm trying both IF/ELSE and WarningVariable now. I'd like the least amount of code and it looks like -WarningVariable is an option.

Thanks for the feedback!

Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 11:47am

I played with this a bit and I had to do some trickery to suppress the original warning:

$CNAME = Read-Host 'Enter collection name'

try {

    New-CMDeviceCollection -Name $CNAME -LimitingCollectionName 'All Systems' -WarningAction SilentlyContinue -WarningVariable trigger

} catch {

    If ($trigger) {
    
        Write-Warning "$CNAME cannot be created because a collection with the specified name already exists."
        Remove-Variable trigger

    }

}

September 9th, 2015 12:07pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics