Solved

Script to look in multple paths

Posted on 2015-02-13
7
26 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 78

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
Promote certifications in your email signature

Has your company recently won an award or achieved a certification? They'll no doubt want to show it off. Email signature images used to promote certifications & awards can instantly establish credibility with a recipient and provide you with numerous benefits.

 
LVL 78

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 78

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

Do email signature updates give you a headache?

Do you feel like all of your time is spent managing email signatures? Too busy to visit every user’s desk to make updates? Want high-quality HTML signatures on all devices, including on mobiles and Macs? Then, let Exclaimer solve all your email signature problems today!

Join & Write a Comment

In this article, we will see the basic design consideration while designing a Multi-tenant web application in a simple manner. Though, many frameworks are available in the market to develop a multi - tenant application, but do they provide data, cod…
The recent Microsoft changes on update philosophy for Windows pre-10 and their impact on existing WSUS implementations.
This tutorial will walk an individual through locating and launching the BEUtility application and how to execute it on the appropriate database. Log onto the server running the Backup Exec database. In a larger environment, this would generally be …
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…

705 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now