Solved

Powershell - write User to CSV, explicitly exclude part of the User from any action

Posted on 2013-06-07
10
824 Views
Last Modified: 2013-06-09
Hi,

In the Script posted below i marked the steps where i need help e.g. ### Question No. 1###

1. What is the best way to write only the USERIDs of the DB "*WEB*" to an
external CSV at this step?

2. Is there a way to exclude the User which are stored in Database (*WEB*) from the action should taken below, after identify them and write to an external file
or must be  this user explicitly exclude from any action before it should taken?

for example: ($_.Version -eq "MSXC2010" -and $_.action -eq "New" -and $user_db -notlike "*WEB*")


Import-Module ActiveDirectory 
ForEach ($User in  Import-Csv "c:\import.csv"){ #$user}
switch($user){
		         
{$_.Version -eq "MSXC2010" -and $_.aktion -eq "new"} {

			
$user_dept = (Get-ADUser -identity $user.UserID).department
$user_db = (Get-Mailbox -Identity $user.userid).Database
			
			
if($user_db -notlike "*WEB*" -and $user_dept -like "EMC") {
					
$db = "DBEMC0$("{0:00}" -f (1..43 | Get-random))"
           
Enable-Mailbox -Identity $user.UserId $DB  #here should enable all user in department EMC to Database DBEMC0 - DBEMC043

### Question No. 1 ####
}elseif ($user_db -like "*WEB*" | Out-File "c:\Temp\webUser.csv") {   #here write userids database web to a file

### Question No. 2 ####
		
		    }elseif ($user_dep -notlike "*EMC*" -and $user_db -notlike "*WEB*") {  # all user not department EMC and not Database WEB should be enable here
            
            Enable-Mailbox -Identity $user.UserId


                  }
                  else { 

                  $mbox = Get-Mailbox -Identity $User.userid
                  $mbox.EmailAddresses = $user.userid + "@emc.de"
                  $mbox.EmailAddresses+="MRS:$($user.userid)@MRS"
                  Set-Mailbox -Identity $User.userid -EmailAddresses $mbox.Emailaddresses -EmailAddressPolicyEnabled $False
                  
                     
              
   switch($user.company){
					"LCA*" {Set-Mailbox -Identity $User.userid -CustomAttribute4 'T' -CustomAttribute10 'LCA' -CustomAttribute14 'vcom'}
					"LCG*" {Set-Mailbox -Identity $User.userid -CustomAttribute4 'K' -CustomAttribute10 'LCG' -CustomAttribute14 'vcom'}
					"LCY*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LCY' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
					"LCT*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LCT' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
					"LCP*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LCP' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "LTC*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LTC' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "LVT*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LVT' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "LCN*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'LCN' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "BTL*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'BTL' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "BTM*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'BTM' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "BTS*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'BTS' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "DTN*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'DTN' -CustomAttribute4 'R' -CustomAttribute14 'vcom'}
                    "KPA*" {Set-Mailbox -Identity $User.userid -CustomAttribute10 'KPA' -CustomAttribute4 'R'  -CustomAttribute14 'vcom'}
                    default {Set-Mailbox -Identity $User.userid -CustomAttribute10 'EMC' -CustomAttribute4 'R' -CustomAttribute13 'vcom'}
}

                    $descnew = $user.orderid
                    $desccurrent = (Get-ADUser -identity $user.userid -Properties Description).Description
                    set-aduser -identity $user.userid -description ($desccurrent+"/"+$descnew+" ")
                  }
   			
			}
		{$_.Version -eq "MSXC2010" -and $_.action -eq "delete"} { 
		   
		   $dbnew = (Get-Mailbox -Identity $user.userid | Select-Object Database)
		   $desccurrent = (Get-ADUser -identity $user.userid -Properties Description).Description
           set-aduser -identity $user.userid -description ($desccurrent+"/"+$dbnew+" ")
		
			#disable mailbox exchange 2010
		   	Disable-Mailbox -Identity $user.UserID -confirm:$false
 
           
                  }
                 
                  }
           
              
            
                                # If ($_.Version -eq "MSXC2010" -and $_.action -eq "New") { 
                                {$_.Version -eq "MSXC2010" -and $_.aktion -eq "AdAccount"}  {
                              
                                $NewPassword = $user.UserId.Insert(5,"$")
                                $NewPassword = $newPassword.Insert(3,"L")
                                $NewPassword = $newPassword.Remove(0, 1)
                                $newPassword = $newPassword.Insert(0,"Z")        
                                Set-ADAccountPassword -Identity $user.UserId -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $newPassword -Force) 
                                write-host -ForegroundColor magenta "Password of $($user.UserId) has been set to $newPassword"
                              
                                "User {0}  Last PW Reset at {1}" -f $user.userid,((Get-ADUser $user.userid -properties PasswordLastSet).PasswordLastSet)

                                }
                               
                              
                                {$_.Version -eq "MSXC2010" -and $_.aktion -eq "New"} {
                               
                                
                                $PW = (Get-ADUser -identity $user.userid -properties * ).CannotChangePassword
                                If ($PW -eq $false) {
                                $GROUP = (Get-ADUser -identity $user.userid -Properties *).MemberOf | % { ($_ -split ",")[0] } | Where { $_ -like "CN=E*" }
                                If (!($GROUP)) {
                               
                                $NewPassword = $user.userid.Insert(5,"$")
                                $NewPassword = $newPassword.Insert(3,"L")
                                $NewPassword = $newPassword.Remove(0, 1)
                                $newPassword = $newPassword.Insert(0,"Z")        
                                Set-ADAccountPassword -Identity $user.userid -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $newPassword -Force) 
                                write-host -ForegroundColor yellow "Password of $($user.UserId) has been set to $newPassword"
                              
                                "User {0}  Last PW Reset at {1}" -f $user.userid,((Get-ADUser $user.userid -properties PasswordLastSet).PasswordLastSet)
                              
                                }                                          
                           
                                }
                                

Open in new window



appreciate for your help
Mandy
0
Comment
Question by:Mandy_
  • 5
  • 5
10 Comments
 
LVL 68

Expert Comment

by:Qlemo
ID: 39231404
Firstly, the code you posted doesn't look like it integrates the corrections several Experts (including me) suggested already. E.g. the "LGA*" switch statement cannot work.

Each switch condition is processed, even if a prior case was hit. To prevent from that, end the code of each case with a break. That makes the switch work more like a cascaded IF.
0
 
LVL 2

Author Comment

by:Mandy_
ID: 39231522
Hi to everyone, hi qlemo

First a big thank you to all the people who have helped me so far.

I'm sorry that i'm not able to integrate all requirements from the beginning.
The complete task is very complex and there are many variations to observed.

I checked every time at home in my virtual environment with exchange2013
every variations of user , databases, departments, password flags, group
membership and and and... You know its not easy to observe everything
at one time. I like a product at the end that makes almost everything
automatically. I dont like to spend a lot of time to fix problems gonna
happen in the live environment. I'm working for a known company
I have to anonymize my code and cannot use realnames of company, groups , user and
so on. For this it could happen that i'm writing one time LCA or DKH or
what else. Names are not important. The error occurs with that i can remove myself.

Pls just pay attention for the questions i'm asking. That are not questions to
fix the complete code itself i need to optimize it with new requirements
as a result of checking and testing.

Ok the switch statement it's already checked and its working. Above i forgot to use
the   switch -wildcard ($user.company){ parameter, but thats not my question.

I'm getting always the solution which provide first to me and build in after checking
in test environment. One time the expert resolve my last question not answering
for my next question. What should i do? Private contact as far as i know here
not allowed.  I can understand if different handwriting fonts mess up the final result.
Too many cooks spoil the porridge :)

Just pay attention for the questions i'm exactly asking then everything will be fine

Thanks to all again
Mandy
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 39231684
I understand well that it is not easy for you to provide obfuscated code. Besides, that is not important.
The issue with the code is that we need to understand what it should do, to get the "big picture". So without understanding the code (and that is for sure - I do not understand it), I have posted a recommendation for the second question: use break in each case statement block.

Another recommendation to break that lengthy code into managable parts is to use functions for each task. That way the outer switch is visually protruding, the details are a black box, and we do not need to understand their purpose fully. That has also the advantage that you can test much more easily.

I do not understand your first question - the code seems to do that already?!
0
 
LVL 2

Author Comment

by:Mandy_
ID: 39231866
hi,

First question: yes i did it already but is it the best way to do that, if i like only
the Userid to an external file?

2nd: Maybe its the better way to put it to my 1st step. At this step i'm converting my
CSV and check the output. I could check also for database web user and just remove that
lines from the CSV.  Here's my first step and i tried to implement that.

(import-csv -delimiter ';' c:\import.csv | convertto-csv -notype ) -replace "\uFEFF" | out-file c:\export.csv -encoding utf8

ForEach ($User in  Import-Csv "c:\export.csv"){$user}
foreach ($line in $user) {

$user_db = (Get-Mailbox -Identity $user.userid).Database
($user_db -like "*WEB*" | Out-File "c:\Temp\webUser.csv")  #writing only user.id with column userid
ForEach ($User in  Import-Csv "c:\Temp\webUser.csv"
foreach ($line in $user) {
$userid = (Get-Mailbox -Identity $user.userid).alias
(Get-Content "c:\export.csv") -notmatch $userid | Out-File "c:\export2.csv"

Open in new window


I did not understand "break in each case statement block"

I'm not expert in powershell but if it to difficult i should accept the error messages
i'm getting if the script try to enable an existing mailbox of this webuser,
but also the custom attributes will be change, an email address will be set
and a password reset will be done.

What you think? I think then its the better way to remove them from the CSV
before. Pls take a look to my code above.

thanks
mandy
0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
ID: 39231931
"break in each case statement block":
Import-Module ActiveDirectory 
ForEach ($User in  Import-Csv "c:\import.csv"){ 
switch($user){
{$_.Version -eq "MSXC2010" -and $_.aktion -eq "new"} {
   # code to execute here
   break
  }
{$_.Version -eq "MSXC2010" -and $_.action -eq "delete"} {
   # ...
   break
  }
}

Open in new window

but I guess that is not what you want, reading your last response.

It would be much easier to just exclude users from*WEB* db from any action, e.g. with
Import-Module ActiveDirectory 
ForEach ($User in  Import-Csv "c:\import.csv"){
  $user_dept = (Get-ADUser -identity $user.UserID).department
  $user_db = (Get-Mailbox -Identity $user.userid).Database
  if ($user_db -like '*WEB*') {
    # write log files or such
    continue   # will skip all other code, and continue with the next user
  }
  # other code
}

Open in new window

0
 
LVL 2

Author Comment

by:Mandy_
ID: 39232040
Thank you. thats what i want.  But still i have problem to write the user -like database
*web* to an logfile.

 {$user_db -like '*WEB*'} | Select Name, Alias | Export-Csv -Encoding 'Unicode' c:\temp\contacts.csv -NoTypeInformation -Append

these isn't functional because the variable stores just the database not alias and name.
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 39232218
if ($user_db -like '*WEB*') { $user | select Name, Alias | Export-CSV -NoType -Encoding Unicode C:\Temp\Contacts.csv -Append

Open in new window

I assume you are using code which has replaced Export-CSV to allow for the -Append, resp. you are running PowerShell 3 which supports it from start?
0
 
LVL 2

Author Comment

by:Mandy_
ID: 39232652
thank you. thats the one. Yes you're right. The -append not working with powershell 2.0
I dont know if the out-file command do it. But what can i use instead in earlier ps versions?


if ($user_db -like '*WEB*') { $user | select userid,name | out-file -filepath c:\webuser.csv -append 

Open in new window

0
 
LVL 68

Expert Comment

by:Qlemo
ID: 39232670
There are several options. You can use the Export-CSV expansion of http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/, or
if ($user_db -like '*WEB*') { $user | select Name, Alias | convertto-csv -NoType | select -skip 1 | out-file -Encoding Unicode C:\Temp\Contacts.csv -Append }

Open in new window

0
 
LVL 2

Author Closing Comment

by:Mandy_
ID: 39233259
thank you so much
0

Join & Write a Comment

We are happy to announce a brand new addition to our line of acclaimed email signature management products – CodeTwo Email Signatures for Office 365.
Exchange server is not supported in any cloud-hosted platform (other than Azure with Azure Premium Storage).
In this video we show how to create an Address List in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Organization >> Ad…
To show how to create a transport rule in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Mail Flow >> Rules tab.:  To cr…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now