Append to CSV in PowerShell?

I'd like to find a way to append to an outputted csv file in Powershell.  Out-File has too much wasted space and duplicate lines.  Here's the script I'm trying to run:
$a=Get-Content users.txt
foreach ($i in $a)
    get-user $i | select displayname,samaccountname | Export-Csv output.csv -notype
I can't seem to find anything when dealing with an input file...  Thx.

Something like this
Param($File)  
$csvObjects = import-csv $file 
$NewCSVObject = @()  
foreach ($item in $csvObjects)  
    $NewCSVObject += $item | Add-Member -name "NewPropertyName" -value "NewValue" -MemberType NoteProperty  
$NewCSVObject | export-csv $File -noType  
Brandon Shell [MVP]

Similar Messages

  • Add Column to an existing CSV using powershell

    Hi Everyone,
    I am horribly stuck in building a logic of how can i add a column with certain details in an existing CSV using powershell. I tried many things one of the code is posted below.
    The situation is , I have a Folder path ' D:\Exclusion\Final1' it contains a list of CSV's that looks like below:
    preprocessed1.csv
    CI,Environment
    vm-Serv1,Test
    preprocessed2.csv
    CI,Environment
    vm-bkp1,Prod
    and so on with same structure..
    Then I have another CSV that Contains certain list of Patches and Title
    looks like:
    Master_Exclusion.csv
    Title, Patch
    xyz, KB23109
    abc, KB432344
    yyy, KB321221
    What I am Trying to do is to Copy the Column 'Patch' from here and copy them to all the CSVs present at ' D:\Exclusion\Final1'
    and  the output would look like :
    preprocessed1.csv
    CI ,Environment , Patch
    vm-Serv1, Test     ,KB23109
                                KB432344
                                KB321221
    CI,Environment,Patch
    vm-bkp1,Prod,  ,KB23109
                            KB432344
                            KB321221
    $filepathex=Get-ChildItem D:\Exclusion\Final1
    foreach($fileex in $filepathex)
    $exclusion=Import-Csv D:\Exclusion\Master_Exclusion.csv
    $list=Import-Csv D:\Exclusion\Final1\$fileex
    $list |
    Select-Object *,@{Name='Patch';Expression={$exclusion.Patch}}} |
    Export-Csv D:\Exclusion\Split2\$fileex -Append -NoTypeInformation
    Thanks in Advance for any help or suggestions.

    I am extremely sorry for the confusions , actually I am trying to just add a new column named "Patch" to a a list of existing CSV's . the patch column is present in another CSV i need to append it to the list of CSV's
    Like
    existing csv:
    CI,Environment
    vm-serv,Test
    and another CSV is 
    Master_Exclusion.csv
    Title,Patch
    xyz,kb084932
    yrx,KB893748
    trw,kb949298
    The output would be :
    output.csv
    CI,Environment ,Patch
    vm-serv,Test,kb084932
                         KB893748               
                          kb949298

  • External Table which can handle appending multiple csv files dynamic

    I need an external table which can handle appending multiple csv files' values.
    But the problem I am having is : the number of csv files are not fixed.
    I can have between 2 to 6-7 files with the suffix as current_date. Lets say it will be like my_file1_aug_08_1.csv, my_file1_aug_08_2.csv, my_file1_aug_08_3.csv etc. and so on.
    I can do it by following as hardcoding if I know the number of files, but unfortunately the number is not fixed and need to something dynamically to inject with a wildcard search of file pattern.
    CREATE TABLE my_et_tbl
      my_field1 varchar2(4000),
      my_field2 varchar2(4000)
    ORGANIZATION EXTERNAL
      (  TYPE ORACLE_LOADER
         DEFAULT DIRECTORY my_et_dir
         ACCESS PARAMETERS
           ( RECORDS DELIMITED BY NEWLINE
            FIELDS TERMINATED BY ','
            MISSING FIELD VALUES ARE NULL  )
         LOCATION (UTL_DIR:'my_file2_5_aug_08.csv','my_file2_5_aug_08.csv')
    REJECT LIMIT UNLIMITED
    NOPARALLEL
    NOMONITORING;Please advice me with your ideas. thanks.
    Joshua..

    Well, you could do it dynamically by constructing location value:
    SQL> CREATE TABLE emp_load
      2      (
      3       employee_number      CHAR(5),
      4       employee_dob         CHAR(20),
      5       employee_last_name   CHAR(20),
      6       employee_first_name  CHAR(15),
      7       employee_middle_name CHAR(15),
      8       employee_hire_date   DATE
      9      )
    10    ORGANIZATION EXTERNAL
    11      (
    12       TYPE ORACLE_LOADER
    13       DEFAULT DIRECTORY tmp
    14       ACCESS PARAMETERS
    15         (
    16          RECORDS DELIMITED BY NEWLINE
    17          FIELDS (
    18                  employee_number      CHAR(2),
    19                  employee_dob         CHAR(20),
    20                  employee_last_name   CHAR(18),
    21                  employee_first_name  CHAR(11),
    22                  employee_middle_name CHAR(11),
    23                  employee_hire_date   CHAR(10) date_format DATE mask "mm/dd/yyyy"
    24                 )
    25         )
    26       LOCATION ('info*.dat')
    27      )
    28  /
    Table created.
    SQL> select * from emp_load;
    select * from emp_load
    ERROR at line 1:
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    SQL> set serveroutput on
    SQL> declare
      2      v_exists      boolean;
      3      v_file_length number;
      4      v_blocksize   number;
      5      v_stmt        varchar2(1000) := 'alter table emp_load location(';
      6      i             number := 1;
      7  begin
      8      loop
      9        utl_file.fgetattr(
    10                          'TMP',
    11                          'info' || i || '.dat',
    12                          v_exists,
    13                          v_file_length,
    14                          v_blocksize
    15                         );
    16        exit when not v_exists;
    17        v_stmt := v_stmt || '''info' || i || '.dat'',';
    18        i := i + 1;
    19      end loop;
    20      v_stmt := rtrim(v_stmt,',') || ')';
    21      dbms_output.put_line(v_stmt);
    22      execute immediate v_stmt;
    23  end;
    24  /
    alter table emp_load location('info1.dat','info2.dat')
    PL/SQL procedure successfully completed.
    SQL> select * from emp_load;
    EMPLO EMPLOYEE_DOB         EMPLOYEE_LAST_NAME   EMPLOYEE_FIRST_ EMPLOYEE_MIDDLE
    EMPLOYEE_
    56    november, 15, 1980   baker                mary            alice     0
    01-SEP-04
    87    december, 20, 1970   roper                lisa            marie     0
    01-JAN-99
    SQL> SY.
    P.S. Keep in mind that changing location will affect all sessions referencing external table.

  • Appending multiple *.csv files while retaining the original file name in the first column

    Hi guys it's been awhile.
    I'm trying to append multiple *.csv files while retaining the original file name in the first column, the actual data set is about 40 files.
    file a.csv contains:
    1, line one in a.csv
    2, line two in a.csv
    file b.csv contains:
    1, line one in b.csv
    2, line two in b.csv
    output.csv result is this:
    I would like this:
    a.csv, 1, line one in a.csv
    a.csv, 2, line two in a.csv
    b.csv, 1, line one in b.csv
    b.csv, 2, line two in b.csv
    Any suggestions to speed up my hobbling attempts would be aprieciated
    Thanks,
    -SS
    Solved!
    Go to Solution.

    What you could do is given in the attachment.
    Started with 2 files :
    a.csv
    copy of a.csv
    Both with data :
    1;1.123
    2;2.234
    3;3.345
    Output :
    a.csv;1;1.123
    a.csv;2;2.234
    a.csv;3;3.345
    Copy of a.csv;1;1.123
    Copy of a.csv;2;2.234
    Copy of a.csv;3;3.345
    If you have more questions, just shoot
    Kind regards,
    - Bjorn -
    Have fun using LabVIEW... and if you like my answer, please pay me back in Kudo's
    LabVIEW 5.1 - LabVIEW 2012
    Attachments:
    AppendingCSV.JPG ‏73 KB

  • How to append two CSV files using ftp

    Hi
    Please let me know the FTP command to append the two .CSV files into one .CSV file.
    e.g.
    Let me explain:
    one CSV file has the fields F1 , F2, F3 , F4 and has 5 records
    another CSV file has the same sequence of fields F1, F2, F3, F4 and has 10 records
    after appending both the files , I must get 15 records.
    Thanks
    Alok

    Ok I will try out.
    I am illustrating my requirement as follow
    File#1 (type .CSV)
    F1     F2     F3     F4
    100   566    89     86   
    235   256    56     12
    File#2 (type .CSV)
    F1     F2     F3     F4
    56     56     98     102
    12     23     36      523
    23      56     56    89
    Now we want to Append File#1 to File#2 as follow: 
    F1    F2    F3     F4
    100   566    89     86   
    235   256    56     12   
    56     56     98     102
    12     23     36      523
    23      56     56    89
    Please suggest now that which command would be appropiate.
    Alok

  • Appending a csv column exported from Active Directory

    Hi Guys
    We have a new access control system. The DB of the control system needs to be updated with new people from Active Directory. It has an import tool to this. I want to automate it to do it every hour. So I started writing a powershell script to export any
    users that have changed in the last day. Here is what I have so far:
    Get-ADUser -Filter * -Properties * | Where {$_.Modified -ge $(Get-Date).AddDays(-1)} | select rcscardcode | Export-Csv -path C:\Users\johncolfer\Desktop\TempStuff\Active-dir\export12.csv
    So as you can see I have selected a property "rcscardcode". It is a custom attribute in AD. An example of 1 of these numbers in the exported csv file is "1141410511000000" I need to be able to change this number to "1141410511"
    and all subsequent numbers in that column of the csv file. Is this possible? 
    Any help would be great.
    Thanks
    John

    Still no joy:
    I changed a property for a test account in AD which is a standard attribute. So I changed the "company" attribute to "987654321000000" in attribute editor. I then ran the following
    Get-ADUser-Identitygoofy-Properties*|select 
    company|%{
    $_.company=$_.company.Substring(0,10)
    } |Export-Csv-pathC:\Users\johncolfer\Desktop\TempStuff\Active-dir\export1342.csv-NoType
    It ran ok, but there was nothing in the exported CSV. I was hoping to see 1 column with a value of "987654321"

  • Applescript: filenames from folder to append to csv

    For my bookkeeping I need to scan and store my receipts as a PDF file, but transfer some information (like amount and category) to an Numbers (Excel)-sheet as well. I'm using TextExpender to include al information needed for the Numberssheet inside the filename, which looks something like this:
    UIT4,20130401,23,categoryA,.pdf
    I want to transfer all the pdf-filenames in the folder to append to a csv file, so I get:
    test.csv
    UIT4,201304001,23,categoryA
    UIT5,201305002,25,categoryB
    UIT2,201306001,22,categoryA
    etc.
    I can import the csv in Numbers and all is well.
    My question for you is how can I use applescript to get all the pdf-filenames in a folder to append to a csv-file?
    I've tried this modified script by Pierre L, but I get a error regarding the ending of the file??
    set theFolder to choose folder
    set theTextFile to POSIX file "/Users/user_name/Desktop/test.csv" -- for example
    set theText to read theTextFile
    tell application "Finder"
        set theFileNames to name of files of theFolder whose name extension is "pdf"
        repeat with thisName in theFileNames
            try
                set xx to (text 1 through 2 of thisName) as integer
                set theNewFileName to paragraph (xx + 1) of theText
                if character 3 of thisName is "-" then
                    set theNewFileName to theNewFileName & character 4 of thisName
                end if
                set name of file thisName of theFolder to theNewFileName & ".pdf"
            end try
        end repeat
    end tell
    If you'd like to help out, that would be great!

    Or perhaps you could write the replacement for "_" into ";" in the Applescript itself.
    That's pretty easy using AppleScript - that way you could leave the file names intact and just change them before writing the data to the file. There are several ways of doing this and, unless you really want, I won't delve deep into the process of using text item delimiters, but an example script is below.
    - the script lets me choose a folder in a dialog box, is it also possible to direct it to a pre-specified folder?
    Of course. The first line is the one that triggers the Choose Folder dialog:
    set theFolder to (choose folder)
    You can just change this to any folder on disk by providing its path:
    set theFolder to "Macintosh HD:Users:username:Desktop:My folder"
    and making sure you tell the Finder that this represents a folder path:
              set theFiles to every file of folder theFolder whose name extension is "pdf"
    (note the addition of the 'folder' keyword.
    - is it possible to let the script create a new CSV-file named OUT4_[current date].csv?
    Yes, but....
    The third line in the script creates the output file.
              set csvFile to open for access (file ((path to desktop as text) & "my.csv")) with write permission
    You can call it whatever you like - replace 'my.csv' with the desired file name. Just be careful in putting formatted dates into filenames since characters like the '/' in '11/24/2013' will be confusing since the / is used as a directory delimiter ('11/24/2013' would normally indicate the file called '2013' inside the '24' folder that is inside the '11' folder). Date formatting in AppleScript can be tricky, but its certainly do-able. How do you want it formatted?
    Revised script that incorporates replacing underscores with commas:
    set theFolder to "Macintosh HD:Users:you:Desktop:Some folder"
    tell application "Finder"
              set csvFile to open for access (file ((path to desktop as text) & "my.csv")) with write permission
      set eof csvFile to 0 -- remove this line to append data
              set theFiles to every file of folder theFolder whose name extension is "pdf"
              repeat with eachFile in theFiles
                        set fn to name of eachFile
                        set csvData to my replaceChars(fn, "_", ",")
      write (csvData & return) as text to csvFile
              end repeat
      close access csvFile
    end tell
    on replaceChars(inputFileName, oldChar, newChar)
              set {tid, my text item delimiters} to {my text item delimiters, oldChar}
              set newfilename to text items of inputFileName
              set my text item delimiters to newChar
              set newfilename to newfilename as text
              set my text item delimiters to tid
              return newfilename
    end replaceChars

  • Working with CSV files -Powershell

    Hello all,
                 Here is a senario where am struck for past 2 days and i thought some one here can help.
    I am trying to get unique lines out of a csv file based on one particular column. Lets take a rough example , below is a sample csv i have pasted.. where i need to get only one last row from each category
    Problem
    Severity
    Category
    1
    Warning
    Event
    2
    critical
    Alert
    3
    Warning
    Alert
    4
    Warning
    Event
    5
    Warning
    Alert
    So the end result should have the complete row of problem 4&5 as that is the last appearing of unique data. Just to add an information that my csvhas 25 columns and as big as 11MB of data. Any thoughts would be greatly appreciated.
    S.Arun Prasath HP ARDE TEAM

    If I understand your scenario, this does the job...
    $testdata=import-csv 'c:\temp\test.csv'
    $categories=$testdata | Select Category -Unique
    foreach($cat in $categories){
    $testdata | Where-Object{$_.Category -eq $cat.Category} | Select -Last 1
    Result:
    Problem                                                  
    Severity                                                
    Category                                               
    4                                                        
    Warning                                                 
    Event                                                  
    5                                                        
    Warning                                                 
    Alert  
    Just a humble SysAdmin

  • ¿How to get activities templates collection from sr template and export to csv using powershell?

    Hi friends.
    I want to build a script that obtains the collection of activities templates from a sr template (filtering the sr template by displayname)  and export the list (template activities displaynames) to csv file.
    Thanks for advance.
    Cheers

    Import-Module SMLets -Force
    $templateName =  "SS-Internas" 
    $template = Get-SCSMObjectTemplate -DisplayName $templateName
    $templateAct = $template.ObjectCollection.PropertyCollection | Where { $_.Path  -eq '$Context/Property[Type=''CustomSystem_WorkItem_Library!System.WorkItem'']/Title$'}
    $report=@()
    foreach($value in $templateAct.MixedValue){
    $obj = New-Object PSObject -Property @{
    "DisplayName" = $value 
    $report += $obj
    $filePath = "E:\ACT_"+$templateName+".csv"
    $report | export-csv $filePath -NoTypeInformation -Encoding UTF8
    (Get-Content $filePath) | % {$_ -replace '"', ""} | out-file -FilePath $filePath -Force -Encoding UTF8

  • Remove specif rows in a CSV with Powershell

    Hi All,
    I have the following script which tells me if an account is in AD, disabled or not present:-
    $users = Import-Csv c:\migration\batches\AWTESTFILES\awtestfiles.csv
    foreach($u in $users){
    $Name = $u.name
    $User = Get-ADUser -LDAPFilter "(sAMAccountName=$Name)"
    If (($User  -ne $Null) -and ($user.enabled-eq $False)){
    #  $outfile = (Join-Path $destination $errfilename)
      Write-Host "$name is Disabled" -fore red
    if ($User -eq $null){
     Write-Host "$Name is not in Active Directory" -ForegroundColor Yellow
    #  $Name =  "$($u.name) is not in Active Directory "
    #    Add-Content $outfile -Value $Name
    If (($User -ne $null) -and ($User.enabled -eq $true)){
     Write-Host "$name is in Active Directory and Enabled" -fore green
    If the account is disabled or not present I wan to remove the entry from the csv file so that they are not migrated.
    What is the easiest way to do this?
    I know how to call up excel and manipulate some data but I'm not sure how to delete a specific row base on the name
    TIA
    Andy

    Hi Andy,
    I'd test the users in your input file and then create a new output file that only contains the enabled users. Are you able to use a second file or do you have to update the original?
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • How to get Document Set property values in a SharePoint library in to a CSV file using Powershell

    Hi,
    How to get Document Set property values in a SharePoint library into a CSV file using Powershell?
    Any help would be greatly appreciated.
    Thank you.
    AA.

    Hi,
    According to your description, my understanding is that you want to you want to get document set property value in a SharePoint library and then export into a CSV file using PowerShell.
    I suggest you can get the document sets properties like the PowerShell Command below:
    [system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
    $siteurl="http://sp2013sps/sites/test"
    $listname="Documents"
    $mysite=new-object microsoft.sharepoint.spsite($siteurl)
    $myweb=$mysite.openweb()
    $list=$myweb.lists[$listname]
    foreach($item in $list.items)
    if($item.contenttype.name -eq "Document Set")
    if($item.folder.itemcount -eq 0)
    write-host $item.title
    Then you can use Export-Csv PowerShell Command to export to a CSV file.
    More information:
    Powershell for document sets
    How to export data to CSV in PowerShell?
    Using the Export-Csv Cmdlet
    Thanks
    Best Regards
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • Help appending how many times an event ID has occurred next to the unique Event ID.

    Hello,
    I am trying to figure out how to find how many times an event occurred and then append that next to the single  -unique Event ID.
    The closest I can find is the Sort-Object Count but I can't figure out how to get that work within the below script.
    Any help would be appreciated, the below script works already. but just doesn't have that Event ID count. 
    Thank you for any help. 
    Below is the
    script to pull all Event Logs for each server, filter them to only display Warnings, Failures, and FailureAudits for Application, System, and Security logs and then remove all duplicate EventIDs so only 1 of each is shown. it then exports that info into a
    .CSV per server.
    param([string]$days= "31" )
    $servers = @("Server1", "Server2" "Server3", "Etc")
    $user = Get-Credential
    #Set namespace and calculate the date to start from
    $namespace = "root\CIMV2"
    $BeginDate=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime((get-date).AddDays(-$days))
    $store = "C:\Powershell\MonthlyMaintenance"
    foreach ($computer in $servers)
    $filter="TimeWritten >= '$BeginDate' AND (type='Warning' OR type='Error' OR type='FailureAudit')"
    Echo "Pulling Event Logs for $computer ..."
    Get-WmiObject Win32_NTLogEvent -computername $computer -Filter $filter |
    sort eventcode -unique |
    select Computername,
    Logfile,
    Type,
    @{N='TimeWritten';E={$_.ConvertToDateTime($_.TimeWritten)}},
    SourceName,
    Message,
    Category,
    EventCode,
    User |
    Export-CSV C:\Powershell\MonthlyMaintenance\$computer-Filter.csv
    Echo "Done."

    Unfortunately adding that to the script just outputs a bunch of jargon:
    #TYPE Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
    ClassId2e4f51ef21dd47e99d3c952918aff9cd
    pageHeaderEntry
    pageFooterEntry
    autosizeInfo
    shapeInfo
    033ecb2bc07a4d43b5ef94ed5a35d280
    Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo
    Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo
    9e210fe47d09416682b841769c78b8a3
    I did try adding it in various ways and removing the initial # Sort EventCode -unique | # and I just get the same jargon
    Am I adding it in wrong some how? 
    Thank you again for any help.
    param([string]$days= "31" )
    $servers = @("ComputerName")
    $user = Get-Credential
    #Set namespace and calculate the date to start from
    $namespace = "root\CIMV2"
    $BeginDate=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime((get-date).AddDays(-$days))
    $store = "C:\Powershell\MonthlyMaintenance"
    foreach ($computer in $servers)
    $filter="TimeWritten >= '$BeginDate' AND (type='Warning' OR type='Error' OR type='FailureAudit')"
    Echo "Pulling Event Logs for $computer ..."
    Get-WmiObject Win32_NTLogEvent -computername $computer -Filter $filter |
    sort eventcode -unique |
    select Computername,
    Logfile,
    Type,
    @{N='TimeWritten';E={$_.ConvertToDateTime($_.TimeWritten)}},
    SourceName,
    Message,
    Category,
    User,
    EventCode | Select Name,Count | FT -auto|
    Export-CSV C:\Powershell\MonthlyMaintenance\$computer-Filter.csv
    Echo "Done."

  • Bulk Create Users from CSV: Error: "Put": "There is no such object on the server."?

    Hi,
    I'm using the below PowerShell script, by @hicannl which I found on the MS site, for bulk creating users from a CSV file.
    I've had to edit it a bit, adding some additional user fields, and removing others, and changing the sAMAccount name from first initial + lastname, to firstname.lastname. However now when I run it, I get an error saying:
    "[ERROR]     Oops, something went wrong: The following exception occurred while retrieving member "Put": "There is no such object on the server."
    The account is created in the default OU, with the correct firstname.lastname format, but then it seems to error at setting the "Set an ExtensionAttribute" section. However I can't see why!
    Any help would be appreciated!
    # ERROR REPORTING ALL
    Set-StrictMode -Version latest
    # LOAD ASSEMBLIES AND MODULES
    Try
    Import-Module ActiveDirectory -ErrorAction Stop
    Catch
    Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
    Exit 1
    #STATIC VARIABLES
    $path = Split-Path -parent $MyInvocation.MyCommand.Definition
    $newpath = $path + "\import_create_ad_users_test.csv"
    $log = $path + "\create_ad_users.log"
    $date = Get-Date
    $addn = (Get-ADDomain).DistinguishedName
    $dnsroot = (Get-ADDomain).DNSRoot
    $i = 1
    $server = "localserver.ourdomain.net"
    #START FUNCTIONS
    Function Start-Commands
    Create-Users
    Function Create-Users
    "Processing started (on " + $date + "): " | Out-File $log -append
    "--------------------------------------------" | Out-File $log -append
    Import-CSV $newpath | ForEach-Object {
    If (($_.Implement.ToLower()) -eq "yes")
    If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
    Write-Host "[ERROR]`t Please provide valid GivenName, LastName. Processing skipped for line $($i)`r`n"
    "[ERROR]`t Please provide valid GivenName, LastName. Processing skipped for line $($i)`r`n" | Out-File $log -append
    Else
    # Set the target OU
    $location = $_.TargetOU + ",$($addn)"
    # Set the Enabled and PasswordNeverExpires properties
    If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
    If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }
    If (($_.ChangePasswordAtLogon.ToLower()) -eq "true") { $changepassword = $True } Else { $changepassword = $False }
    # A check for the country, because those were full names and need
    # to be land codes in order for AD to accept them. I used Netherlands
    # as example
    If($_.Country -eq "Netherlands")
    $_.Country = "NL"
    ElseIf ($_.Country -eq "Austria")
    $_.Country = "AT"
    ElseIf ($_.Country -eq "Australia")
    $_.Country = "AU"
    ElseIf ($_.Country -eq "United States")
    $_.Country = "US"
    ElseIf ($_.Country -eq "Germany")
    $_.Country = "DE"
    ElseIf ($_.Country -eq "Italy")
    $_.Country = "IT"
    Else
    $_.Country = ""
    # Replace dots / points (.) in names, because AD will error when a
    # name ends with a dot (and it looks cleaner as well)
    $replace = $_.Lastname.Replace(".","")
    $lastname = $replace
    # Create sAMAccountName according to this 'naming convention':
    # <FirstName>"."<LastName> for example
    # joe.bloggs
    $sam = $_.GivenName.ToLower() + "." + $lastname.ToLower()
    Try { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" -Server $server }
    Catch { }
    If(!$exists)
    # 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.
    $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
    Try
    Write-Host "[INFO]`t Creating user : $($sam)"
    "[INFO]`t Creating user : $($sam)" | Out-File $log -append
    New-ADUser $sam -GivenName $_.GivenName `
    -Surname $_.LastName -DisplayName ($_.LastName + ", " + $_.GivenName) `
    -StreetAddress $_.StreetAddress -City $_.City `
    -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
    -Company $_.Company -Department $_.Department `
    -Title $_.Title -AccountPassword $setpass `
    -PasswordNeverExpires $expires -Enabled $enabled `
    -ChangePasswordAtLogon $changepassword -server $server
    Write-Host "[INFO]`t Created new user : $($sam)"
    "[INFO]`t Created new user : $($sam)" | Out-File $log -append
    $dn = (Get-ADUser $sam).DistinguishedName
    # Set an ExtensionAttribute
    If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
    $ext = [ADSI]"LDAP://$dn"
    $ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
    Try { $ext.SetInfo() }
    Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
    # Move the user to the OU ($location) 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
    If ([adsi]::Exists("LDAP://$($location)"))
    Move-ADObject -Identity $dn -TargetPath $location
    Write-Host "[INFO]`t User $sam moved to target OU : $($location)"
    "[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
    Else
    Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!"
    "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
    # 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
    Rename-ADObject -Identity $newdn -NewName ($_.LastName + ", " + $_.GivenName)
    Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n"
    "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
    Catch
    Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
    Else
    Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
    "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
    Else
    Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
    "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    $i++
    "--------------------------------------------" + "`r`n" | Out-File $log -append
    Write-Host "STARTED SCRIPT`r`n"
    Start-Commands
    Write-Host "STOPPED SCRIPT"

    Here is one I have used.  It can be easily updated to accommodate many needs.
    function New-RandomPassword{
    $pwdlength = 10
    $bytes = [byte[]][byte]1
    $pwd=[string]""
    $rng=New-Object System.Security.Cryptography.RNGCryptoServiceProvider
    while (!(($PWD -cmatch "[a-z]") -and ($PWD -cmatch "[A-Z]") -and ($PWD -match "[0-9]"))){
    $pwd=""
    for($i=1;$i -le $pwdlength;$i++){
    $rng.getbytes($bytes)
    $rnd = $bytes[0] -as [int]
    $int = ($rnd % 74) + 48
    $chr = $int -as [char]
    $pwd = $pwd + $chr
    $pwd
    function AddUser{
    Param(
    [Parameter(Mandatory=$true)]
    [object]$user
    $pwd=New-RandomPassword
    $random=Get-Random -minimum 100 -maximum 999
    $surname="$($user.Lastname)$random"
    $samaccountname="$($_.Firstname.Substring(0,1))$surname"
    $userprops=@{
    Name=$samaccountname
    SamAccountName=$samaccountname
    UserPrincipalName=“$[email protected]”)
    GivenName=$user.Firstname
    Surname=$surname
    SamAccountName=$samaccountname
    AccountPassword=ConvertTo-SecureString $pwd -AsPlainText -force
    Path='OU=Test,DC=nagara,DC=ca'
    New-AdUser @userprops -Enabled:$true -PassThru | |
    Add-Member -MemberType NoteProperty -Name Password -Value $pwd -PassThru
    Import-CSV -Path c:\users\administrator\desktop\users.csv |
    ForEach-Object{
    AddUser $_
    } |
    Select SamAccountName, Firstname, Lastname, Password |
    Export-Csv \accountinformation.csv -NoTypeInformation
    ¯\_(ツ)_/¯

  • Powershell output results log

    Hi guys.
    I have a question and do not know if you can
    help me.
    I do not know much about Powershell,
    but I created a script that disables,
    moves and changes the description of dismissed
    enterprise users through the registration number
    (POBOX in my case).
    The question is would you like to generate a log
    each time this script was executed,
    stating whether or not the actions were
    performed successfully.
    Tested
    with some examples I found on Technet
    but did not work.
    Does anyone havea hint howcan I includethis functionalityin my script?
    $csvFile = ".\list.csv"
    $disabledUsersOU = "<OU DESTINATION>"
    Import-Csv $csvFile | ForEach {
     $f = $_.POBox;
     Get-ADUser -Filter {POBox -eq $f} | Disable-ADAccount
     Get-ADUser -Filter {POBox -eq $f} | Set-ADUser -Description "Disable User Script v4"
     Get-ADUser -Filter {POBox -eq $f} | Move-ADObject -TargetPath $disabledUsersOU
     $user = Get-ADUser -Filter {POBox -eq $f} -Properties MemberOf
     foreach ($group in ($user | Select-Object -ExpandProperty MemberOf))
      Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
    Thanks a lot.
    David Soares MCTS:MBS - MCTS - MCITP

    You could try something like this:
    $csvFile = ".\list.csv"
    $disabledUsersOU = "<OU DESTINATION>"
    $Results = Import-Csv $csvFile | ForEach {
    $f = $_.POBox;
    Get-ADUser -Filter {POBox -eq $f} | Disable-ADAccount
    Get-ADUser -Filter {POBox -eq $f} | Set-ADUser -Description "Disable User Script v4"
    Get-ADUser -Filter {POBox -eq $f} | Move-ADObject -TargetPath $disabledUsersOU
    $user = Get-ADUser -Filter {POBox -eq $f} -Properties MemberOf,Description,Enabled
    foreach ($group in ($user | Select-Object -ExpandProperty MemberOf))
    Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
    $user = Get-ADUser $user -properties MemberOf,POBox,Description
    New-Object PSObject -property @{User=$user.samaccountname;POBox=$user.POBox;Description=$user.Description;MemberOf=(($user | select -expand MemberOf) -join ",");Enabled=$user.Enabled;DN=$user.DistinguishedName}
    $Results | Select User,POBox,Description,MemberOf,Enabled | Export-CSV ".\results.csv" -NoType
    All I really added was to create New-Object for each user and each one gets included in $Results, which gets piped to a csv file.  This way you can see what may or may not have succeeded.  The alternative is to evaluate each of the values and compare
    it to what you expect - if any of them are not what you would expect, then User = fail and instead of the new-object line and having all of the output go to $Results you could do:
    Out-File ".\results.log" -InputObject "$($User.sAMAccountName) = FAIL" -append
    (or PASS, or SUCCESS, or whatever works).  The reason I provided the approach above is that you have a complete picture of the results.
    The select in the last line orders the columns in the CSV, otherwise Powershell chooses the order and it isn't usually what you would like.
    I hope this post has helped!

  • How to export Listitems in sharepoint 2010 using powershell

    I am able to export all items in sharepoint list by below command in powershell
    Export-SPWeb -Identity
    "http://myurl.com" -   path
    "C:\Export\Lists\Announcements.cmp" -ItemUrl
    "/Lists/Announcements/AllItems.aspx" -Force
    My list is having huge data in production I want to export only 10 items from the list using powershell. Is there any command to export only certain items.
    I want to filter the Items and export only certain set of items using Export command.
    Rajendra

    Hi all,
    To export a list you can try: 
    Export data from SharePoint 2010 List using Management Shell: http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Server/MS-SharePoint/A_9182-Export-data-from-SharePoint-2010-List-using-Management-Shell.html
    Export SharePoint 2010 List to Excel with PowerShell: http://iwillsharemypoint.blogspot.com.es/2011/02/export-sharepoint-2010-list-to-excel.html
    Export SharePoint List Items to CSV using PowerShell: http://www.sharepointdiary.com/2013/04/export-sharepoint-list-items-to-csv-using-powershell.html
    If a post answers your question, please click Mark As Answer on that post and
    Vote as Helpful

Maybe you are looking for

  • Installing Aperture 3 onto new MacBook Pro

    Hi Support Team, I own a copy of Aperture 3.0 (on disk); I bought the software back in 2010 when it was first released and have been running the software on my MacBook Pro (2009 model). Now, I have bought the new MacBook Pro Retina and installed Moun

  • My course is stuck in the quiz section...

    I'm using captivate 8 and all the settings are set so the user can retake the quiz upon failure and review. When I play the course, the first part allows full navigation, but when I get to the quiz it gets stuck.  I cannot move forward or back and I

  • Problem with deploytool

    I'm using IPlanet 6 SP3 and am using the deploytool to deploy my application. The application deploys without errors, but one of my jar files that lives under WEB-INF/lib does not get fully unpacked. I have some dtd files which live in the JAR with t

  • How do I remove the links underneath the main toolbar (most visited, latest headlines, news, Apple, etc.)?

    I have no idea how to remove the links that are underneath the main toolbar (where the back and forward buttons are, refresh, etc.). I know they got there by either Apple default, or by me accidentally dragging something there. I have tried dragging

  • Can't open sticky notes

    I transferd an old Windows XP hard drive into a new Windows 8 pc. I can open the older pdf files in Reader XI, I can see the Icons of the sticky notes made last year, but to scroll or click on them does nothing. I can make new sticky notes and the ne