Adeel ASIF
Adeel ASIF

Reputation: 3534

How to optimize multiple if statements in Powershell?

This is my code :

Function CleanUpOracle 
{

    if ($Requete)
    {
        $Requete.Dispose()
    }

    if ($ExecuteRequete)
    {
        $ExecuteRequete.Dispose()
    }

    if ($Transaction)
    {
        $Transaction.Dispose()
    }

    if ($OracleConnexion)
    {
        $OracleConnexion.close()
        $OracleConnexion.Dispose()
    }

    if ($Log.id)
    {

        $Log.PSObject.Properties.Remove('id')

    }

}

I'm testing if a variable exist then {do something}

But in the future I'll many variable to test, I don't want to have hundred lines with that.

How can I optimize this? Maybe with a switch but how?

Thanks !

Upvotes: 1

Views: 516

Answers (1)

Sean
Sean

Reputation: 62532

If you want to conditionally call Dispose against multiple items you can stream them from a list into the ForEach-Object (whose alias is %):

@($Requete, $ExecuteRequete, $Transaction, $OracleConnexion) |
% {if($_) {$_.Dispose()} }

NOTE: I've split this onto multiple lines for readability.

Upvotes: 5

Related Questions