Solved

How to append a csv file for logging instead of .log file

Posted on 2013-05-24
13
428 Views
Last Modified: 2013-06-06
I have the following
$log      = "C:\scripts\ceridian\05-22-2013_Ceridian_Create_AD_Users.log"
"SKIPPED - ALREADY EXISTS OR ERROR: " + $_."Last Name" + " " + $_."First Name" + " " + $_."Clock Number" | Out-File $log -append

Open in new window

Is there anyway to EXPORT/APPEND into a csv file ?
0
Comment
Question by:namerg
13 Comments
 
LVL 39

Expert Comment

by:footech
Comment Utility
With PowerShell 3.0, Export-CSV has an -append parameter.  But if you can't use that, I've come across a function someone put together to do that.  It's basically a wrapper for Export-CSV that adds the capability.
Here's a link to that.
http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/
0
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 500 total points
Comment Utility
You can try constructing the csv file..
For example..
$log = "C:\scripts\ceridian\05-22-2013_Ceridian_Create_AD_Users.csv"
$Out = "SKIPPED - ALREADY EXISTS OR ERROR:" + "," + $_."Last Name" + "," + $_."First Name" + "," + $_."Clock Number"
Add-Content -Value $Out -Path $log

Open in new window

0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
Of course you need to take care to use the exact same format already in the CSV when perfoming appends. Neither the Export-CSV implemention of Dmitry Sotnikov does a check, nor the Add-Content; I don't know for the PS 3 one, but I reckon it's working the same way.
0
 

Author Comment

by:namerg
Comment Utility
@Subsun: I get the following in the generated CSV file: :)
I read only two languages no this one. :) :)

Created following users (on 05/28/2013 10:50:22):
--------------------------------------------
¿¿¿/¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿/¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿/¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿/¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿----------------------------------------
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Can you post the script which you are using?
0
 

Author Comment

by:namerg
Comment Utility
Here it goes:
Import-Module ActiveDirectory
# Get current directory and set import file in variable
$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = "C:\scripts\ceridian\05-22-2013_CeridianExport.csv"
# Define variables
#$log      = "C:\scripts\ceridian\05-22-2013_Ceridian_Create_AD_Users.log"
$log = "C:\scripts\ceridian\05-28-2013_Ceridian_Create_AD_Users.csv"
$Out = "SKIPPED - ALREADY EXISTS OR ERROR:" + "," + $_."Last Name" + "," + $_."First Name" + "," + $_."Clock Number"
$date     = Get-Date
$i        = 0
# Change this to the location you want the users to be created in your AD
$location = "OU=New Users,DC=domain,DC=com"
# FUNCTIONS
Function createUsers
{
  "Created following users (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object { 
    $sam = $_."Last Name".ToLower() + $_."First Name".substring(0,1).ToLower()
    $ClockNumber = $_."Clock Number"
    Try   {
      #$exists = Get-ADUser -SearchBase "OU=ou,DC=domain,DC=com" -filter * -LDAPFilter "(sAMAccountName=$sam)" 
      $exists = Get-ADUser -SearchBase "OU=ou,DC=domain,DC=com" -filter * -Properties sAMAccountName,sn,givenName,title,employeeNumber | Where { $_.DistinguishedName -notmatch "OU=VIP" -and $_.DistinguishedName -notmatch "OU=DA" -and $_.sAMAccountName -notmatch $sam -and $_.employeeNumber -notmatch $ClockNumber} | Select-Object  sAMAccountName,sn,givenName,title,employeeNumber
      }
    Catch { }
    If(!$exists)
    {
      $i++
      # Set all variables according to the table names in the Excel 
      # sheet / import CSV. The names can differ in every project, but 
      # if the names change, make sure to change it below as well.
       $password = Get-RandomPassword
	   $domain = "@domain.com"
       $setpass = ConvertTo-SecureString -AsPlainText $password -force
       Write-Host $_."Last Name" ,  $_."First Name" $setpass
       New-ADUser $sam -AccountPassword $setpass -OtherAttributes @{userPrincipalName=$sam + $domain; givenName=$_."First Name";sn=$_."Last Name"; displayName=$_."Last Name" + ", " + $_."First Name"; title=$_."Job Title"; employeeNumber=$_."Clock Number"}
      
      $dn  = (Get-ADUser $sam).DistinguishedName
      #*****Set an ExtensionAttribute*******
      
      #$ext = [ADSI]"LDAP://$dn"
      #$ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
      #$ext.SetInfo()
 
      # Move the user to the OU you set above. If you don't want to
      # move the user(s) and just create them in the global Users
      # OU, comment the string below
      Move-ADObject -Identity $dn -TargetPath $location
 
      # Rename the object to a good looking name (otherwise you see
      # the 'ugly' shortened sAMAccountNames as a name in AD. This 
      # can't be set right away (as sAMAccountName) due to the 20
      # character restriction
      $newdn = (Get-ADUser $sam).DistinguishedName

      $CN = $_."Last Name" + ", " + $_."First Name"
      Rename-ADObject -Identity $newdn -NewName $CN
 
      $output  = $i.ToString() + ") Name: " + $CN + "  sAMAccountName: " 
      $output += $sam + "  Pass: " + $setpass
      $output | Out-File $log -append
    }
    Else
    {
      #"SKIPPED - ALREADY EXISTS OR ERROR: " + $_."Last Name" + " " + $_."First Name" + " " + $_."Clock Number" | Out-File $log -append
      Add-Content -Value $Out -Path $log
      #"SKIPPED - ALREADY EXISTS OR ERROR: " + $_."Last Name" + " " + $_."First Name" + " " + $_."Clock Number" | Export-Csv "c:\scripts\ceridian\05-23-2013_ADMisMatch.csv" -NoTypeInformation
      
    }
  }
  "----------------------------------------" + "`n" | Out-File $log -append

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 500 total points
Comment Utility
I can see in the script you have used Add-Content and Out-File. One thing you can try is to keep the same encoding while updating the file and see if you can get a good output..

Add   -Encoding UTF8  or   -Encoding Default while updating the files..

For example..
Add-Content -Value $Out -Path $log -Encoding Default
"----------------------------------------" + "`n" | Out-File $log -append -Encoding Default

Open in new window


Also I would suggest separate log files for created user and failed users so that the csv file will be more logical. Right now it's looks a bit vague as also it doesn't have any header..
0
 

Author Comment

by:namerg
Comment Utility
yes you are right about creating two files...
0
 

Author Comment

by:namerg
Comment Utility
Hmm, i get this:
Add-Content : Cannot bind parameter 'Encoding'. Cannot convert value "Default" to type "Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding" due to invalid enum
eration values. Specify one of the following enumeration values and try again. The possible enumeration values are "Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8,
 UTF7, Ascii".
At C:\scripts\ceridian\Ceridian_Create_AD_Users.ps1:66 char:51
0
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
Comment Utility
PS3 support the Default enumeration for Encoding parameter.. I think you have PS2, try with UTF8
0
 

Author Comment

by:namerg
Comment Utility
Hmm, now I get the following on the csv:
Column A
SKIPPED - ALREADY EXISTS OR ERROR:
SKIPPED - ALREADY EXISTS OR ERROR:
SKIPPED - ALREADY EXISTS OR ERROR:
SKIPPED - ALREADY EXISTS OR ERROR:
SKIPPED - ALREADY EXISTS OR ERROR:
SKIPPED - ALREADY EXISTS OR ERROR:
The original text/log file, creates the following:
Created following users (on 05/24/2013 16:46:43):
--------------------------------------------
SKIPPED - ALREADY EXISTS OR ERROR: FirstName LastName Clock Number
SKIPPED - ALREADY EXISTS OR ERROR: FirstName LastName Clock Number
SKIPPED - ALREADY EXISTS OR ERROR: FirstName LastName Clock Number
SKIPPED - ALREADY EXISTS OR ERROR: FirstName LastName Clock Number
SKIPPED - ALREADY EXISTS OR ERROR: FirstName(n) LastName(n) Clock Number(n)

I can use the txt/log file but for reporting purposes the CSV works great
0
 

Author Comment

by:namerg
Comment Utility
I got it I had to insert the following on line65 on  a39202232
$Out = "SKIPPED - ALREADY EXISTS OR ERROR:" + "," + $_."Last Name" + "," + $_."First Name" + "," + $_."Clock Number"

Open in new window

0
 

Author Comment

by:namerg
Comment Utility
Not sure, I am all set on this one...but this is another stage on the code...i will let you know...
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

772 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