Add Logging to powershell script - Schedule script

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

Peter CopeAsked:
Who is Participating?
 
SubsunConnect With a Mentor Commented:
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
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
Check the value of $OU1 (the DN of the OU) and make sure it's correct..
0
Improved Protection from Phishing Attacks

WatchGuard DNSWatch reduces malware infections by detecting and blocking malicious DNS requests, improving your ability to protect employees from phishing attacks. Learn more about our newest service included in Total Security Suite today!

 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
Change [PSObject] to [PSCustomObject] in code..
0
 
Peter CopeAuthor Commented:
I changed both of them and it just creates a blank CSV file
0
 
SubsunCommented:
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
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
Yes it should. csv should look something like this..
"User","Status","Error"
"UserA","Added to Group"

Open in new window

0
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
Did you change [PSObject] to [PSCustomObject] in code?
0
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
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
 
SubsunCommented:
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
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
[PSCustomObject] should work on PS 3.0 and above..

You can use the code which works for you.. :-)
1
 
Peter CopeAuthor Commented:
How would you run Powershell as a different user?
0
 
SubsunCommented:
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
 
Peter CopeAuthor Commented:
How would i add a time stamp to the log file? or date?
0
 
SubsunCommented:
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
 
Peter CopeAuthor Commented:
Oh yeah i got that, I was just trying to add a time stamp column to the csv file?
0
 
SubsunCommented:
I am not clear. What time stamp you trying to add and reason for adding in csv file?
0
 
Peter CopeAuthor Commented:
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
 
SubsunCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.