Home > Software engineering >  Use Powershell variable in another variable / in parameter of a commandlet
Use Powershell variable in another variable / in parameter of a commandlet

Time:06-11

I would like to use a variable with variable name in 2 examples

Example 1:

$Myvalue1 = "$AutomateProcessing"

I want to put $false in my variable $AutomateProcessing using

$"$Myvalue1" = $false 

(in place of $AutomateProcessing = $false)

Example 2:

$Myvalue2 = "AutomateProcessing"

Get-EXOMailbox $MyMBX | set-CalendarProcessing -$Myvalue2 $MyConfig

(in place of Get-EXOMailbox $MyMBX | set-CalendarProcessing -AutomateProcessing $MyConfig)

With this, I could create a loop with a lot of parameters I want to modifiy.

Is it possible to do with PowerShell?

Thank you in advance

CodePudding user response:

You can use the cmdlet set-variable.

Use switch "Variable" to define your variable (without $ sign) and the switch "Value" for the value.

$AutomateProcessing=$true
$Myvalue1 = "AutomateProcessing"
Set-Variable -Name $Myvalue1 -Value $false
Out-Host -InputObject "Variable $Myvalue1 is now set to $AutomateProcessing"

The result:

Variable AutomateProcessing is now set to False

CodePudding user response:

The first part is not clear.

On the second example you mentioned, You can achieve this if you store the entire commandlet as a string first and use Invoke-Expression to trigger it.

Something like this.

[string] $FullCommandlet = "Get-EXOMailbox $MyMBX | set-CalendarProcessing -$Myvalue2 $MyConfig"

Invoke-Expression -Command $FullCommandlet

Hope that helps !

CodePudding user response:

Try Splatting your parameters in from a hashtable

Param(
[array]$MyMBX = <array>,
[String]$AddOrganizerToSubject = <value>,
[bool]$AutomateProcessing = <value>,
[bool]$AllowRecurringMeetings = <value>
)
Foreach($mbx in $MyMBX){
$Myconfig = @{'Identity' = (Get-EXOMailbox -Identity $mbx)
             'AutomateProcessing' = $AutomateProcessing 
             'AddOrganizerToSubject' = $AddOrganizerToSubject
             'AllowRecurringMeetings' = $AllowRecurringMeetings
              }# etc etc
Set-CalendarProcessing @Myconfig
}
  • Related