Active Directory & PowerShell

Hi
I am trying to right a PowerShell script  that compares a csv of usernames and passwords against Active Directory to ensure that the AD password is correct
Can this be done?
Many thanks
Iain

Nope.
 You cannot read the passwords from AD.  In fact they aren't even stored there.  What is stored is a hash that's calculated from the password prompt when the user sets their password.  When they re-enter the password to log in, it takes
the entered password, recalculates the hash from that, and compares it to the hash that's stored in AD.
The password itself is never stored.
Edit: 
You can test a set of credentials using the username and password in the csv,
Function Test-ADAuthentication {
param($username,$password)
(new-object directoryservices.directoryentry "",$username,$password).psbase.name -ne $null
Test-ADAuthentication 'test' 'Password1'
but you can't simply read the password from AD and compare it to what's in the csv.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

Similar Messages

  • Active Directory Powershell "internal error..."

    Hey all,
    Need help on this. I have two domains A and B. I was able to do powershell AD queries on both domains. Starting yesterday, I can no longer run queries on A domain. I keep getting the error below for one of the queries. I am still able to perform AD tasks
    on the B domain with the same credential. 
    Any help is appreciated!
    Get-ADDomain : The server was unable to process the request due to an internal error.  For more information 
    about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from 
    the <serviceDebug> configuration behavior) on the server in order to send the exception information back to 
    the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the 
    server trace logs.

    How can I tell which server it is sending the query to?
    Actually, I'm not sure how PowerShell automatically determines which server it connects to when you don't specify the server via the -Server parameter. My guess is that will will try to use the closest DC it can find (try running Get-ADDomainController with
    no parameters, this gave me the results I was expecting to see).
    If your machine lives in domainB, I think you may need to always specify a domainA server via the parameter if you want to work on objects in that domain. I'm in a single domain environment, so I don't have much personal experience in working with multiple
    domains.
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Bulk create Active Directory Users and Groups in PowerShell using Excel XLSX source file instead of CSV

    Hi Scripting Guy.  I am a Server Administrator who is very familiar with Active Directory, but new to PowerShell.  Like many SysAdmins, I often need to create multiple accounts (ranging from 3-200) and add them multiple groups (ranging
    from 1 - 100).  Previously I used VBS scripts in conjunction with an Excel .XLS file (not CSV file).  Since VBS is essentially out the door and PowerShell is in - I am having to re-create everthing.
    I have written a PowerShell script that bulk creates my users and adds them to their corresponding groups - however, this can only use a CSV file (NOT an XLS file).  I understand that "CSV is much easier to use than Excel worksheets", but
    most times I have three sets of nearly identical groups (for Dev, QA and Prod).  Performing Search and Replace on the Excel template across all four Worksheets ensures the names used are consistent throughout the three environments.
    I know each Excel Worksheet can be exported as a separate CSV file and then use the PowerShell scripts as is, but since I am not the only SysAdmin who will be using these it leads to "unnecessary time lost", not to mention the reality that even
    though you clearly state "These tabs need to be exported using this naming standard" (to work with the PowerShell scripts) that is not the result.
    I've been tasked to find a way to modify my existing PowerShell/CSV scripts to work with Excel spreadsheets/workbooks instead - with no success.  I have run across many articles/forums/scirpts that let you update Excel or export AD data into an Excel
    spreadsheet (even specifying the worksheet, column and row) - but nothing for what I am trying to do.
    I can't imagine that I am the ONLY person who is in this situation/has this need.  So, I am hoping you can help.  How do I modify my existing scripts to reference "use this Excel spreadsheet, and this specific worksheet in the spreadsheet
    prior to performing the New-ADUser/Add-ADGroupMember commands".
    For reference, I am including Worksheet/Column names of my Excel Spreadsheet Template as well as the first part of my PowerShell script.  M-A-N-Y T-H-A-N-K-S in advance.
       Worksheet:  Accounts
         Columns: samAccountName, CN_DisplayName_Name, sn_LastName, givenName_FirstName, Password, Description, TargetOU
       Worksheets:  DevGroups / QAGroups / ProdGroups
         Columns:  GroupName, Members, MemberOf, Description, TargetOU
    # Load PowerShell Active Directory module
    Write-Host "Loading Active Directory PowerShell module." -foregroundcolor DarkCyan # -backgroundcolor Black
    Import-Module ActiveDirectory
    Write-Host " "
    # Set parameter for location of CSV file (so source file only needs to be listed once).
    $path = ".\CreateNewUsers-CSV.csv"
    # Import CSV file as data source for remaining script.
    $csv = Import-Csv -path $path | ForEach-Object {
    # Add '@saccounty.net' suffix to samAccountName for UserPrincipalName
    $userPrincinpal = $_."samAccountName" + "@saccounty.net"
    # Create and configure new AD User Account based on information from the CSV source file.
    Write-Host " "
    Write-Host " "
    Write-Host "Creating and configuring new user account from the CSV source file." -foregroundcolor Cyan # -backgroundcolor Black
    New-ADUser -Name $_."cn_DisplayName_Name" `
    -Path $_."TargetOU" `
    -DisplayName $_."cn_DisplayName_Name" `
    -GivenName $_."givenName_FirstName" `
    -SurName $_."sn_LastName" `
    -SamAccountName $_."samAccountName" `
    -UserPrincipalName $userPrincinpal `

    Here is the same script as a function:
    Function Get-ExcelSheet{
    Param(
    $fileName = 'C:\scripts\test.xls',
    $sheetName = 'csv2'
    $conn = New-Object System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = $fileName;Extended Properties=Excel 8.0")
    $cmd=$conn.CreateCommand()
    $cmd.CommandText="Select * from [$sheetName$]"
    $conn.open()
    $cmd.ExecuteReader()
    It is called like this:
    Get-ExcelSheet -filename c:\temp\myfilename.xslx -sheetName mysheet
    Do NOT change anything in the function and post the exact error.  If you don't have Office installed correctly or are running 64 bits with a 32 bit session you will have to adjust your system.
    ¯\_(ツ)_/¯
    HI JRV,
    My apologies for not responding sooner - I was pulled off onto another project this week.  I have included and called your Get-ExcelSheet function as best as I could...
    # Load PowerShell Active Directory module
    Write-Host "Loading Active Directory PowerShell module." -foregroundcolor DarkCyan # -backgroundcolor Black
    Import-Module ActiveDirectory
    Write-Host " "
    # JRV This Function Loads the Excel Reader
    Function Get-ExcelSheet{
    Param(
    $fileName = 'C:\scripts\test.xls',
    $sheetName = 'csv2'
    $conn = New-Object System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = $fileName;Extended Properties=Excel 8.0")
    $cmd=$conn.CreateCommand()
    $cmd.CommandText="Select * from [$sheetName$]"
    $conn.open()
    $cmd.ExecuteReader()
    # Set parameter for location of CSV file (so source file only needs to be listed once) as well as Worksheet Names.
    $sourceFile = ".\NewDocClass-XLS-Test.xlsx"
    # Add '@saccounty.net' suffix to samAccountName for UserPrincipalName
    $userPrincinpal = $_."samAccountName" + "@saccounty.net"
    # Combine GivenName & SurName for DisplayName
    $displayName = $_."sn_LastName" + ". " + $_."givenName_FirstName"
    # JRV Call the Get-ExcelSheet function, providing FileName and SheetName values
    # Pipe the data from source for remaining script.
    Get-ExcelSheet -filename "E:\AD_Bulk_Update\NewDocClass-XLS-Test.xlsx" -sheetName "Create DocClass Accts" | ForEach-Object {
    # Create and configure new AD User Account based on information from the CSV source file.
    Write-Host " "
    Write-Host " "
    Write-Host "Creating and configuring new user account from the CSV source file." -foregroundcolor Cyan # -backgroundcolor Black
    New-ADUser -Name ($_."sn_LastName" + ". " + $_."givenName_FirstName") `
    -SamAccountName $_."samAccountName" `
    -UserPrincipalName $userPrincinpal `
    -Path $_."TargetOU" `
    Below is the errors I get:
    Exception calling "Open" with "0" argument(s): "The 'Microsoft.Jet.OLEDB.4.0'
    provider is not registered on the local machine."
    At E:\AD_Bulk_Update\Create-BulkADUsers-XLS.ps1:39 char:6
    + $conn.open()
    + ~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException
    Exception calling "ExecuteReader" with "0" argument(s): "ExecuteReader
    requires an open and available Connection. The connection's current state is
    closed."
    At E:\AD_Bulk_Update\Create-BulkADUsers-XLS.ps1:40 char:6
    + $cmd.ExecuteReader()
    + ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

  • [Forum FAQ] Using PowerShell to assign permissions on Active Directory objects

    As we all know, the
    ActiveDirectoryAccessRule class is used to represent an access control entry (ACE) in the discretionary access control list (DACL) of an Active Directory Domain Services object.
    To set the permissions on Active Directory objects, the relevant classes and their enumerations are listed as below:
    System.DirectoryServices.ActiveDirectoryAccessRule class:
    http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectoryaccessrule(v=vs.110).aspx
    System.DirectoryServices.ActiveDirectoryRights
    class:
    http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectoryrights(v=vs.110).aspx
    System.Security.AccessControl.AccessControlType class:
    http://msdn.microsoft.com/en-us/library/w4ds5h86(v=vs.110).aspx
    System.DirectoryServices.ActiveDirectorySecurityInheritance class:
    http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectorysecurityinheritance(v=vs.110).aspx
    In this article, we introduce three ways to get and set the ACE on an Active Directory object. In general,
    we use Active Directory Service Interfaces (ADSI) or
    Active Directory module cmdlets
    with the Get-Acl and Set-Acl cmdlets to assign simple permissions on Active Directory objects. In addition, we can use the extended rights and GUID settings to execute
    more complex permission settings.
    Method 1: Using ADSI
      1. Get current permissions of an organization unit (OU)
    We can use the PowerShell script below to get current permissions of an organization unit and you just need to define the name of the OU.
    $Name = "OU=xxx,DC=com"
    $ADObject = [ADSI]"LDAP://$Name"
    $aclObject = $ADObject.psbase.ObjectSecurity
    $aclList = $aclObject.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
    $output=@()
    foreach($acl in $aclList)
    $objSID = New-Object System.Security.Principal.SecurityIdentifier($acl.IdentityReference)
         $info = @{
    'ActiveDirectoryRights' = $acl.ActiveDirectoryRights;
    'InheritanceType' = $acl.InheritanceType;
    'ObjectType' = $acl.ObjectType;
    'InheritedObjectType' = $acl.InheritedObjectType;
    'ObjectFlags' = $acl.ObjectFlags;
    'AccessControlType' = $acl.AccessControlType;
    'IdentityReference' = $acl.IdentityReference;
    'NTAccount' = $objSID.Translate( [System.Security.Principal.NTAccount] );
    'IsInherited' = $acl.IsInherited;
    'InheritanceFlags' = $acl.InheritanceFlags;
    'PropagationFlags' = $acl.PropagationFlags;
    $obj = New-Object -TypeName PSObject -Property $info
    $output+=$obj}
    $output
    In the figure below, you can see the results of running the script above:
    Figure 1.
    2. Assign a computer object with Full Control permission on an OU
    We can use the script below to delegate Full Control permission to the computer objects within an OU:
    $SysManObj = [ADSI]("LDAP://OU=test….,DC=com") #get the OU object
    $computer = get-adcomputer "COMPUTERNAME" #get the computer object which will be assigned with Full Control permission within an OU
    $sid = [System.Security.Principal.SecurityIdentifier] $computer.SID
    $identity = [System.Security.Principal.IdentityReference] $SID
    $adRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"
    $type = [System.Security.AccessControl.AccessControlType] "Allow"
    $inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"
    $ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$inheritanceType #set permission
    $SysManObj.psbase.ObjectSecurity.AddAccessRule($ACE)
    $SysManObj.psbase.commitchanges()
    After running the script above, you can check the computer object in Active Directory Users and Computers (ADUC) and it is under the Security tab in OU Properties.
    Method 2: Using Active Directory module with the Get-Acl and Set-Acl cmdlets
    You can use the script below to get and assign Full Control permission to a computer object on an OU:
    $acl = get-acl "ad:OU=xxx,DC=com"
    $acl.access #to get access right of the OU
    $computer = get-adcomputer "COMPUTERNAME"
    $sid = [System.Security.Principal.SecurityIdentifier] $computer.SID
    # Create a new access control entry to allow access to the OU
    $identity = [System.Security.Principal.IdentityReference] $SID
    $adRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"
    $type = [System.Security.AccessControl.AccessControlType] "Allow"
    $inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"
    $ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$inheritanceType
    # Add the ACE to the ACL, then set the ACL to save the changes
    $acl.AddAccessRule($ace)
    Set-acl -aclobject $acl "ad:OU=xxx,DC=com"
    Method 3: Using GUID setting
    The scripts above can only help us to complete simple tasks, however, we may want to execute more complex permission settings. In this scenario, we can use GUID settings to achieve
    that.
    The specific ACEs allow an administrator to delegate Active Directory specific rights (i.e. extended rights) or read/write access to a property set (i.e. a named collection of attributes) by
    setting ObjectType field in an object specific ACE to the
    rightsGuid of the extended right or property set. The delegation can also be created to target child objects of a specific class by setting the
    InheritedObjectType field to the schemaIDGuid of the class.
    We choose to use this pattern: ActiveDirectoryAccessRule(IdentityReference, ActiveDirectoryRights, AccessControlType, Guid, ActiveDirectorySecurityInheritance, Guid)
    You can use the script below to
    assign the group object with the permission to change user password on all user objects within an OU.
    $acl = get-acl "ad:OU=xxx,DC=com"
    $group = Get-ADgroup xxx
    $sid = new-object System.Security.Principal.SecurityIdentifier $group.SID
    # The following object specific ACE is to grant Group permission to change user password on all user objects under OU
    $objectguid = new-object Guid 
    00299570-246d-11d0-a768-00aa006e0529 # is the rightsGuid for the extended right User-Force-Change-Password (“Reset Password”) 
    class
    $inheritedobjectguid = new-object Guid 
    bf967aba-0de6-11d0-a285-00aa003049e2 # is the schemaIDGuid for the user
    $identity = [System.Security.Principal.IdentityReference] $SID
    $adRights = [System.DirectoryServices.ActiveDirectoryRights] "ExtendedRight"
    $type = [System.Security.AccessControl.AccessControlType]
    "Allow"
    $inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "Descendents"
    $ace = new-object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$objectGuid,$inheritanceType,$inheritedobjectguid
    $acl.AddAccessRule($ace)
    Set-acl -aclobject $acl "ad:OU=xxx,DC=com"
    The figure below shows the result of running the script above:
    Figure 2.
    In addition, if you want to assign other permissions, you can change the GUID values in the script above. The common GUID values are listed as below:
    $guidChangePassword     
    = new-object Guid ab721a53-1e2f-11d0-9819-00aa0040529b
    $guidLockoutTime        
    = new-object Guid 28630ebf-41d5-11d1-a9c1-0000f80367c1
    $guidPwdLastSet         
    = new-object Guid bf967a0a-0de6-11d0-a285-00aa003049e2
    $guidComputerObject     
    = new-object Guid bf967a86-0de6-11d0-a285-00aa003049e2
    $guidUserObject         
    = new-object Guid bf967aba-0de6-11d0-a285-00aa003049e2
    $guidLinkGroupPolicy    
    = new-object Guid f30e3bbe-9ff0-11d1-b603-0000f80367c1
    $guidGroupPolicyOptions 
    = new-object Guid f30e3bbf-9ff0-11d1-b603-0000f80367c1
    $guidResetPassword      
    = new-object Guid 00299570-246d-11d0-a768-00aa006e0529
    $guidGroupObject        
    = new-object Guid BF967A9C-0DE6-11D0-A285-00AA003049E2                                          
    $guidContactObject      
    = new-object Guid 5CB41ED0-0E4C-11D0-A286-00AA003049E2
    $guidOUObject           
    = new-object Guid BF967AA5-0DE6-11D0-A285-00AA003049E2
    $guidPrinterObject      
    = new-object Guid BF967AA8-0DE6-11D0-A285-00AA003049E2
    $guidWriteMembers   
        = new-object Guid bf9679c0-0de6-11d0-a285-00aa003049e2
    $guidNull               
    = new-object Guid 00000000-0000-0000-0000-000000000000
    $guidPublicInformation  
    = new-object Guid e48d0154-bcf8-11d1-8702-00c04fb96050
    $guidGeneralInformation 
    = new-object Guid 59ba2f42-79a2-11d0-9020-00c04fc2d3cf
    $guidPersonalInformation = new-object Guid 77B5B886-944A-11d1-AEBD-0000F80367C1
    $guidGroupMembership    
    = new-object Guid bc0ac240-79a9-11d0-9020-00c04fc2d4cf
    More information:
    Add Object Specific ACEs using Active Directory Powershell
    http://blogs.msdn.com/b/adpowershell/archive/2009/10/13/add-object-specific-aces-using-active-directory-powershell.aspx
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    The ActiveDirectoryAccessRule has more than one constructor, but yes, you've interpreted the one that takes six arguments correctly.
    Those GUIDs are different (check just before the first dash). Creating that ACE will create an empty GUID for InheritedObjectType, though, because you're telling it to apply to the Object only ([System.DirectoryServices.ActiveDirectorySecurityInheritance]::None).
    Since the ACE will only apply to the object, there's no need to worry about what types of objects will inherit it.
    If you've got time, check out
    this module. It will let you view the security descriptors in a much friendlier format. Try both version 3.0 and the version 4.0 preview:
    Sample version 3.0:
    # This is going to be kind of slow, and it will take a few seconds the first time
    # you run it because it has to build the list of GUID <--> Property/Class/etc objects
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ObjectAceType member -InheritedObjectAceType group -ActiveDirectoryRights WriteProperty
    # Same as the previous command, except limit it to access granted to GroupX
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ObjectAceType member -InheritedObjectAceType group -ActiveDirectoryRights WriteProperty -Principal GroupX
    Here's version 4.0. It's way faster than 3.0, but it's missing the -ObjectAceType and -InheritedObjectAceType parameters on Get-AccessControlEntry (don't worry, when they come back they'll be better than in 3.0):
    Get-ADGroup GroupY |
    Get-AccessControlEntry
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ActiveDirectoryRights WriteProperty
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ActiveDirectoryRights WriteProperty -Principal GroupX
    # You can do a Where-Object filter until the parameters are added back to Get-AccessControlEntry:
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ActiveDirectoryRights WriteProperty |
    where { $_.AccessMask -match "All Prop|member Prop" }
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ActiveDirectoryRights WriteProperty |
    where { $_.ObjectAceType -in ($null, [guid]::Empty, "bf9679c0-0de6-11d0-a285-00aa003049e2") }
    Get-ADGroup GroupY |
    Get-AccessControlEntry -ActiveDirectoryRights WriteProperty |
    where { $_.AccessMask -match "All Prop|member Prop" -and $_.AppliesTo -match "group"}
    That's just for viewing. Version 3.0 can add and remove access, or you can use New-AccessControlEntry to replace your call to New-Object, and you can still use Get-Acl and Set-Acl. The benefit to New-AccessControlEntry is that you can do something like this:
    New-AccessControlEntry -Principal GroupX -ActiveDirectoryRights WriteProperty -ObjectAceType member -InheritedObjectAceType group #-AppliesTo Object
     

  • Looking for Help with Active Directory Script to Remove a User from msExchDelegateListLink

    I'm struggling to put together an Active Directory Powershell script that will remove a specific user from the msExchDelegateListLink.
    It looks like Set-AdUser would do the trick. I would want to remove a user in the format of
    {CN=Wood\, Sandy,OU=Networking,OU=IT,DC=my,DC=domain,DC=com}
    Has anyone succeeded in doing this before?
    Orange County District Attorney

    I use this:
    $user = '<user name>'
    $userDN = Get-ADUser $user | select -ExpandProperty DistinguishedName
    $delegates = Get-ADUser $user -Properties msExchDelegateListBL |
    select -ExpandProperty msExchDelegateListBL
    foreach ($delegate in $delegates)
    Set-ADUser $delegate -Remove @{msExchDelegateListLink = "$UserDN"}
    Never quite got around to putting it into a function.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Trying to delete Active Directory but getting error's

    Hi There, 
    I am trying to delete an Active Directory that I have. I have removed all subscriptions from this Active Directory but now I get the message:
    Directory contains one or more applications that were added by a user or administrator.
    Under the Active Directory, I have no applications (it used to have applications and I have since removed them).
    I don't have any other subscriptions tied to this Active Directory. It could have been used for an Office 365 trial quite a few years ago.
    How can I remove this? Tried almost everything.
    Thanks

    Hello,
    A Global Administrator can delete an Azure AD directory from the Azure Management Portal. When a directory is deleted, all resources contained in the directory are also deleted; so you should be sure you don’t need the directory before you delete it.
    ERROR:  Directory has one or more applications
    If you get this error message you may have applications associated with the directory, in order to proceed with the deletion of the directory you must ensure these are removed.
    If you select the Applications pane within Azure Active Directory check the applications, and if they are not required then proceed with deleting them. If no applications are visible then you may find that you have ‘hidden’ applications that are not yet
    exposed via the UI.
    In order to delete this, you will need to use Azure Active Directory PowerShell module. You can download this (Manage Azure AD using Windows PowerShell)
    Once you have downloaded the required components and successfully installed them go ahead and launch a Powershell Console
    Connect -MsolService
    Enter your global admin credentials {example:
    [email protected]}
    It is important to note here that you wont be able to login using a Microsoft Account aka Live ID and so if this is the only identity you have. create a work account aka organizational account in the directory first to perform this action which you can
    delete once finished.
    Get -MsolServicePrincipal | Select DisplayName
    This will then show you what applications you have listed, some of which are require and won’t be able to be removed. if you don’t need any of the applications listed you can go ahead and remove them
    Get -MsolServicePrincipal | Remove-MsolServicePrincipal
    NOTE:
    You will find that some error (red text will be displayed) ignore that, those ones are service side service principals but they are white-listed and the deletion will work with them present.
    If this then fails, take a look at the PowerShell MSONLINE Log Files and if you still need further guidance, ensure to attach that to the support incident as it is super helpful to the support engineering teams when investigating the problem your having.
    These files can be found “C:\Users\%username%\AppData\Local\Microsoft\Office365\Powershell\”
    Regards,
    Neelesh.

  • Using PowerShell to import CSV data from Vendor database to manipulate Active Directory Users

    Hello,
    I have a big project I am trying to automate.  I am working in a K-12 public education IT Dept. and have been tasked with importing data that has been exported from a vendor database via .csv file into Active Directory to manage student accounts. 
    My client wants to use this data to make bulk changes  to student user accounts in AD such as moving accounts from one OU to another, modifying account attributes based on State ID, lunchroom ID, School, Grade, etc. and adding new accounts / disabling
    accounts for students no longer enrolled.
    The .csv that is exported doesn't have headers that match up with what is needed for importing in AD, so those have to be modified in this process, or set as variables to get the correct info into the correct attributes in AD or else this whole project is
    a bust.  He is tired of manually manipulating the .csv data and trying to get it onto AD with few or no errors, hence the reason it has been passed off to me.
    Since this information changes practically daily, I need a way to automate user management by accomplishing the following on a scheduled basis.
    Process must:
    Check to see if Student Number already exists
    If yes, then modify account
    Update {School Name}, {Site Code}, {School Number}, {Grade Level} (Variables)
    Add correct group memberships (School / Grade Specific)
    Move account to correct OU (OU={Grade},OU=Students,OU=Users,OU={SiteCode},DC=Domain,DC=net)
    Remove incorrect group memberships (School / Grade Specific)
    Set account status (enabled / disabled)
    If no, create account
    Import Student #
    Import CNP #
    Import Student name
    Extract First and Middle initial
    If duplicate name exists
    Create log entry for review
    Import School, School Number, Grade Level
    Add to correct Group memberships (School / Grade Specific)
    Set correct OU (OU={Grade},OU=Students,OU=Users,OU={SiteCode},DC=Domain,DC=net)
    Set account Status
    I am not familiar with Powershell, but have researched enough to know that it will be the best option for this project.  I have seen some partial solutions in VB, but I am more of an infrastructure person instead of scripting / software development. 
    I have just started creating a script and already have hit a snag.  Maybe one of you could help.
    #Connect to Active Directory
    Import-Module ActiveDirectory
    # Import iNOW user information
    $Users = import-csv C:\ADUpdate\INOW_export.csv
    #Check to see if the account already exists in AD
    ForEach ( $user in $users )
    #Assign the content to variables
    $Attr_employeeID = $users."Student Number"
    $Attr_givenName = $users."First Name"
    $Attr_middleName = $users."Middle Name"
    $Attr_sn = $users."Last Name"
    $Attr_postaldeliveryOfficeName = $users.School
    $Attr_company = $users."School Number"
    $Attr_department = $users."Grade Level"
    $Attr_cn = $Attr_givenName.Substring(0,1) + $Attr_middleName.Substring(0,1) + $Attr_sn
    IF (Get-ADUser $Attr_cn)
    {Write-Host $Attr_cn already exists in Active Directory

    Thank you for helping me with that before it became an issue later on, however, even when modified to be $Attr_sAMAaccountName i still get errors.
    #Connect to Active Directory
    Import-Module ActiveDirectory
    # Import iNOW user information
    $Users = import-csv D:\ADUpdate\Data\INOW_export.csv
    #Check to see if the account already exists in AD
    ForEach ( $user in $users )
    #Assign the content to variables
    $Attr_employeeID = $users."Student Number"
    $Attr_givenName = $users."First Name"
    $Attr_middleName = $users."Middle Name"
    $Attr_sn = $users."Last Name"
    $Attr_postaldeliveryOfficeName = $users.School
    $Attr_company = $users."School Number"
    $Attr_department = $users."Grade Level"
    $Attr_sAMAccountName = $Attr_givenName.Substring(0,1) + $Attr_middleName.Substring(0,1) + $Attr_sn
    IF (Get-ADUser $Attr_sAMAccountName)
    {Write-Host $Attr_sAMAccountName already exists in Active Directory
    PS C:\Windows\system32> D:\ADUpdate\Scripts\INOW-AD.ps1
    Get-ADUser : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser'
    required by parameter 'Identity'. Specified method is not supported.
    At D:\ADUpdate\Scripts\INOW-AD.ps1:28 char:28
    + IF (Get-ADUser $Attr_sAMAccountName)
    + ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetAD
    User

  • Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Sales Group then add to Distribution list based on Region

    Hey Scripting Guys,
    I have been in and out of Powershell last few years, not that great at it tbh !!! I'm looking for advice on how I can as in Title, Create a Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Group then add to Distribution
    list based on Region/Country
    I was thinking along the lines of get-aduser -LDAPFilter "(department=SALES France) and adding a where clause for country.
    Any help would be great.
    Dec

    So I have tried a few variations but get errors on both 
    get-aduser -LDAPFilter "(&(department=SALES)(c=us))" | Add-ADPrincipalGroupMembership -MemberOf "testgroup"
    get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADGroupMember -identity "testgroup"
    Add-ADPrincipalGroupMembership : Object reference not set to an instance of an
    object.
    At line:1 char:86
    + get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADPrincipalGroupMe
    mbership <<<< -MemberOf "testgroup"
    + CategoryInfo : NotSpecified: (:) [Add-ADPrincipalGroupMembershi
    p], NullReferenceException
    + FullyQualifiedErrorId : Object reference not set to an instance of an ob
    ject.,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMem
    bership

  • How to use Powershell to update user details in Active Directory?

    Hi,
    I received an updated contact list from HR of about 1500 names, and I want to update (make corrections and add missing data) ADUC quickly without having to do each user manually. How would I go about that using power-shell?
    The fields that need updating are:
    Under the General tab -> Description, Telephone number
    Everything under the Address tab
    Under the Telephone tab - > Mobile
    Under the Organization tab -> Job Title, Department, Company, Manager
    The server we're using is Windows Server 2008 R2.
    Many thanks,
    Nick

    There are 100 of such scripts are there online.
    here are few tips and codes. you will get more.  
    https://gallery.technet.microsoft.com/scriptcenter/Feeding-data-to-Active-0227d15c
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/10/31/use-powershell-to-modify-existing-user-accounts-in-active-directory.aspx
    http://powershell.org/wp/forums/topic/ad-import-csv-update-attributes-script/
    Please mark this as answer if it helps

  • Powershell Active Directory Account Expiration Script

    I am putting together a script that creates a user account in AD, sets the password, adds groups, etc.  The part I am having problems with is when the user selects the Contractor employee option and is prompted for the expiration date of the AD account. 
    The script will create the account, but the expiration date is not set in AD.  Any suggestions?
    Here's the code:
    #Script to create Active Directory account
    #Add the Active Directory Module if not already present
    if (-not (Get-Module ActiveDirectory))
    Import-Module ActiveDirectory -Force
    Write-Host ""
    Write-Host "======================================================" -ForegroundColor DarkYellow
    Write-Host ""
    Write-Host "Computer Access"      
    Write-Host "Create Active Directory User Script"
    Write-Host "PowerShell 3.0"
    Write-Host "Version: 1.2"                   
    Write-Host "Date: 4/14/2014"                       
    Write-Host "Author: "
    Write-Host ""
    Write-Host "Please review the created Active Directory Account" -ForegroundColor Red -BackgroundColor Yellow
    Write-Host ""
    Write-Host "Base Business Unit Group Memberships are added only" -ForegroundColor Red -BackgroundColor Yellow
    Write-Host ""
    Write-Host "======================================================" -ForegroundColor DarkYellow
    Write-Host ""
    Write-Host ""
    Write-Host "======================================================" -ForegroundColor DarkYellow
    Write-Host "Creating Active Directory Account" -ForegroundColor Yellow
    Write-Host "======================================================" -ForegroundColor DarkYellow
    Write-Host ""
    #Specify the target OU for new users
    $targetOU = "OU=Personnel,OU=ETA,DC=eta,DC=state,DC=tx"
    #Find the current domain info
    $domdns = (Get-ADDomain).dnsroot # for UPN generation
    #Set Account Variables
    #Set Username with Dialogue Box
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Font = New-Object System.Drawing.Font("Arial",10)
    $objForm.Text = "Username"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"
    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$global:setusername=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm.Close()}})
    $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({$global:setusername=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    $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(
    {$Looping=$False
    $objForm.Close()
    [environment]::Exit(0)
    $objForm.Controls.Add($CancelButton)
    $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 for the account:"
    $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(); $objTextBox.focus()})
    [void] $objForm.ShowDialog()
    #If OK then set variable and continue
    $samname = ($setusername | Out-String)
    $samname = ($setusername) + ("")
    function validateUser
        param(
        [string]$username
        #if the username is passed without domain\
        if(($username.StartsWith("domain\")) -eq $false)
            $user = Get-ADUser -Filter { SamAccountName -eq $username }
            if (!$user)
                return $false
            else
                return $true
        elseif(($username.StartsWith("domain\")) -eq $true)
            $username = ($username.Split("\")[1])
            $user = Get-ADUser -Filter { SamAccountName -eq $username }
            if (!$user)
                return $false
            else
                return $true
    $usercheck = validateUser -username $samname
    if($userCheck -eq $true) {
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [Windows.Forms.MessageBox]::Show("Username already exists in AD please check and retry",`
     "Username Check", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Stop)
    [environment]::Exit(0)
    else {} #Continue
    Write-Host ""
    Write-Host "USERNAME has been set to" $samname -ForegroundColor Yellow
    #Set User Accounts First Name
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Font = New-Object System.Drawing.Font("Arial",10)
    $objForm.Text = "First Name"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"
    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$global:setfirstname=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm.Close()}})
    $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({$global:setfirstname=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    $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(
    {$Looping=$False
    $objForm.Close()
    [environment]::Exit(0)
    $objForm.Controls.Add($CancelButton)
    $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 users first name:"
    $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(); $objTextBox.focus()})
    [void] $objForm.ShowDialog()
    #If OK then set variable and continue
    $givname = ($setfirstname | Out-String)
    $givname = ("$setfirstname") + ("")
    Write-Host ""
    Write-Host "FIRST NAME has been set to" $givname -ForegroundColor Yellow
    #Set User Accounts Last Name
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Font = New-Object System.Drawing.Font("Arial",10)
    $objForm.Text = "Last Name"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"
    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$global:setlastname=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm.Close()}})
    $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({$global:setlastname=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    $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(
    {$Looping=$False
    $objForm.Close()
    [environment]::Exit(0)
    $objForm.Controls.Add($CancelButton)
    $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 users last name:"
    $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(); $objTextBox.focus()})
    [void] $objForm.ShowDialog()
    #If OK then set variable and continue
    $surname = ($setlastname | Out-String)
    $surname = ("$setlastname") + ("")
    Write-Host ""
    Write-Host "LAST NAME has been set to" $surname -ForegroundColor Yellow
    #Set the Department Number for the Active Directory Account
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Font = New-Object System.Drawing.Font("Arial",10)
    $objForm.Text = "Cost Center"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"
    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$global:setcostcode=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm.Close()}})
    $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({$global:setcostcode=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    $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(
    {$Looping=$False
    $objForm.Close()
    [environment]::Exit(0)
    $objForm.Controls.Add($CancelButton)
    $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 cost center for the account:"
    $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(); $objTextBox.focus()})
    [void] $objForm.ShowDialog()
    #If OK then set variable and continue
    $costcode = ($setcostcode | Out-String)
    $costcode = ("$setcostcode") + ("")
    Write-Host ""
    Write-Host "COSTCODE has been set to" $costcode -ForegroundColor Yellow
    #This creates a checkbox called Employee
    $objTypeCheckbox = New-Object System.Windows.Forms.Checkbox
    $objTypeCheckbox.Location = New-Object System.Drawing.Size(10,220)
    $objTypeCheckbox.Size = New-Object System.Drawing.Size(500,20)
    $objTypeCheckbox.Text = "Employee"
    $objTypeCheckbox.TabIndex = 4
    $objForm.Controls.Add($objTypeCheckbox)
    #This creates a checkbox called Citrix User
    $objCitrixUserCheckbox = New-Object System.Windows.Forms.Checkbox
    $objCitrixUserCheckbox.Location = New-Object System.Drawing.Size(10,240)
    $objCitrixUserCheckbox.Size = New-Object System.Drawing.Size(500,20)
    $objCitrixUserCheckbox.Text = "Citrix User"
    $objCitrixUserCheckbox.TabIndex = 5
    $objForm.Controls.Add($objCitrixUserCheckbox)
    #Set Permanent or Contractor (Expiration Date)
    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $datetimepicker1 = New-Object 'System.Windows.Forms.DateTimePicker'
    $radiobuttonPermanent = New-Object 'System.Windows.Forms.RadioButton'
    $radiobuttonContractor = New-Object 'System.Windows.Forms.RadioButton'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    $radiobuttonContractor_CheckedChanged={
        if($radiobuttonContractor.Checked){
            $datetimepicker1.Visible=$true
        }else{
            $datetimepicker1.Visible=$false
    $Form_StateCorrection_Load=
        #Correct the initial state of the form to prevent the .Net maximized form issue
        $form1.WindowState = $InitialFormWindowState
    $Form_Cleanup_FormClosed=
        #Remove all event handlers from the controls
        try
            $radiobuttonContractor.remove_CheckedChanged($radiobuttonContractor_CheckedChanged)
            $form1.remove_Load($FormEvent_Load)
            $form1.remove_Load($Form_StateCorrection_Load)
            $form1.remove_FormClosed($Form_Cleanup_FormClosed)
        catch [Exception]
    $form1.Controls.Add($datetimepicker1)
    $form1.Controls.Add($radiobuttonPermanent)
    $form1.Controls.Add($radiobuttonContractor)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.ClientSize = '508, 262'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = "form1"
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = "Form"
    $form1.add_Load($FormEvent_Load)
    # datetimepicker1
    $datetimepicker1.Location = '160, 91'
    $datetimepicker1.Name = "datetimepicker1"
    $datetimepicker1.Size = '200, 20'
    $datetimepicker1.TabIndex = 3
    $datetimepicker1.Visible = $False
    # radiobuttonPermanent
    $radiobuttonPermanent.Location = '33, 57'
    $radiobuttonPermanent.Name = "radiobuttonPermanent"
    $radiobuttonPermanent.Size = '104, 24'
    $radiobuttonPermanent.TabIndex = 2
    $radiobuttonPermanent.TabStop = $True
    $radiobuttonPermanent.Text = "Permanent"
    $radiobuttonPermanent.UseVisualStyleBackColor = $True
    # radiobuttonContractor
    $radiobuttonContractor.Location = '33, 87'
    $radiobuttonContractor.Name = "radiobuttonContractor"
    $radiobuttonContractor.Size = '104, 24'
    $radiobuttonContractor.TabIndex = 1
    $radiobuttonContractor.TabStop = $True
    $radiobuttonContractor.Text = "Contractor"
    $radiobuttonContractor.UseVisualStyleBackColor = $True
    $radiobuttonContractor.add_CheckedChanged($radiobuttonContractor_CheckedChanged)
    # buttonOK
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '421, 227'
    $buttonOK.Name = "buttonOK"
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = "OK"
    $buttonOK.UseVisualStyleBackColor = $True
    #endregion Generated Form Code
    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    #Show the Form
    $form1.ShowDialog()
    #Set the password for the new user account
    #Change P@$$w0rd to whatever you want the account password to be
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Font = New-Object System.Drawing.Font("Arial",10)
    $objForm.Text = "Password"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"
    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$global:setpassword=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$objForm.Close()}})
    $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({$global:setpassword=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    $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(
    {$Looping=$False
    $objForm.Close()
    [environment]::Exit(0)
    $objForm.Controls.Add($CancelButton)
    $objLabel = New-Object System.Windows.Forms.Label
    $objLabel.Location = New-Object System.Drawing.Size(10,20)
    $objLabel.Size = New-Object System.Drawing.Size(280,40)
    $objLabel.Text = "Please enter the password you wish to set. Press Enter for P@SSw0rd:"
    $objForm.Controls.Add($objLabel)
    $objTextBox = New-Object System.Windows.Forms.TextBox
    $objTextBox.Location = New-Object System.Drawing.Size(10,60)
    $objTextBox.Size = New-Object System.Drawing.Size(260,20)
    $objForm.Controls.Add($objTextBox)
    $objForm.Topmost = $True
    $objForm.Add_Shown({$objForm.Activate(); $objTextBox.focus()})
    [void] $objForm.ShowDialog()
    #If OK then set password and continue
    $userpassword = ($setpassword | Out-String)
    $userpassword = ("$setpassword") + ("")
    if ($userpassword -eq "") {$userpassword = 'P@SSw0rd'}
    $password = (ConvertTo-SecureString $userpassword -AsPlainText -Force)
    #Set Variables for New-ADUser cmdlet
    $dplname = "$surname, $givname"
    $upname = "$givname.$surname" + "@" + "$domdns"
    $email = "$givname" + "." + "$surname" + "@eta.state.tx.us"
    $office = "WBT"
    $description = "$costcode"
    $description2 = "611IS - Permanent"
    $description3 = "611PM - Permanent"
    $description4 = "501 - Permanent"
    ##$loginscript = "yourloginscriptname"
    $servername = "teafs2"
    $homedir = "\\$($servername)\User\$($samname)"
    $homedirpath = "\\$($servername)\User\$($samname)"
    $Company= "ETA"
    $department = "yourdepartment"
    $department4 = "School Finance"
    $departmentnumber = "" + "-" + "$costcode"
    Write-Host ""
    Write-Host "HOME SERVER is" $servername -ForegroundColor Yellow
    Write-Host ""
    Write-Host "HOME DIRECTORY has been set to" $homedir -ForegroundColor Yellow
    Write-Host ""
    Write-Host "DEPARTMENT has been set to" $department -ForegroundColor Yellow
    Write-Host ""
    Write-Host "DESCRIPTION has been set to" $departmentnumber -ForegroundColor Yellow
    Write-Host ""
    #Create Active Directory Account
    New-ADUser -Name $dplname -SamAccountName $samname -DisplayName $dplname `
    -givenname $givname -surname $surname -userprincipalname $upname -emailaddress $email `
    -Path $targetou -Enabled $true -ChangePasswordAtLogon $true -Department $department `
    -OtherAttributes @{'departmentNumber'="$departmentnumber"} -Company $Company -HomeDrive "H" -HomeDirectory $homedir `
    -Description $description -Office $office -ScriptPath $loginscript -AccountPassword $password `
    #Add User to Active Directory Groups Based on Description Field
    If ((Get-ADUser $samname -Properties description).description -eq $description2) {
      Add-ADGroupMember -Identity "CN=InformationSystemsPrintGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=InformationSystemsOUDataGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=InformationSystemsNetworkAccess,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=Mail users,OU=Groups,DC=tea,DC=state,DC=tx" -Member $samname
    If ((Get-ADUser $samname -Properties description).description -eq $description3) {
      Add-ADGroupMember -Identity "CN=ProjectMgmtNetworkAccess,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=ProjectMgmtOUDataGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=ProjectMgmtPrintGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=Cognos ETASE Dev-Test-Prod,OU=Groups,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=PMO ALL,OU=Distribution Groups,OU=Mailbox accounts,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=PMO Permanent,OU=Distribution Groups,OU=Mailbox accounts,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=Mail users,OU=Groups,DC=tea,DC=state,DC=tx" -Member $samname
    If ((Get-ADUser $samname -Properties description).description -eq $description4) {
      Add-ADGroupMember -Identity "CN=SchoolFinancePrintGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=SchoolFinanceOUDataGroup,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=SchoolFinanceNetworkAccess,CN=Groups,OU=ETA,DC=tea,DC=state,DC=tx" -Member $samname
      Add-ADGroupMember -Identity "CN=Mail users,OU=Groups,DC=tea,DC=state,DC=tx" -Member $samname
    #Does the user require a mailbox?
    $mailbox = New-Object -ComObject wscript.shell
    $intAnswer = $mailbox.popup("Does this user require a mailbox?", `
    0,"Create Mailbox",32+4)
    If ($intAnswer -eq 6) {
        Add-ADGroupMember -Identity "YourADGroupName5" -Member $samname
        $mailbox.popup("User added to EMail Provisioning Group", `
        0,"Created",64+0)
    } else {
        $mailbox.popup("User has not been added to the EMail Provisioning Group", `
        0,"Not Created",64+0)
    #Does the user require a LYNC Account?
    $lyncaccount = New-Object -ComObject wscript.shell
    $intAnswer = $lyncaccount.popup("Does this user require a LYNC Account?", `
    0,"Create LYNC Account",32+4)
    If ($intAnswer -eq 6) {
        Add-ADGroupMember -Identity "YourADGroupName6" -Member $samname
        $lyncaccount.popup("User added to LYNC Provisioning Group", `
        0,"Created",64+0)
    } else {
        $lyncaccount.popup("User has not been added to the LYNC Provisioning Group", `
        0,"Not Created",64+0)
    #Create Home Directory and Set Permissions on Home Directory
    New-Item -path $homedirpath -type directory
    $acl = Get-ACL -path $homedirpath
    $permission = "yourdomainname\$($samname)","Modify","ContainerInherit,ObjectInherit","None","Allow"
    $accessrule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessrule)
    $acl | Set-ACL -path $homedirpath
    ##Set Share Permissions on Home Directory
    $Computer = $servername
    $Class = "Win32_Share"
    $Method = "Create"
    $name = $sharename
    $path = $sharedirpath
    $description = ""
    $sd = ([WMIClass] "\\$Computer\root\cimv2:Win32_SecurityDescriptor").CreateInstance()
    $ACE = ([WMIClass] "\\$Computer\root\cimv2:Win32_ACE").CreateInstance()
    $Trustee = ([WMIClass] "\\$Computer\root\cimv2:Win32_Trustee").CreateInstance()
    $Trustee.Name = "EVERYONE"
    $Trustee.Domain = $Null
    $Trustee.SID = @(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
    $ace.AccessMask = 2032127
    $ace.AceFlags = 3
    $ace.AceType = 0
    $ACE.Trustee = $Trustee
    $sd.DACL += $ACE.psObject.baseobject
    $mc = [WmiClass]"\\$Computer\ROOT\CIMV2:$Class"
    $InParams = $mc.psbase.GetMethodParameters($Method)
    $InParams.Access = $sd
    $InParams.Description = $description
    $InParams.MaximumAllowed = $Null
    $InParams.Name = $name
    $InParams.Password = $Null
    $InParams.Path = $path
    $InParams.Type = [uint32]0
    $R = $mc.PSBase.InvokeMethod($Method, $InParams, $Null)
    switch ($($R.ReturnValue))
      0 {Write-Host "Share:$name Path:$path Result:Success"; break}
      2 {Write-Host "Share:$name Path:$path Result:Access Denied" -foregroundcolor red -backgroundcolor yellow;break}
      8 {Write-Host "Share:$name Path:$path Result:Unknown Failure" -foregroundcolor red -backgroundcolor yellow;break}
      9 {Write-Host "Share:$name Path:$path Result:Invalid Name" -foregroundcolor red -backgroundcolor yellow;break}
      10 {Write-Host "Share:$name Path:$path Result:Invalid Level" -foregroundcolor red -backgroundcolor yellow;break}
      21 {Write-Host "Share:$name Path:$path Result:Invalid Parameter" -foregroundcolor red -backgroundcolor yellow;break}
      22 {Write-Host "Share:$name Path:$path Result:Duplicate Share" -foregroundcolor red -backgroundcolor yellow;break}
      23 {Write-Host "Share:$name Path:$path Result:Reedirected Path" -foregroundcolor red -backgroundcolor yellow;break}
      24 {Write-Host "Share:$name Path:$path Result:Unknown Device or Directory" -foregroundcolor red -backgroundcolor yellow;break}
      25 {Write-Host "Share:$name Path:$path Result:Network Name Not Found" -foregroundcolor red -backgroundcolor yellow;break}
      default {Write-Host "Share:$name Path:$path Result:*** Unknown Error ***" -foregroundcolor red -backgroundcolor yellow;break}

    Would you be able to show me how it's done?
    Here's an example:
    $date = Read-Host 'Enter a date (e.g. 4/23/14)'
    Write-Host "Original string: $date"
    $dateTime = [datetime]$date
    Write-Host "DateTime object: $dateTime"
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • New Version of the Azure Active Directory Module and PowerShell 2.0

    Since the last upgrade of the Azure Active Directory Module for Windows PowerShell (64-bit version), we are no longer able to load it in an application targeting .NET Framework 3.5 SP1. The error message that we receive is:
    Could not load file or assembly 'file:///C:\Windows\system32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. This assembly is built by a runtime newer
    than the currently loaded runtime and cannot be loaded.
    Our application loads and uses the Azure AD PowerShell Module for Azure AD management. The previous version of the module available until September worked well, however, we cannot use the new version because it is built using the .NET Framework 4.0 runtime,
    and our application targets .NET Framework 3.5 SP1.
    The link for the old version of the module was removed, and since the EULA for the module restricts us from making the old version available on our web site, we need a solution that would enable us
    to load the module in our application because we cannot retarget the application to a newer Framework version. In particular,
    we need a link that our customers can use to download the old version of the module.
    Is there a URL to the old version of the Azure Active Directory Module that we can download the old version from? Can someone help?

    Hi Vladimir,
    Since I'm not familiar with AZure AD, to get the old version of Azure AD Module, I also recommend you can post in Azure AD forum for more effective support:
    http://social.msdn.microsoft.com/forums/azure/en-US/home?forum=WindowsAzureAD
    However, for the error you posted, as you said, this is related to .NET version.
    I found a similar error, which was solved by upgrading the Powershell version 3.0 on Server 2008 R2 sp1, which also need to update the .NET version on server.
    Active Directory Single sign-on Office 365 Powershell Error
    If there is anything else regarding the powershell, please feel free to post back.
    Best Regards,
    Anna Wang
    Anna, yep upgrading to version 3.0 simple solve the issue. But WMF 3.0 is not compatible with few things like
    SharePoint 2010, Exchange 2007 , SCCM etc.
    WMF 3.0 has the same .NET version so how about making a configuration file in version 2.0
    I am not really sure if Azure support this but its worth to make your configuration file to support .NET 4.0
    $PShome\PowerShell_ISE.CONFIG and $PSHOME\PowerShell.exe.config will be not existing.
    So you can make an entry in configuration to support .NET framework 4.0
    like shown below
    $config_text = @"
    <?xml version="1.0"?>
    <configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0.30319"/>
    <supportedRuntime version="v2.0.50727"/>
    </startup>
    </configuration>
    $config_text| Out-File $pshome\powershell.exe.config
    $config_text| Out-File $pshome\powershell_ise.exe.config
    Close PowerShell Console and open as administrator.
    Try loading the modules back and let me know.
    Regards Chen V [MCTS SharePoint 2010]

  • FYI: Testing Active Directory Replication Latency/Convergence Through PowerShell (Update 2)

    see:
    (2014-02-01) Testing Active Directory Replication Latency/Convergence Through PowerShell (Update
    2)
    Jorge de Almeida Pinto [MVP-DS] | Principal Consultant | BLOG: http://jorgequestforknowledge.wordpress.com/

    Might that link has been been broken.Here is the link
    http://jorgequestforknowledge.wordpress.com/2014/02/01/testing-active-directory-replication-latencyconvergence-through-powershell-update-2/
    Nice Jorge. Thanks for sharing.
    Regards~Biswajit
    Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights.
    MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, MCTS, Enterprise Admin
    MY BLOG
    Domain Controllers inventory-Quest Powershell
    Generate Report for Bulk Servers-LastBootUpTime,SerialNumber,InstallDate
    Generate a Report for installed Hotfix for Bulk Servers

  • PowerShell Active Directory: Get last logon date of a deleted user

    So, my first post in this noble community. I've been lurking here and I've been getting some good information. Hopefully, you guys can help me in this concern which may be simple to some but I couldn't seem to get around it.
    Is it possible to get the last logon date of a DELETED user in Active Directory?
    I can get the available properties of deleted users using the following:
    Get-ADObject -Filter {samaccountname -eq <account_name> -and ObjectClass -eq "user"} -IncludeDeletedObjects -Properties *
    But the last logon date is not one of the properties available from Get-ADObject. Get-ADUser has the last logon property, but it does not have data on deleted users. Is there anyway this can be achieved? Perhaps convert an ADObject to an ADUser?
    Any information would be much appreciated. Thank you.

    Thanks everyone for your response. It looks like jrv is leading me to the right path, but I'm still having issues. I'm trying to get the lastlogon time by querying all the DCs in our domain, but every query returns a null lastlogon time for all the deleted
    users I tried:
    $DomainControllers = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ }).Name
    foreach ($DC in $DomainControllers)
        $dn=(Get-ADObject -Filter {samaccountname -eq <user_account>} -includedeletedobjects -server $DC).DistinguishedName
        $user=[adsi]"LDAP://$dn"
        $user.LastLogon
    It always returns null. Morever, simply executing [adsi]"LDAP://$dn" from each DC gives the following error:
    format-default : The following exception occurred while retrieving member
    "distinguishedName": "There is no such object on the server.
        + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedType
       SystemException
        + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Comm
       ands.FormatDefaultCommand
    It's a bit surprising to me though, since $user=[adsi]"LDAP://$dn" does return a value for $user (instead of null whenever an error is encountered) of type System.DirectoryServices.DirectoryEntry but it has no members.
    Anyone know what I'm missing?

  • SBS 2008 - Microsoft Azure Active Directory Module for Windows PowerShell - is not supported by your version

    Hi,
    I was following the artigle (http://www.messageops.com/resources/office-365-documentation/ad-fs-with-office-365-step-by-step-guide/) but
    when try to install the 'Office 365 PowerShell Module' shows a msg saying that 'windows azure active directory module for windows powershell is not supported by your version'.
    And according to the blog (http://blogs.office.com/2014/04/15/synchronizing-your-directory-with-office-365-is-easy/) "DirSync can be
    installed on an existing domain controller"
    >>>> Any help is appreciated.
    * Similar issue: http://www.adaxes.com/forum/post7398.html

    Ok Vasil tks for reply, but this server is 64x. I dont get the point.
    Microsoft Windows [Version 6.0.6002]
    C:\Users\Administrator>set
    ALLUSERSPROFILE=C:\ProgramData
    APPDATA=C:\Users\Administrator\AppData\Roaming
    CLIENTNAME=ANJOTEC_NOTE01
    CommonProgramFiles=C:\Program Files\Common Files
    CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    COMPUTERNAME=COMPANYBR-SERVER
    ComSpec=C:\Windows\system32\cmd.exe
    FP_NO_HOST_CHECK=NO
    HOMEDRIVE=C:
    HOMEPATH=\Users\Administrator
    lib=C:\Program Files\SQLXML 4.0\bin\
    LOCALAPPDATA=C:\Users\Administrator\AppData\Local
    LOGONSERVER=\\COMPANYBR-SERVER
    NUMBER_OF_PROCESSORS=4
    OS=Windows_NT
    Path=C:\ProgramData\Oracle\Java\javapath;C:\Program Files\HP\NCU;C:\Windows\sys
    em32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\
    1.0\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program File
    (x86)\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Serve
    \90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program F
    les (x86)\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files (x86)\Microsoft SQ
    Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Vis
    al Studio 8\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\ExchangeMapi\
    C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x
    6)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Rox
    o Shared\9.0\DLLShared\;C:\Program Files\Microsoft\Exchange Server\bin;C:\Progr
    m Files\Microsoft\Exchange Server\Scripts
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE=AMD64
    PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 30 Stepping 5, GenuineIntel
    PROCESSOR_LEVEL=6
    PROCESSOR_REVISION=1e05
    ProgramData=C:\ProgramData
    ProgramFiles=C:\Program Files
    ProgramFiles(x86)=C:\Program Files (x86)
    PROMPT=$P$G
    PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
    PUBLIC=C:\Users\Public
    RoxioCentral=C:\Program Files (x86)\Common Files\Roxio Shared\9.0\Roxio Central
    3\
    SESSIONNAME=RDP-Tcp#0
    SystemDrive=C:
    SystemRoot=C:\Windows
    TEMP=C:\Users\Administrator\AppData\Local\Temp\2
    TMP=C:\Users\Administrator\AppData\Local\Temp\2
    USERDNSDOMAIN=COMPANYBR.LOCAL
    USERDOMAIN=COMPANYBR
    USERNAME=administrator
    USERPROFILE=C:\Users\Administrator
    windir=C:\Windows
    C:\Users\Administrator>

  • PowerShell and Active Directory

    Jpacella wrote:
    I get that they're trying to have personality and perhaps bring some color to dreadfully boring topics :) but I guess i'ma crabby old man and just want them to get to the point :)
    I was that way at first, but got used to his personality. Besides those topics in the AD series are so interesting they don't need much animation lol. I've learned a great deal from that series so far, mainly the stale object section.

    If you work with Active Directory at all, which if you're a windows admin.. well you do. You HAVE TO WATCH THIS!! It teaches you almost everything you need to know about Active Directory and PowerShell. It's very applicable and interactive.
    http://www.microsoftvirtualacademy.com/training-courses/using-powershell-for-active-directory
    This topic first appeared in the Spiceworks Community

Maybe you are looking for