Solved

Add Logging to powershell script - Schedule script

Posted on 2016-11-02
24
64 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 500 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
 

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

Join & Write a Comment

This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

743 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

11 Experts available now in Live!

Get 1:1 Help Now