?
Solved

Script to look in multple paths

Posted on 2015-02-13
7
Medium Priority
?
35 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 84

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
What Security Threats Are We Predicting for 2018?

Cryptocurrency, IoT botnets, MFA, and more! Hackers are already planning their next big attacks for 2018. Learn what you might face, and how to defend against it with our 2018 security predictions.

 
LVL 84

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 84

Accepted Solution

by:
David Johnson, CD, MVP earned 2000 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

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Question has a verified solution.

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

There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
In this post, I will showcase the steps for how to create groups in Office 365. Office 365 groups allow for ease of flexibility and collaboration between staff members.
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

840 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