?
Solved

Add Logging to powershell script - Schedule script

Posted on 2016-11-02
24
Medium Priority
?
144 Views
Last Modified: 2016-11-07
Hello,

I am trying to add logging to a powershell script, to log when a user is added to a security group. This will just be to verify that the script is actually adding users to the Sec Group.

This is what i have so far.
#Set Error Action to Silently Continue
$ErrorActionPreference = "SilentlyContinue"
#Log File Info
$sLogPath = "C:\Windows\Temp"
$sLogName = "Write_PA_PasswordPolicy.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
$Error.Clear()

Import-Module ActiveDirectory

$OU1 = 'OU=SecTest,OU=Priviledged_Access,OU=_Users,DC=test,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PrivilegedUserPasswordPolicy').DistinguishedName

Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
#Log Error
$Error | Out-file $sLogFile -Append

Open in new window

0
Comment
Question by:Peter Cope
  • 13
  • 11
24 Comments
 
LVL 40

Accepted Solution

by:
Subsun earned 2000 total points
ID: 41871026
Try this.. Log file is a csv file which can be opened in Excel..
#Set Error Action to Stop
$ErrorActionPreference = "Stop"
#Log File Info
$sLogPath = "C:\Windows\Temp"
$sLogName = "Write_PA_PasswordPolicy.csv"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
$Error.Clear()

Import-Module ActiveDirectory

$OU1 = 'OU=SecTest,OU=Priviledged_Access,OU=_Users,DC=test,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PrivilegedUserPasswordPolicy').DistinguishedName

Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | %{
$User = $_
	Try{
	$User | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
	[PSObject]@{
		User = $User.sAMAccountName
		Status = "Added to Group"
		Error = $null
	}
	}
	Catch{
	[PSObject]@{
		User = $User.sAMAccountName
		Status = "Failed"
		Error = $_.Exception.Message
	}
   }
} | Export-Csv $sLogFile -nti

Open in new window

0
 

Author Comment

by:Peter Cope
ID: 41871053
Getting an error when i run it.

Get-ADUser : Directory object not found
At C:\scripts\Write_PA.ps1:14 char:1
+ Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=u ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.GetADUser
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41871066
Check the value of $OU1 (the DN of the OU) and make sure it's correct..
0
 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

 

Author Comment

by:Peter Cope
ID: 41871083
Yeah thanks for that catch, dont know how that go changed. The logging is not logging correct it seems.

Getting this

IsReadOnly      IsFixedSize      IsSynchronized      Keys      Values      SyncRoot      Count
FALSE      FALSE      FALSE      System.Collections.Hashtable+KeyCollection      System.Collections.Hashtable+ValueCollection      System.Object      3
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41871120
Change [PSObject] to [PSCustomObject] in code..
0
 

Author Comment

by:Peter Cope
ID: 41871130
I changed both of them and it just creates a blank CSV file
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41871139
Do you have any users which is not member of the group? If not csv will be blank.. If you have users which is not member of group then only the log will have users..
0
 

Author Comment

by:Peter Cope
ID: 41872026
Well I'm just testing for now, but i have one user that is not in the group. So it should create a row for a successful add?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872098
Yes it should. csv should look something like this..
"User","Status","Error"
"UserA","Added to Group"

Open in new window

0
 

Author Comment

by:Peter Cope
ID: 41872146
I get something like this.

  1. IsReadOnly      IsFixedSize      IsSynchronized      Keys      Values      SyncRoot      Count
  2. FALSE      FALSE      FALSE      System.Collections.Hashtable+KeyCollection      System.Collections.Hashtable+ValueCollection      System.Object      3
  3. FALSE      FALSE      FALSE      System.Collections.Hashtable+KeyCollection      System.Collections.Hashtable+ValueCollection      System.Object      3
  4. FALSE      FALSE      FALSE      System.Collections.Hashtable+KeyCollection      System.Collections.Hashtable+ValueCollection      System.Object      3
  5. FALSE      FALSE      FALSE      System.Collections.Hashtable+KeyCollection      System.Collections.Hashtable+ValueCollection      System.Object      3
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872150
Did you change [PSObject] to [PSCustomObject] in code?
0
 

Author Comment

by:Peter Cope
ID: 41872157
Yes.. last part of script this is what i have.

Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | %{
$User = $_
	Try{
	$User | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
	[PSCustomObject]@{
		User = $User.sAMAccountName
		Status = "Added to Group"
		Error = $null
	}
	}
	Catch{
	[PSCustomObject]@{
		User = $User.sAMAccountName
		Status = "Failed"
		Error = $_.Exception.Message
	}
   }
} | Export-Csv $sLogFile -nti

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872164
Probably an issue with your powershell version.. Try..
Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | %{
$User = $_
	Try{
	$User | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
	New-Object PSobject -Property @{
		User = $User.sAMAccountName
		Status = "Added to Group"
		Error = $null
	}
	}
	Catch{
	New-Object PSobject -Property @{
		User = $User.sAMAccountName
		Status = "Failed"
		Error = $_.Exception.Message
	}
   }
} | Export-Csv $sLogFile -nti

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872175
Or simply use the text file logging..
Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | %{
$User = $_
	Try{
	$User | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
	Echo "$($User.sAMAccountName) added to Group"
	}
	Catch{
	Echo "$($User.sAMAccountName)  Failed - Error - $($_.Exception.Message)"
	}
} | Out-File $sLogFile

Open in new window

0
 

Author Comment

by:Peter Cope
ID: 41872178
Awesome!!

I checked my version and I'm on 2.0. I guess i will upgrade to 4.0.

Should i use the other code before?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872182
[PSCustomObject] should work on PS 3.0 and above..

You can use the code which works for you.. :-)
1
 

Author Comment

by:Peter Cope
ID: 41872204
How would you run Powershell as a different user?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41872210
If you are scheduling it using task scheduler, then you can configure the account which you want to use in security option of the task.
0
 

Author Comment

by:Peter Cope
ID: 41877506
How would i add a time stamp to the log file? or date?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41877563
Change log file name "Write_PA_PasswordPolicy.csv" to
"Write_PA_PasswordPolicy-$(Get-Date -f dd_MM_yyy_HH-mm).log"

Open in new window

0
 

Author Comment

by:Peter Cope
ID: 41877568
Oh yeah i got that, I was just trying to add a time stamp column to the csv file?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41877571
I am not clear. What time stamp you trying to add and reason for adding in csv file?
0
 

Author Comment

by:Peter Cope
ID: 41877577
I guess the question is, will it create a new log file each time the script runs? I was just thinking of keeping it all in one file.
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41877610
If you want to keep all in one file then you need to use the -append switch, in that case you need to add time stamp for each addition (as you mentioned).

If you want to create a log for each time you run the script then you need add the date and time stamp in the log file name.
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

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

How to deal with a specific error when using the Enable-RemoteMailbox cmdlet to create a mailbox in the cloud-based service, for an existing user in an on-premises Active Directory.
It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…

839 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