Saturday, 15 January 2011

powershell - Handle output that can either be an array or a single string -


I have a script that receives data from the web service in XML format. Some elements can be there - or not - and it may contain one or more sub elements, so I get the value with it:

$ uid = $ changeRecord.newAttrs | Where {$ _. Name-EC 'UID'} | Choose - Expand Property Value | Selection Index 0

This works fine in most of the answer There is only one sub element in the part and even if not, then I am only interested in the first one, however, the last part | Select -index 0 generates silent warnings in the Windows Event Log (see also) if & lt; Values ​​& gt; Within there is only one element so I would like to get rid of the error.

That's why I'm looking for errors to get the same behavior without any errors - and possibly not just try- hold around.

Thank you!

// Update: As mentioned below, so far the answers do not solve the problem. So far the closest is

  ([array] ($ changeRecord.newAttrs | where {$ _ .name-eq 'uid'} | Select- ExpandPrafficity Value)) [0]  

This fails with any errors if there is no element in the array. With any thought it can be controlled even within a line?

Have you tried this: choose-object-first 1 ?

  $ uid = $ changeRecord.newAttrs | Where-object {$ _. Name-EC 'UID'} | Selection-object-ExpandProfility Value | Choose-Object-First 1  

No comments:

Post a Comment