?
Solved

Script to look in multple paths

Posted on 2015-02-13
7
Medium Priority
?
32 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 82

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
Bringing Advanced Authentication to the SMB Market

WatchGuard announces the acquisition of advanced authentication provider, Datablink, with one mission – to bring secure authentication to SMB, mid-market, and distributed enterprises with a cloud-based solution, ideal for resale via their established channel & MSSP community.

 
LVL 82

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 82

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

In this post we will be converting StringData saved within a text file into a hash table. This can be further used in a PowerShell script for replacing settings that are dynamic in nature from environment to environment.
After seeing many questions for JRNL_WRAP_ERROR for replication failure, I thought it would be useful to write this article.
To efficiently enable the rotation of USB drives for backups, storage pools need to be created. This way no matter which USB drive is installed, the backups will successfully write without any administrative intervention. Multiple USB devices need t…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
Suggested Courses

741 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