Link to home
Start Free TrialLog in
Avatar of infradatel
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
Avatar of infradatel
infradatel

ASKER

Also I can get the script to export all the errors into a text file, but I just want it to list the usernames as it will make it easier to read.
Avatar of SubSun
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}

Open in new window

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?
Are you running the script from Active Directory PowerShell? if not add  Import-Module ActiveDirectory in first line..
Yes I am running it with imported modules
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="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}
Change $ErrorActionPreference="SilentlyContinue" to $ErrorActionPreference="Continue" and see what is the error?
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], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: 'TestGroup' under: 'DC=emea,DC=wdpr,DC=disney,DC=co
   m'.,Microsoft.ActiveDirectory.Management.Commands.GetADGroup

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 : PositionalParameterNotFound,Microsoft.PowerShell.Commands.AddContentCommand
Could the issue be spacing or line breaks etc as I am just copying and pasting???
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:10 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.ActiveDirectory.Ma
   nagement.Commands.AddADGroupMember

System.Management.Automation.CmdletInvocationException: The specified account name is already a member of the group ---
> Microsoft.ActiveDirectory.Management.ADException: The specified account name is already a member of the group ---> Sy
stem.ServiceModel.FaultException: Active Directory returned an error processing the operation.
   --- End of inner exception stack trace ---
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForExtendedError(String extendedErrorMessage, E
xception innerException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForErrorCode(String message, String errorCode,
String extendedErrorMessage, Exception innerException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForFaultDetail(FaultDetail faultDetail, FaultEx
ception faultException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowException(AdwsFault adwsFault, FaultException faultExcep
tion)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.Modify(ADModifyRequest request)
   at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADSyncOperatio
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
   at Microsoft.ActiveDirectory.Management.ADActiveObject.Update()
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"}

Open in new window

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.ActiveDirectory.Ma
   nagement.Commands.AddADGroupMember

System.Management.Automation.CmdletInvocationException: The specified account name is already a member of the group ---
> Microsoft.ActiveDirectory.Management.ADException: The specified account name is already a member of the group ---> Sy
stem.ServiceModel.FaultException: Active Directory returned an error processing the operation.
   --- End of inner exception stack trace ---
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForExtendedError(String extendedErrorMessage, E
xception innerException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForErrorCode(String message, String errorCode,
String extendedErrorMessage, Exception innerException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForFaultDetail(FaultDetail faultDetail, FaultEx
ception faultException)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowException(AdwsFault adwsFault, FaultException faultExcep
tion)
   at Microsoft.ActiveDirectory.Management.AdwsConnection.Modify(ADModifyRequest request)
   at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADSyncOperatio
ns.Modify(ADSessionHandle handle, ADModifyRequest request)
   at Microsoft.ActiveDirectory.Management.ADActiveObject.Update()
   at Microsoft.ActiveDirectory.Management.Commands.ADSetCmdletBase`3.SetFromIdentity(O identity)
   at Microsoft.ActiveDirectory.Management.Commands.ADSetCmdletBase`3.ProcessRecordOverride()
   at Microsoft.ActiveDirectory.Management.Commands.SetADGroupMember`1.ProcessRecordOverride()
   at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase.ProcessRecord()
   --- End of inner exception stack trace ---
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable error
Results, Boolean enumerate)
   at System.Management.Automation.PipelineNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionC
ontext context)
   at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe output
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"}

Open in new window

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.
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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?
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!