Generate powershell command from input

Daniel Kaliel 1,111 Reputation points

I have a function to set a users out of office. Don't ask, I know that a user could set this through their outlook on their phone or their PC, but we have a need for this internally. Unfortunately. What I need is to build out the Set-MailboxAutoReplyConfiguration dynamically. So, if there is valid input in the $message variable add -InternalMessage $message -ExternalMessage $message to Set-MailboxAutoReplyConfiguration. If their is no valid input or the input is null don't add it.

I tried this but it failed.

                if ( ($StartDate) -or ($EndDate) ) { $args += '-AutoReplyState Scheduled ' } else { $args += '-AutoReplyState Enabled ' }  
                if ($StartDate) { $args += '-StartTime $StartDate ' }  
                if ($EndDate) { $args += '-EndTime $EndDate ' }  
                if ($Message) { $args += '-InternalMessage "$Message" -ExternalMessage "$Message" ' }  

                Set-MailboxAutoReplyConfiguration $User -Confirm:$False $args  
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,884 questions
{count} votes

Accepted answer
  1. Rich Matheisen 38,821 Reputation points

    Use "splatting" to do this.

    $parameters = @{}  
    $parameters['AutoReplyState'] = if ( ($StartDate) -or ($EndDate) ) {'Scheduled'} else {'Enabled'}  
    if ($StartDate) { $parameters['StartTime'] = $StartDate}  
    if ($EndDate) { $parameters['EndTime'] = $EndDate}  
    if ($Message) { $parameters['InternalMessage'] = "$Message"; $parameters['ExternalMessage'] = $Message }  
    $parameters['Confirm'] = $false  
    $parameters['Identity'] = $User  
    Set-MailboxAutoReplyConfiguration @parameters  
    0 comments No comments

0 additional answers

Sort by: Most helpful