Solved

Add Logging to powershell script - Schedule script

Posted on 2016-11-02
24
103 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

Had a business requirement to store the mobile number in an environmental variable. This is just a quick article on how this was done.
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

718 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