Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Tuesday, May 19, 2015

Office 365 - Licensing Users in Bulk

If you've signed your business up for Office 365, you are probably well aware of their license offerings and that you must assign them to users as you go.  You may be using a variety of licenses such as the Exchange Standard license or the Office Subscription license.  If you automate user creation, you can add a license at creation time or after they are already created.  In this example, I'll show how to license user's who are already created.

If you are unsure on how to connect to your instance of Office 365, please see my other blog post on connecting: Connect to Office365

First, you need to find your AccountSKUID

 Get-MsolAccountSku  

This will return a column called AccountSkuID.  You will insert this into the script below where you see the term AccountSkuID.

This example shows how you can feed a list of existing users via a txt or csv file.  The file I use only has one column with no header.  This list contains the user ID portion of the user's email address only.  For example if the user's email address is 12345@mydomain.com, the user ID is 12345.

 import-module msonline  
 $Username = "admin@yourdomain.com"  
 $Password = ConvertTo-SecureString 'P@$$w0rd' -AsPlainText -Force  
 $cred = New-Object System.Management.Automation.PSCredential $Username, $Password  
 connect-msolservice -credential $cred  
 $users = Get-Content c:\scripts\msolusers.csv  
 foreach($user in $users){  
 set-msoluserlicense -userprincipalname $user@yourdomain.com -addlicenses AccountSkuID:OFFICESUBSCRIPTION  
 }  

Alternatively, if you'd like to license all user's who are currently in your Office 365 system, use the following script:


 import-module msonline  
 $Username = "admin@yourdomain.com"  
 $Password = ConvertTo-SecureString 'P@$$w0rd' -AsPlainText -Force  
 $cred = New-Object System.Management.Automation.PSCredential $Username, $Password  
 connect-msolservice -credential $cred  
 $users = Get-MsolUser -all | select userprincipalname  
 foreach($user in $users){  
 set-msoluserlicense -userprincipalname $user -addlicenses AccountSkuID:OFFICESUBSCRIPTION  
 }  

Disclaimer: All scripts and other powershell references on this blog are offered "as is" with no warranty.  While these scripts are tested and working in my environment, it is recommended that you test these scripts in a test environment before using in your production environment.

Thursday, July 19, 2012

Powershell: Working with CSV Files

Today I'm going to talk about interacting with CSV files using powershell.  You may use CSV files to store values temporarily for a script, or you may be creating user accounts in Active Directory.  I'll be going over the process of how to read the file and declare variables for the headers.

The root of the whole process is importing a CSV file you've created.  The command to do this is:

Import-Csv pathtocsvfile

So that reads the file but how do we interact with the data?  The following example shows how you can process a csv file one row at a time.  This script simply echoes the data stored in the 2 columns in the csv file.



 $testcsv = import-csv c:\scripts\test.csv
  
 
  
 foreach($test in $testcsv)
  
   {
  
   $field1 = $test.field1
  
   $field2 = $test.field2
  
   
  
   Echo "$field1, $field2"
  
   }
  
     


So to break this out piece by piece:

1. This imports the csv file and stores it in the variable $testcsv

$testcsv = import-csv c:\scripts\test.csv

2.  This starts a "foreach loop" to process the csv file row by row.  The first variable, $test, can be named anything you want it to be.  I find it good practice to name it something relevent to the import-csv variable.  The second variable is the one we defined earlier for importing the csv file.

foreach($test in $testcsv)

3. Start the loop with a {

{

4.  This part is how we tie variables to the column headers in the csv file.  Again, name these what you want.  I like to name them after the column headers.  Set them equal to the $test variable dot (.) the column header they are tied to.

$field1 = $test.field1
$field2 = $test.field2


5.  This is the command we are going to run each row through.  Use the variables from the last step in the command.  Here we are telling powershell to echo field1 and field2.  Again, each row in the csv will run through this command.

Echo "$field1, $field2"

6.  Close the foreach loop with one of these }

}


My csv called test.csv looks like this:

Field1,Field2
data1,data2
data3,data3

When I run this script in powershell, I see the output of rows 1 and 2:



Create Active Directory Accounts from a CSV file with Powershell


Here's another example of how you can create Active Directory accounts using this method.





 ##########################################################################
  
 #     Create Active Directory Users from CSV
  
 #
  
 # This script will allow you to import users from a csv file
  
 # and create an active directory account for each of them. This requires
  
 # your domain and forest functional level to be 2008 R2.
  
 #
  
 # Source: ps1scripting.blogspot.com
  
 #
  
 ##########################################################################
  
 
  
 
  
 #Imports active directory module for running AD cmdlets
  
 Import-Module active directory
  
 
  
 #variable to store the data in adusers.csv
  
 $adusers = Import-csv c:\scripts\adusers.csv
  
 
  
 #This will process the CSV row by row. Each row contains information to create an active directory account for a user.
  
 foreach ($user in $adusers)
  
   {
  
   
  
   $username = $user.username
  
   $password = $user.password
  
   $firstname = $user.firstname
  
   $lastname = $user.lastname
  
   
  
   #create AD Acct #sets for username  #sets account name      #sets first name   #sets lastname  #enables account #sets display name        #sets login script path
  
   new-aduser -samaccountname $username -name "$lastname, $firstname" -givenname $firstname -surname $lastname -enabled $true -displayname "$lastname, $firstname" -scriptpath "\\server\loginscript.bat" -accountpassword (convertto-securestring $password -asplaintext -force)
  
   
  
   }  


I like to automate the Active Directory account creation process by using SQLCMD to select users from a SQL database and output them to a csv file.  Set these scripts up as scheduled tasks and let powershell do the rest!


Disclaimer: All scripts and other powershell references on this blog are offered "as is" with no warranty.  While these scripts are tested and working in my environment, it is recommended that you test these scripts in a test environment before using in your production environment.

Tuesday, July 17, 2012

Active Directory: Restore User from AD Recycle Bin

Ever deleted accidently deleted a user from active directory only to find that they need their account restored?  You can recreate the account manually but the SID (security identifier) will be different the second time around causing you to have to reestablish group membership, folder permissions, remount Exchange mailbox, etc. 

If you are running a Windows 2008 R2 domain environment with your domain and forest functional level at 2008 R2, there's a handy new feature call the Active Directory recycly bin.  This is only accessible through powershell which is kind of a bite, but in the script below, I've integrated a simple .net form with the cmdlet required to perform the object restore.  You will have to enable this feature first to use it and there's no going back if you do (why would you want to?).

To enable this feature, run powershell as administrator and run the following cmdlet and replace all instances of "yourdomain.com" with your AD domain info.

 Enable-ADOptionalFeature –Identity ‘CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=yourdomain,DC=com’ –Scope ForestOrConfigurationSet –Target ‘yourdomain.com’
  

As I mentioned above, I am using a simple .net form to create somewhat of a nice GUI for running this cmdlet.  I got the form from here:  http://technet.microsoft.com/en-us/library/ff730941 .  Check out this page if you'd like to learn more about it.

When you run the script below, you will see the following window pop up:

Simply type in the account name of the user that was deleted and click ok.  Like magic, the user with their SID is restored.  Their exchange mailbox is automatically reconnected (if it still exists and isn't connected to another account), and they should have access to any folder they did before.  It's like they were never deleted.  Here's the script, save it as Restore_AD_Account.ps1


 ######################################################################################  
#           Restore Active Directory Account  
# This script utilizes the Windows 2008 R2 AD ability to undelete an account  
# Your forest and domain functional level must be 2008 R2  
#  
# Source: ps1scripting.blogspot.com  
#  
#
#####################################################################################
  
  
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")   
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
  
   
#The objform.txt names the form window  
$objForm = New-Object System.Windows.Forms.Form   
$objForm.Text = "Restore Active Directory User"  
$objForm.Size = New-Object System.Drawing.Size(300,200)   
$objForm.StartPosition = "CenterScreen"
  
 
  
$objForm.KeyPreview = $True  
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
  {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
     {$objForm.Close()}})
  
 
  
#This labels the OK button
$OKButton = New-Object System.Windows.Forms.Button  
$OKButton.Location = New-Object System.Drawing.Size(75,120)  
$OKButton.Size = New-Object System.Drawing.Size(75,23)  
$OKButton.Text = "OK"  
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()}) 
$objForm.Controls.Add($OKButton)
  
   
#This labels the cancel button
$CancelButton = New-Object System.Windows.Forms.Button 
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)  
$CancelButton.Text = "Cancel" 
$CancelButton.Add_Click({$objForm.Close()})  
$objForm.Controls.Add($CancelButton) 
  
#This gives a description in the window  
$objLabel = New-Object System.Windows.Forms.Label  
$objLabel.Location = New-Object System.Drawing.Size(10,20)   
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
  
$objLabel.Text = "Please enter the username you'd like to restore below:"  
$objForm.Controls.Add($objLabel) 
  
  
$objTextBox = New-Object System.Windows.Forms.TextBox 
$objTextBox.Location = New-Object System.Drawing.Size(10,40)   
$objTextBox.Size = New-Object System.Drawing.Size(260,20)   
$objForm.Controls.Add($objTextBox) 
  
 
  
$objForm.Topmost = $True
  
   
$objForm.Add_Shown({$objForm.Activate()})  
[void] $objForm.ShowDialog()
  
 
#$x variable is passed to powershell cmdlets below
$x
  
#imports active directory module to run AD cmdlets
Import-Module activedirectory
  
#searches AD for object stored in variable by samaccount name and restores it 
get-adobject -filter {samaccountname -eq $x } -includedeletedobjects | restore-adobject
  
 
  
   


This is really a very simple script.  95% of it is just the code required to construct the form.  Let me know if you have any questions.


Disclaimer: All scripts and other powershell references on this blog are offered "as is" with no warranty.  While these scripts are tested and working in my environment, it is recommended that you test these scripts in a test environment before using in your production environment.