0

Is it a way to remove the rows which doesn't contain any value-data? For this script, for example, the 'Department' value field is empty, I would like to trim it out.

    [System.Object]$ADOutputSelectedValues = [ordered] @{

    'FirstName'  = $ADReturnObject.FirstName
    'LastName'   = $ADReturnObject.LastName
    'Location'   = $ADReturnObject.Location
    'Department' = $ADReturnObject.Department
    'Epost'      = $ADReturnObject.Epost
    'Id'         = $ADReturnObject.Id

}

$Output = New-Object -TypeName psobject -Property $ADOutputSelectedValues

$Output

Edit: The current output is:

FirstName  : Donald
LastName   : Duck
Location   : Dugburg
Department : 
Epost      : [email protected]
Id         : 313

Would like it to look like this:

FirstName  : Donald
LastName   : Duck
Location   : Dugburg
Epost      : [email protected]
Id         : 313

In advance, thanks.

3
  • you can't remove a property. [grin] instead, you need to build a new object that leaves the property out by using something like Select-Object. ///// however, that will remove the item from ALL objects, not just the one. if you add code to remove the prop from only the one ... you will have a collection that cannot be exported to a CSV since that requires that the 1st object decide what all other objects props will be. Commented Oct 9, 2019 at 18:21
  • @Lee_Dailey It's not possible to to filter it out by select | where {$_.Value -notlike ' '} or something like that? Commented Oct 9, 2019 at 19:24
  • i presumed you wanted to modify an existing custom object - apparently you want to modify a hashtable. oops! [blush] you cannot REMOVE a property, but you can remove a key-value pair from a hashtable by using the .Remove() method. ///// still, if you make a custom object of that item, you will need to be careful to make the same change to all the objects IF you intend to export them to a CSV file, since the 1st object will determine the columns for all the remaining objects. Commented Oct 9, 2019 at 23:10

1 Answer 1

1

In my own coding, I've made a function to help with cases like this.

Function Remove-EmptyValuesFromHashtable
{
    Param( [Parameter(Mandatory=$True)] [Hashtable] $Hashtable )

    $NewHashtable = @{}

    foreach ($Key in $Hashtable.Keys)
    {
        if ($Hashtable.$Key -as [Bool])
        {
            $NewHashtable += @{ $Key=$Hashtable.$Key }
        }
    }

    return $NewHashtable
}

Note that "empty values" includes $Null, empty string, $False. If you don't want it to remove $False values, you'll have to modify it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.