0

I'm writing a PowerShell script to add / remove people from a distribution group. I want to send a message if the action was successful and another if it failed. This is part of the script:

foreach ($x in Get-Content $pathfile\inputfile.txt) {
$USER = $x.Split(',')[0]
$ACTION = $x.Split(',')[1]
$COMMAND = (Write-Output "$ACTION-DistributionGroupMember -Identity 'Group Name' -Member $USER")
if ($ACTION -ieq "remove") {
$COMMAND = $COMMAND + ' -Confirm:$false'
Invoke-Expression $COMMAND
}
else {
Invoke-Expression $COMMAND
}
}

inputfile.txt, for the sake of information is:

jdoe@example.com,Add
jsmith@example.com,Remove

I've tried using $? and $lasExitCode but neither of those worked as expected as they only consider the output of "Invoke-Expression" and that is always successful.

What I am expecting is:

foreach ($x in Get-Content $pathfile\inputfile.txt) {
$USER = $x.Split(',')[0]
$ACTION = $x.Split(',')[1]
$COMMAND = (Write-Output "$ACTION-DistributionGroupMember -Identity 'Group Name' -Member $USER")
if ($ACTION -ieq "remove") {
$COMMAND = $COMMAND + ' -Confirm:$false'
Invoke-Expression $COMMAND

#if $COMMAND successful: Write-Output "$ACTION on $USER succeeded."
#if $COMMAND unsuccessful: Write-Output "$ACTION on $USER failed."

}
else {
Invoke-Expression $COMMAND

#if $COMMAND successful: Write-Output "$ACTION on $USER succeeded."
#if $COMMAND unsuccessful: Write-Output "$ACTION on $USER failed."

}
}
  • Does this answer your question? [How to get status of "Invoke-Expression", successful or failed?](https://stackoverflow.com/questions/32348794/how-to-get-status-of-invoke-expression-successful-or-failed) – Paolo Jan 21 '23 at 11:11
  • To add to Mathias' answer: [`Invoke-Expression` (`iex`) should generally be avoided](https://stackoverflow.com/a/51252636/45375); definitely [don't use it to invoke an external program or PowerShell script / command](https://stackoverflow.com/a/57966347/45375). – mklement0 Jan 22 '23 at 14:54

1 Answers1

0

$? won't work because even if the command fails, Invoke-Expression was invoked successfully.

Use the & call operator to invoke the call directly instead, and $? will work. For the conditional parameter argument, use splatting!

foreach ($x in Get-Content $pathfile\inputfile.txt) {
    $user,$action,$null = $x.Split(',')

    # construct command name
    $command = "$ACTION-DistributionGroupMember"

    # organize the parameter arguments in a hashtable for splatting later
    $paramArgs = @{
        Identity = 'Group Name'
        Member   = $USER
    }
    
    # conditionally add the `-Confirm` parameter
    if ($ACTION -ieq "remove") {
        $paramArgs['Confirm'] = $false
    }

    # invoke the command with the call operator
    & $command @paramArgs

    if($?){
        # command invocation suceeded
    }
    else {
        # command invocation failed
    }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206