Solved

Script to look in multple paths

Posted on 2015-02-13
7
29 Views
Last Modified: 2015-04-13
Hi EE

I have a script that checks for samAccountNames in one path and adds them to an AD group .
Can someone help me change this line so it looks in multiple paths ?

$(Foreach ($User in GC \\MyServer\User1\SamAccountNames.txt){

I want this line to also check these paths
\\MyServer\User2\SamAccountNames.txt
\\MyServer\User3\SamAccountNames.txt
0
Comment
Question by:MilesLogan
  • 3
  • 3
7 Comments
 
LVL 13

Expert Comment

by:Guy Lidbetter
ID: 40607862
I would keep the list of paths in a txt file, so you only have to update that going forward if you wanted to change or add paths.

EG: SAMAccountNamePaths.txt

Then

$Paths = Get-Content SAMAccountNamePaths.txt  
         Foreach ($Path in $Paths) {
                    GC $Path | Foreach { <Add $_ to group>}
        }
0
 
LVL 2

Author Comment

by:MilesLogan
ID: 40608455
Hi Guy .. I like your suggestion alot but cant seem to get it .. this is the working script but checking only one path.. can you help me modify it?

$(Foreach ($User in GC \\MyServer\User1\SamAccountNames.txt){
GC C:\PS\Groups.txt | % {
   $Group = $_
   #using try catch to capture the errors
   Try{
        Add-ADGroupmember -identity $Group -member $User -ea stop
      #create custom PS object to output the command status..
        New-Object PSObject -Property @{
      GroupName = $Group
      User = $User
      Status = "Success"
      }
    }Catch{
      New-Object PSObject -Property @{
      GroupName = $Group
      User = $User
      Status = "Account already in the Group"
      }      
     }
   }
}) | export-csv "C:\PS\Added\File_$((Get-Date -Format MM-dd-yyyy-hhmmss)).csv" -NoTypeInformation
0
 
LVL 80

Expert Comment

by:David Johnson, CD, MVP
ID: 40608636
Try this one
$users=  @()
$paths = Get-Content \\MyServer\User1\SamAccountPaths.txt
#$paths = Get-Content C:\test\samaccountpaths.txt

foreach ($path in $paths) 
    {
    Get-Content $Path | % 
        {
        $users += $_
        }
    }

$(
Foreach ($User in $Users) {
    $groups = Get-Content C:\PS\Groups.txt
    Foreach ($group in $groups)  
        {
        #using try catch to capture the errors
        Try{
            Add-ADGroupmember -identity $Group -member $User -ea stop
            #create custom PS object to output the command status..
            New-Object PSObject -Property @{
                GroupName = $Group
                User = $User
                Status = "Success"
                }
            }
        Catch{
          New-Object PSObject -Property @{
          GroupName = $Group
          User = $User
          Status = "Account already in the Group"
          }      
         }
       }
}) | export-csv "C:\PS\Added\File_$((Get-Date -Format MM-dd-yyyy-hhmmss)).csv" -NoTypeInformation 

Open in new window

0
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
LVL 80

Expert Comment

by:David Johnson, CD, MVP
ID: 40608753
slight modification
<#
.SYNOPSIS

Adds AD Users to a group

.DESCRIPTION
 
 This function will add users from a list of text files that may contain many text file locations

.EXAMPLE
 
My-Add-ADUsers

.EXAMPLE

My-Add-ADusers -listpath <path to text file that contains paths to files that contain usernames to add to AD

.EXAMPLE

My-Add-Adusers -outputpath <path to output .csv>

.OUTPUTS

CSV of added users <path>\AddedFile_<DATE>.csv

.NOTES

You need to run this function as a member of the Domain Admins group; doing so is the only way to ensure you have permission to modify Active Directory

.LINK 

http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_28616457.html

.LINK

new-aduser

.LINK

Add-ADGroupmember
#>
function My-Add-ADUsers
{
    [CmdletBinding()]
   
   Param(
    [Parameter(Mandatory=$False)]
    [string]$listpath = "\\MyServer\User1\SamAccountPaths.txt",
    [Parameter(Mandatory=$False)]
   [string]$outputpath = "C:\PS\"
	
	)

    Begin
    {
    $users=  @()
$paths = Get-Content $listpath
if ((test-path  $outputpath) -eq $false) {
Write-Output "The path $outputpath does not exist"
break
}

$outputfile = "AddedFile_"
$outputfile += Get-Date -Format MM-dd-yyyy-hhmmss
$outputfile += ".csv"

foreach ($path in $paths) 
    {
    Get-Content $Path | % 
        {
        $users += $_
        }
    }

    }
    Process
    {
    $(
Foreach ($User in $Users) {
    $groups = Get-Content C:\PS\Groups.txt
    Foreach ($group in $groups)  
        {
        #using try catch to capture the errors
        Try{
            Add-ADGroupmember -identity $Group -member $User -ea stop
            #create custom PS object to output the command status..
            New-Object PSObject -Property @{
                GroupName = $Group
                User = $User
                Status = "Success"
                }
            }
        Catch{
          New-Object PSObject -Property @{
          GroupName = $Group
          User = $User
          Status = "Account already in the Group"
          }      
         }
       }
}) | export-csv $outputfile -NoTypeInformation

    }
    End
    {
    }
}

Open in new window

0
 
LVL 2

Author Comment

by:MilesLogan
ID: 40612775
Hi David ..  I updated the paths and I am receiving the error below. I know its not an account access issue..


PS C:\ps> My-Add-ADUsers -listpath c:\ps
Get-Content : Access to the path 'C:\ps' is denied.
At C:\Users\vmadmin\Documents\My-Add-ADUsers.ps1:57 char:10
+ $paths = Get-Content $listpath
+          ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\ps:String) [Get-Content], UnauthorizedAccessException
    + FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
0
 
LVL 80

Accepted Solution

by:
David Johnson, CD, MVP earned 500 total points
ID: 40612909
list path is a fully qualified namelistpath = "\\MyServer\User1\SamAccountPaths.txt",



<#
.SYNOPSIS
Adds AD Users to a group
.DESCRIPTION
 This function will add users from a list of text files that may contain many text file locations
 added more error checking
.EXAMPLE
My-Add-ADUsers

.EXAMPLE

My-Add-ADusers -listpath <path to text file that contains paths to files that contain usernames to add to AD

.EXAMPLE

My-Add-Adusers -outputpath <path to output .csv>

.OUTPUTS

CSV of added users <path>\AddedFile_<DATE>.csv

.NOTES

You need to run this function as a member of the Domain Admins group; doing so is the only way to ensure you have permission to modify Active Directory

.LINK 

http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_28616457.html

.LINK

new-aduser

.LINK

Add-ADGroupmember
#>
function My-Add-ADUsers
{
    [CmdletBinding()]
   
   Param(
    [Parameter(Mandatory=$False)]
    [string]$listpath = "\\MyServer\User1\SamAccountPaths.txt",
    [Parameter(Mandatory=$False)]
   [string]$outputpath = "C:\PS\"
	
	)

    Begin
    {
    $users=  @()
if ((test-path $listpath) -eq $true)
{
    $paths = Get-Content $listpath
    if ((test-path  $outputpath) -eq $false) {
    Write-Output "The path $outputpath does not exist"
    break
}
else { 
write-output "The path $listpath does not exist"
break }
}
$outputfile = "AddedFile_"
$outputfile += Get-Date -Format MM-dd-yyyy-hhmmss
$outputfile += ".csv"

foreach ($path in $paths) 
    {
    Get-Content $Path | % 
        {
        $users += $_
        }
    }

    }

    Process
    {
    $(
Foreach ($User in $Users) {
    $groups = Get-Content C:\PS\Groups.txt
    Foreach ($group in $groups)  
        {
        #using try catch to capture the errors
        Try{
            Add-ADGroupmember -identity $Group -member $User -ea stop
            #create custom PS object to output the command status..
            New-Object PSObject -Property @{
                GroupName = $Group
                User = $User
                Status = "Success"
                }
            }
        Catch{
          New-Object PSObject -Property @{
          GroupName = $Group
          User = $User
          Status = "Account already in the Group"
          }      
         }
       }
}) | export-csv $outputfile -NoTypeInformation

    }
    End
    {
    }
}

Open in new window

0
 
LVL 2

Author Closing Comment

by:MilesLogan
ID: 40722072
Thanks for the help..not sure why this stayed open.
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Restoring deleted objects in Active Directory has been a standard feature in Active Directory for many years, yet some admins may not know what is available.
This article outlines the process to identify and resolve account lockout in an Active Directory environment.
This tutorial will walk an individual through locating and launching the BEUtility application to properly change the service account username and\or password in situation where it may be necessary or where the password has been inadvertently change…
This tutorial will show how to configure a new Backup Exec 2012 server and move an existing database to that server with the use of the BEUtility. Install Backup Exec 2012 on the new server and apply all of the latest hotfixes and service packs. The…

860 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