Switch Parameters

This topic contains 3 replies, has 2 voices, and was last updated by  Max Kozlov 2 months, 4 weeks ago.

  • Author
    Posts
  • #71528

    Juli
    Participant

    A lot of my powershell work consists of creating things in bulk using PowerShell and csv files. Is it possible to pass a switch parameter in the csv file?

    Example: Resource Mailboxes

    -Shared
    -Room
    -Equipment

    foreach ($_ in (Import-csv C:\exchangetools\sharedmailbox.csv)) {
    New-Mailbox -Name $_.Name -Alias $_.Alias -OrganizationalUnit $_.OrgUnit -FirstName $_.FirstName -LastName $_.LastName -Database $_.Database -Room
    }

    It would be great to be able to populate a csv file to create multiple resource mailboxes of mixed types (shared, room, equipment) and just run one simple script and pass the switch parameter via the file.

    Yes I could create a script with a switch to read that value and then run the right script for that item, but I am all about the least amount of duplication that is possible.

  • #71531

    Max Kozlov
    Participant

    Why you do not show code you use ?

    the shortest way is splatting. something like that

    $csv = 'Name, Email, Type
    room1, room1@corp.com, Shared
    equip1, eq1@corp.com, Equipment' | ConvertFrom-Csv -Delimiter ','
    
    $csv | Foreacn-Object {
      $params = @{
        name=$_.Name
        email=$_.email
      }
      $params.$type = $true
      new-mailbox @params
    }
    
    • #71534

      Juli
      Participant

      I added the script. If you notice the identifier -room it's a switch parameter, not a value for a parameter and you don't show in your answer how the script is seeing that in the csv file to process the new-mailbox command properly.

  • #71570

    Max Kozlov
    Participant

    Sorry, before line 10 in my example should be $type = $_.Type

    But I thought that you can find the error yourself 🙂

    About switches: take into account than switches can be used as -switch and as -Switch:$true (or $false)

    and finally, if you can't see how parameters goes into new-mailbox, you should `Get-Help about_Splatting`

    p.s. example it just example and may not match real new-mailbox parameters, but it correctly show the conception

You must be logged in to reply to this topic.