infradatel
asked on
Write Powershell Errors to text file
Hi I am running a script that checks a txt file of a list of users and then adds those users to a group. This all work fine, what I need to be able to do now is get the script to list any users that are not recognised or do not exist into a text file.
Import-CSV "C:\Temp\Users.txt" | % {Add-ADGroupMember -Identity 'TestGroup1' -Member $_.UserName}
Can anyone help please
Import-CSV "C:\Temp\Users.txt" | % {Add-ADGroupMember -Identity 'TestGroup1' -Member $_.UserName}
Can anyone help please
I presume you are looking to log the errors like user not found or Group not found etc.. If yes try this..
$ErrorActionPreference="SilentlyContinue"
$InputFile="C:\Temp\Users.txt"
$Logfile = "c:\Temp\log.txt"
$group="TestGroup"
Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru
If (Get-ADGroup $Group)
{Import-CSV $InputFile | % {
If (get-Aduser $_.UserName)
{Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru}
Else {Add-Content $Logfile "Added User $($_.UserName) to $Group" -PassThru}
}
Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}
}}
Else {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
ASKER
Hi Subsun thanks for the reply: the out put in the log file looks like this when I run the command:
Adding Users to TestGroup -------------10/29/2012 08:34:02
Adding Users to TestGroup -------------10/29/2012 08:34:03
Adding Users to TestGroup -------------10/29/2012 08:34:38
Adding Users to TestGroup -------------10/29/2012 08:35:31
Any ideas?
Adding Users to TestGroup -------------10/29/2012 08:34:02
Adding Users to TestGroup -------------10/29/2012 08:34:03
Adding Users to TestGroup -------------10/29/2012 08:34:38
Adding Users to TestGroup -------------10/29/2012 08:35:31
Any ideas?
Are you running the script from Active Directory PowerShell? if not add Import-Module ActiveDirectory in first line..
ASKER
Yes I am running it with imported modules
ASKER
I copied your scrpt to a ps1 file called addusers.ps1:
This is what I get when I run it from the shell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> cd C:\Temp
PS C:\Temp> .\addusers.ps1
Adding Users to TestGroup -------------10/29/2012 11:08:48
PS C:\Temp>
This is what the log.txt file says:
Adding Users to TestGroup -------------10/29/2012 08:34:02
Adding Users to TestGroup -------------10/29/2012 08:34:03
Adding Users to TestGroup -------------10/29/2012 08:34:38
Adding Users to TestGroup -------------10/29/2012 08:35:31
Adding Users to TestGroup -------------10/29/2012 08:36:34
Adding Users to TestGroup -------------10/29/2012 08:36:46
Adding Users to TestGroup -------------10/29/2012 08:36:49
Adding Users to TestGroup -------------10/29/2012 11:06:48
Adding Users to TestGroup -------------10/29/2012 11:08:16
Adding Users to TestGroup -------------10/29/2012 11:08:48
Here is what I have in the ps1 file (I have added the Import-Module and still get the same error:
Import-Module ActiveDirectory
$ErrorActionPreference="Si lentlyCont inue"
$InputFile="C:\Temp\Users. txt"
$Logfile = "c:\Temp\log.txt"
$group="TestGroup"
Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru
If (Get-ADGroup $Group)
{Import-CSV $InputFile | % {
If (get-Aduser $_.UserName)
{Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru}
Else {Add-Content $Logfile "Added User $($_.UserName) to $Group" -PassThru}
}
Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}
}}
Else {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
This is what I get when I run it from the shell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> cd C:\Temp
PS C:\Temp> .\addusers.ps1
Adding Users to TestGroup -------------10/29/2012 11:08:48
PS C:\Temp>
This is what the log.txt file says:
Adding Users to TestGroup -------------10/29/2012 08:34:02
Adding Users to TestGroup -------------10/29/2012 08:34:03
Adding Users to TestGroup -------------10/29/2012 08:34:38
Adding Users to TestGroup -------------10/29/2012 08:35:31
Adding Users to TestGroup -------------10/29/2012 08:36:34
Adding Users to TestGroup -------------10/29/2012 08:36:46
Adding Users to TestGroup -------------10/29/2012 08:36:49
Adding Users to TestGroup -------------10/29/2012 11:06:48
Adding Users to TestGroup -------------10/29/2012 11:08:16
Adding Users to TestGroup -------------10/29/2012 11:08:48
Here is what I have in the ps1 file (I have added the Import-Module and still get the same error:
Import-Module ActiveDirectory
$ErrorActionPreference="Si
$InputFile="C:\Temp\Users.
$Logfile = "c:\Temp\log.txt"
$group="TestGroup"
Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru
If (Get-ADGroup $Group)
{Import-CSV $InputFile | % {
If (get-Aduser $_.UserName)
{Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru}
Else {Add-Content $Logfile "Added User $($_.UserName) to $Group" -PassThru}
}
Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}
}}
Else {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
Change $ErrorActionPreference="Si lentlyCont inue" to $ErrorActionPreference="Co ntinue" and see what is the error?
ASKER
Getting somewhere now I think:
Ran it first time and realised the group name was incorrect TestGroup1 is should have been:
PS C:\Temp> .\addusers.ps1
Get-ADGroup : Cannot find an object with identity: 'TestGroup' under: 'DC=emea,DC=wdpr,DC=disney ,DC=com'.
At C:\Temp\addusers.ps1:6 char:97
+ Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru If (Get-ADGroup <<<< $Group) {Impor
t-CSV $InputFile | % {If (get-Aduser $_.UserName) {Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVari
able Err | Out-Null If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru} Else {Add-Content $Logfile "Added Use
r $($_.UserName) to $Group" -PassThru}} Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}}} Els
e {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
+ CategoryInfo : ObjectNotFound: (TestGroup:ADGroup) [Get-ADGroup], ADIdentityNotFoundExceptio n
+ FullyQualifiedErrorId : Cannot find an object with identity: 'TestGroup' under: 'DC=emea,DC=wdpr,DC=disney ,DC=co
m'.,Microsoft.ActiveDirect ory.Manage ment.Comma nds.GetADG roup
So I ran it the second time and then I got this:
PS C:\Temp> .\addusers.ps1
Add-Content : A positional parameter cannot be found that accepts argument 'If'.
At C:\Temp\addusers.ps1:6 char:12
+ Add-Content <<<< $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru If (Get-ADGroup $Group) {Impor
t-CSV $InputFile | % {If (get-Aduser $_.UserName) {Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVari
able Err | Out-Null If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru} Else {Add-Content $Logfile "Added Use
r $($_.UserName) to $Group" -PassThru}} Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}}} Els
e {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
+ CategoryInfo : InvalidArgument: (:) [Add-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFoun d,Microsof t.PowerShe ll.Command s.AddConte ntCommand
Ran it first time and realised the group name was incorrect TestGroup1 is should have been:
PS C:\Temp> .\addusers.ps1
Get-ADGroup : Cannot find an object with identity: 'TestGroup' under: 'DC=emea,DC=wdpr,DC=disney
At C:\Temp\addusers.ps1:6 char:97
+ Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru If (Get-ADGroup <<<< $Group) {Impor
t-CSV $InputFile | % {If (get-Aduser $_.UserName) {Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVari
able Err | Out-Null If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru} Else {Add-Content $Logfile "Added Use
r $($_.UserName) to $Group" -PassThru}} Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}}} Els
e {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
+ CategoryInfo : ObjectNotFound: (TestGroup:ADGroup) [Get-ADGroup], ADIdentityNotFoundExceptio
+ FullyQualifiedErrorId : Cannot find an object with identity: 'TestGroup' under: 'DC=emea,DC=wdpr,DC=disney
m'.,Microsoft.ActiveDirect
So I ran it the second time and then I got this:
PS C:\Temp> .\addusers.ps1
Add-Content : A positional parameter cannot be found that accepts argument 'If'.
At C:\Temp\addusers.ps1:6 char:12
+ Add-Content <<<< $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru If (Get-ADGroup $Group) {Impor
t-CSV $InputFile | % {If (get-Aduser $_.UserName) {Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVari
able Err | Out-Null If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru} Else {Add-Content $Logfile "Added Use
r $($_.UserName) to $Group" -PassThru}} Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}}} Els
e {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
+ CategoryInfo : InvalidArgument: (:) [Add-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFoun
ASKER
Could the issue be spacing or line breaks etc as I am just copying and pasting???
ASKER
OK I recreated the script using the LSE ran it and I got lots of these errors:
Add-ADGroupMember : The specified account name is already a member of the group
At C:\temp\addusergroup.ps1:1 0 char:20
+ {Add-ADGroupMember <<<< -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
+ CategoryInfo : NotSpecified: (TestGroup1:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDire ctory.Ma
nagement.Commands.AddADGro upMember
System.Management.Automati on.CmdletI nvocationE xception: The specified account name is already a member of the group ---
> Microsoft.ActiveDirectory. Management .ADExcepti on: The specified account name is already a member of the group ---> Sy
stem.ServiceModel.FaultExc eption: Active Directory returned an error processing the operation.
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForExtende dError(Str ing extendedErrorMessage, E
xception innerException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForErrorCo de(String message, String errorCode,
String extendedErrorMessage, Exception innerException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForFaultDe tail(Fault Detail faultDetail, FaultEx
ception faultException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException (AdwsFault adwsFault, FaultException faultExcep
tion)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Modi fy(ADModif yRequest request)
at Microsoft.ActiveDirectory. Management .ADWebServ iceStoreAc cess.Micro soft.Activ eDirectory .Managemen t.IADSyncO peratio
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
at Microsoft.ActiveDirectory. Management .ADActiveO bject.Upda te()
Add-ADGroupMember : The specified account name is already a member of the group
At C:\temp\addusergroup.ps1:1
+ {Add-ADGroupMember <<<< -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
+ CategoryInfo : NotSpecified: (TestGroup1:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDire
nagement.Commands.AddADGro
System.Management.Automati
> Microsoft.ActiveDirectory.
stem.ServiceModel.FaultExc
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory.
xception innerException)
at Microsoft.ActiveDirectory.
String extendedErrorMessage, Exception innerException)
at Microsoft.ActiveDirectory.
ception faultException)
at Microsoft.ActiveDirectory.
tion)
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
at Microsoft.ActiveDirectory.
Try this.. and let me know the result.. If it's working change Continue to SilentlyContinue..
Import-Module ActiveDirectory
$ErrorActionPreference="Continue"
$InputFile="C:\Temp\Users.txt"
$Logfile = "c:\Temp\log.txt"
$group="TestGroup"
If (Test-Path $InputFile){
Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru
If ($(Get-ADGroup $Group))
{Import-CSV $InputFile | % {
If (get-Aduser $_.UserName)
{Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
If ($err.count -gt 0) {Add-Content $Logfile "$Err" -PassThru}
Else {Add-Content $Logfile "Added User $($_.UserName) to $Group" -PassThru}
}
Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}
}}
Else {Add-Content $Logfile "Unable to find Group $Group" -PassThru}}
Else {Write-Host "Not able to find the input file"}
ASKER
Thanks tried that and just see lots of these messages on the shell and in the log.txt file:
Add-ADGroupMember : The specified account name is already a member of the group
At C:\Temp\adusersnew.ps1:11 char:20
+ {Add-ADGroupMember <<<< -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
+ CategoryInfo : NotSpecified: (TestGroup1:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDire ctory.Ma
nagement.Commands.AddADGro upMember
System.Management.Automati on.CmdletI nvocationE xception: The specified account name is already a member of the group ---
> Microsoft.ActiveDirectory. Management .ADExcepti on: The specified account name is already a member of the group ---> Sy
stem.ServiceModel.FaultExc eption: Active Directory returned an error processing the operation.
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForExtende dError(Str ing extendedErrorMessage, E
xception innerException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForErrorCo de(String message, String errorCode,
String extendedErrorMessage, Exception innerException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException ForFaultDe tail(Fault Detail faultDetail, FaultEx
ception faultException)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Thro wException (AdwsFault adwsFault, FaultException faultExcep
tion)
at Microsoft.ActiveDirectory. Management .AdwsConne ction.Modi fy(ADModif yRequest request)
at Microsoft.ActiveDirectory. Management .ADWebServ iceStoreAc cess.Micro soft.Activ eDirectory .Managemen t.IADSyncO peratio
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
at Microsoft.ActiveDirectory. Management .ADActiveO bject.Upda te()
at Microsoft.ActiveDirectory. Management .Commands. ADSetCmdle tBase`3.Se tFromIdent ity(O identity)
at Microsoft.ActiveDirectory. Management .Commands. ADSetCmdle tBase`3.Pr ocessRecor dOverride( )
at Microsoft.ActiveDirectory. Management .Commands. SetADGroup Member`1.P rocessReco rdOverride ()
at Microsoft.ActiveDirectory. Management .Commands. ADCmdletBa se.Process Record()
--- End of inner exception stack trace ---
at System.Management.Automati on.Interna l.Pipeline Processor. Synchronou sExecuteEn umerate(Ob ject input, Hashtable error
Results, Boolean enumerate)
at System.Management.Automati on.Pipelin eNode.Exec ute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionC
ontext context)
at System.Management.Automati on.Stateme ntListNode .ExecuteSt atement(Pa rseTreeNod e statement, Array input, Pipe output
Pipe, ArrayList& resultList, ExecutionContext context)
Add-ADGroupMember : The specified account name is already a member of the group
At C:\Temp\adusersnew.ps1:11 char:20
+ {Add-ADGroupMember <<<< -Identity $group -Member $_.UserName -ErrorVariable Err | Out-Null
+ CategoryInfo : NotSpecified: (TestGroup1:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDire
nagement.Commands.AddADGro
System.Management.Automati
> Microsoft.ActiveDirectory.
stem.ServiceModel.FaultExc
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory.
xception innerException)
at Microsoft.ActiveDirectory.
String extendedErrorMessage, Exception innerException)
at Microsoft.ActiveDirectory.
ception faultException)
at Microsoft.ActiveDirectory.
tion)
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
at Microsoft.ActiveDirectory.
--- End of inner exception stack trace ---
at System.Management.Automati
Results, Boolean enumerate)
at System.Management.Automati
ontext context)
at System.Management.Automati
Pipe, ArrayList& resultList, ExecutionContext context)
Ok, I have corrected the error display for The specified account name is already a member of the group. Try now and let me know the result..
Import-Module ActiveDirectory
$ErrorActionPreference="SilentlyContinue"
$InputFile="C:\Temp\Users.txt"
$Logfile = "c:\Temp\log.txt"
$group="TestGroup"
If (Test-Path $InputFile)
{Add-Content $Logfile "Adding Users to $Group -------------$(Get-Date)" -PassThru
If($(Get-ADGroup $Group))
{Import-CSV $InputFile | %
{
If(get-Aduser $_.UserName)
{Add-ADGroupMember -Identity $group -Member $_.UserName -ErrorVariable Result | Out-Null
If ($e.count -gt 0) {Add-Content $Logfile "Error for $($_.UserName) - $($Err[0].Message)" -PassThru}
Else {Add-Content $Logfile "Added User $($_.UserName) to $Group" -PassThru}
}
Else{Add-Content $Logfile "Unable to find user $($_.UserName)" -PassThru}
}
}
Else {Add-Content $Logfile "Unable to find Group $Group" -PassThru}
}
Else {Write-Host "Not able to find the input file"}
ASKER
I get this now:
PS C:\Temp> .\adusersnew2.ps1
Adding Users to TestGroup1 -------------10/29/2012 12:22:48
cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters:
Process[0]:
By the way thanks for all the help you have given me it is much appreciated.
PS C:\Temp> .\adusersnew2.ps1
Adding Users to TestGroup1 -------------10/29/2012 12:22:48
cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters:
Process[0]:
By the way thanks for all the help you have given me it is much appreciated.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
OK well that looks much better, except if I run the command twice I dont get any errors to say the account is already a member this is what the log file says for every entry in the users.txt file (the correct username does populate in the username field):
Added User "username" to TestGroup1
Added User "username" to TestGroup1
I know.. :-) .. I had copied the wrong script so I had updated the script immediately after posting, can you copy the script once again and run it?
ASKER
Absolutely prefect thank you very much for all your time and help. I wish I could give you more points!!!
No problem, Glad I could help!
ASKER