Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Script to look in multple paths

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

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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 83

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 83

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

Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

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.
Let's recap what we learned from yesterday's Skyport Systems webinar.
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…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

618 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