PowerShell combining objects

In the following script I am attempting to pull some basic data from Exchange and combine the objects into a single output. I believe the problem is tied to the output assigned to my $Usage variable, as there are going to be multiple results for each database.
I'd also like to sort the data by the "Time In Server" column.
The output I get currently looks like this:
Database     | Display Name | Time In Server
DB01
DB02
DB03
The output I'd like to achieve:
Database     | Display Name | Time In Server
DB01             User 3              250
DB01             User 4              225 
DB03             User 2              190
DB03             User 1              100
# Create a new variable with today's date.
$todaysDate = (Get-Date).tostring("MM-dd-yyyy")
# Retreive a list of mailbox databases
$Databases = (Get-MailboxDatabase | where {$_.Name -like "DB*"} | select Name)
# Create an array to store the output
$Output = @()
# Go through each database and retreive the usage statistics
foreach ($Database in $Databases) {
$Usage = (Get-StoreUsageStatistics -Database $Database.Name | where {$_.TimeInServer -gt "5000"} | Select DisplayName, TimeInServer)
# Create a new object to store this information
$OutputItem = New-Object PSObject;
$OutputItem | Add-Member NoteProperty "Database Name" $Database.Name;
$OutputItem | Add-Member NoteProperty "Display Name" $Usage.DisplayName;
$OutputItem | Add-Member NoteProperty "Time In Server" $Usage.TimeInServer;
# Add the object to our array of output objects
$Output += $OutputItem;
$Output | Export-CSV "$todaysDate.csv" -NoTypeInformation

Hi ImageGuy,
good going so far :).
Your main issue is that you are not handling the possibility of multiple usage cases on a single Database. Here's a rewrite example on how to do this:
# Create a new variable with today's date.
$todaysDate = Get-Date -Format "MM-dd-yyyy"
# Retreive a list of mailbox databases
$Databases = Get-MailboxDatabase | Where-Object { $_.Name -like "DB*" }
# Create an array to store the output
$Output = @()
# Go through each database and retreive the usage statistics
foreach ($Database in $Databases)
# For each usage that exceeds limits
foreach ($Usage in (Get-StoreUsageStatistics -Database $Database.Name | Where-Object { $_.TimeInServer -gt "5000" }))
# Collect information into a hashtable
$Props = @{
"Database Name" = $Database.Name
"Display Name" = $Usage.DisplayName
"Time In Server" = $Usage.TimeInServer
# Add the object to our array of output objects
$Output += New-Object PSObject -Property $Props
$Output | Sort-Object "Time In Server" | Export-CSV "$todaysDate.csv" -NoTypeInformation
Also, as it will only perform the inner loop if at least one case of excessive usage exists, you won't get entries for DBs that do not have anyone using it in excess of limits.
I simplified the object creation a little (though there certainly are other methods that work just as well including your previous one).
Finally, on the last line you see an example for sorting.
Cheers,
Fred
There's no place like 127.0.0.1

Similar Messages

  • Help with Combining Objects

    I've been thinking of submiting some of my Illustrator designs to iStock and I want clean up the files and perhaps combine some of the objects so there isn't this bigg mess of layers. The problem I'm having is that some objects need to be on top of other objects - for example a shadow on a foot needs to be above the layer with the foot's primary color. So if I wanted to combine objects that are in this kind of order would anyone have any tips or suggestions? I also want to combine layers that have just lines I've drawn on them, like movement lines which are just open paths with strokes. If I could get these types of objects all merged into one object then I could cut down not only on the size of the file but also the number of layers involved. This way when someone buys it from iStock they're not faced with this huge file with hundreds of layers.
    Any help would be appreciated.
    Thank you.

    Fully familiarize yourself with these topics:
    Combining paths. These are functions common in vector programs which union, punch, and intersect multiple paths. In Illustrator, they are called Pathfinders.
    Outlining Srokes. Creates unstroked filled paths around the edges of stroked paths. Understanding this is integral to using path combination functions in Illustrator especially, because Illustrator is so poor at cutting and dealing with open unfilled paths.
    Transparency and other Raster Effects. You need to understand which effects and transparency settings result in rasterization, and what that portends regarding the scaleability of your artwork.
    Color Model. Are you going to deliver CMYK or RGB files? Do you know why?
    What format do you intend to provide to the clipart reseller? Native AI files? If so, what version?
    Merely having Layers in your AI file does not significantly affect file size. An AI file is a stack of objects. That's true whether the whole stack of objects resides on a single Layer or a hundred Layers. Layers are nothing but another way of "grouping" subsets of the object stack for organization purposes. You seem to be thinking of Layers in AI as similar to Layers in Photoshop. That is a very common and very basic misunderstanding of the nature of vector artwork.
    It's the object constructs that you need to concern yourself with when creating clean, efficient, reliable, versatile, and easy-to-work-with vector artwork. "Normalize" things to their simplest constructs. Avoid unnecessary anchorpoints, clipping paths, masking, so-called "transparency" and "live effects."
    I very much applaud your desire to build clean files. (There is far too much sloppy, convoluted crap floating around out there nowadays.) Not meaning to discourage, but the fact of your concern about Layers frankly suggests that you may not really be ready to be delivering ready-made and problem-free artwork for widespread use as clipart. You need to fully understand the items mentioned above, and alot more. Asking questions in a user forum will be a very slow method of learning that stuff--there are too many variables and specific situations.
    JET

  • Combining objects of two Lists

    I have two input lists ArrayList <A> and ArrayList <B> which are of same size. I want to create ArrayList <C> out of A and B.
    C is a class with two attributes which are of type A and B. C has a constructor which takes in A and B as two parameters.
    I can not change the existing implementations of A,B,C however I am at liberty to add new class or extend existing Generic classes
    Can this be done using existing Generic classes?
    My intention is to avoid loops like following:
    public ArrayList<C> join(ArrayList <A> a, ArrayList <B> b)
            ArrayList c<C> = new ArrayList<C>();
            for(int i=0;i<a.size();i++)
                  c.add(new C(a.get(i),b.get(i)));
            return c;
    }I can not make a non generic function because there are many cases in my code base where A,B,C change (but the relation that C has two attributes of class A and B is valid for all of them).

    Thanks for pointing out the approach. I am getting a compilation error. To keep it small I am keeping the join method and Combinator interface function combine in the same class. I have implemented the following sample code :
    import java.util.*;
    class A
              int x;
    class B
              String y;
    class StrInt
              A z;
              B w;
              public StrInt(A a,B b)
                        z = a;
                        w = b;
    interface Combinator <X,Y,Z>
              public Z combine(X a,Y b);
    public class Com implements Combinator
              public Object combine(Object o, Object O)
                        return null;
              public StrInt combine(A a, B b)
                        return new StrInt(a,b);
              public <A,B,D> List <D> join (List <A> a,List <B> b, Combinator com)
                        ArrayList <D> c = new ArrayList<D>();
                        for (int i=0;i<a.size();i++)
                                  c.add((D) com.combine(a.get(i),b.get(i)));
                        return c;
         public Com()
                   ArrayList <A> a= new ArrayList <A> ();
                   ArrayList <B> b= new ArrayList <B> ();
         public static void main(String a[])
                   Com c = new Com();
    }However I get an error
    Com.java:28: Com is not abstract and does not override abstract method combine(j
    ava.lang.Object,java.lang.Object) in Combinator
    public class Com implements Combinator
    I am new to Generics so do not know the rules for use of a generic interface.

  • Powershell Custom Object Support

    is there a way to pass a powershell custom object created in a .Net activity powershell snippet to another runbook without it being converted to a string?  if not, are there plans to add this feature in the future? 
    e.g
    $obj = New-Object PSObject
    Add-Member -InputObject $obj -MemberType NoteProperty -Name customprop -Value "this is prop"
    Add-Member -InputObject $obj -MemberType NoteProperty -Name Serial -Value "12345"

    Hi,
    in the "Run .Net Script" Activity you can define  Date/Time, Integer, or String as output type of the custom Published Data, not PowerShell object.
    That's up to the version System Center 2012 R2.
    Regards,
    Stefan
    www.sc-orchestrator.eu ,
    Blog sc-orchestrator.eu

  • How to combine objects into one

    Can I combine two or more objects (say, text box and rectangle) so that they effectively become one object? Other software calls this Grouping of objects.

    Welcome to the Apple Discussions. See Old Toad's Tutorial #7 - Converting Photos w/Frames, Drop Shadows and/or Reflections into a Single JPG Image. It describes exactly what you want to do.
    OT

  • Powershell New-object Command not reconized am i missing a module?

    I want to configure high trusted app for app dev in SharePoint, end to do so i need first to insert some commands in the powershell editor like :
        $publicCertPath = "C:\Certs\HighTrustSampleCert.cer" 
        $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($publicCertPath)
    I am using windows PowerShell on Windows Server 2012 R2 which includes Windows PowerShell 4 that includes by default the new-object cmd-let... I don't understand though, why doesn't my system recognize that command .... Each time i am getting the following
    error : New-Object : The term 'New-Object' is not recognized as the name of a cmdlet.
    Every time i open power shell it displays me the following error :
    *select : The term 'Select-Object' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    At C:\Program Files\Common Files\Microsoft Shared\Web Server
    Extensions\15\CONFIG\POWERSHELL\Registration\SharePoint.ps1:1 char:16
    + $ver = $host | select version
    +                ~~~~~~
        + CategoryInfo          : ObjectNotFound: (Select-Object:String) [], Comma
       ndNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    Set-location : The term 'Set-location' is not recognized as the name of a
    cmdlet, function, script file, or operable program. Check the spelling of the
    name, or if a path was included, verify that the path is correct and try again
    At C:\Program Files\Common Files\Microsoft Shared\Web Server
    Extensions\15\CONFIG\POWERSHELL\Registration\SharePoint.ps1:4 char:1
    + Set-location $home
    + ~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (Set-location:String) [], Comman
       dNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException*
    I thought that was normal until today... does it have any relation with the error?
    And here is the hole (new-object) exception stack:
    *New-Object : The term 'New-Object' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    At line:1 char:16
    + $certificate = New-Object
    System.Security.Cryptography.X509Certificates.X509Cert ...
    +                ~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (New-Object:String) [], CommandN
       otFoundException
        + FullyQualifiedErrorId : CommandNotFoundException*
    Can anyone help me please?

    the new-object cmdlet is not defined in a module.
    Try this:
    reboot your computer
    start the powershell console
    type a new-object command without parameter
    this is what happens when I do that:
    PS C:\Users\Al> new-object
    cmdlet New-Object at command pipeline position 1
    Supply values for the following parameters:
    TypeName:
    what happens on your system?
    Al Dunbar 
    Aren't you able to see a simple semantic error?
    I told you almost never post any technical text, just vague and imprecise generalities.
    When you try to post something technical, you post a rubbishellian text like this one, typical of a decrepit old vb scripter 101% PowerShell ignorant.
    Certainly, you are the worst rubbishellian I met in this forum.
    @admins: will you please, inhibit the reply button for this rubbishellian forum member? He should just ask questions; never answer any of them.
    Your post above is off-topic in this thread, as it is a personal attack on me that contains no information likely to actually help the OP with his problem.
    I was not aware that you are the arbiter here of what is appropriate to post, especially given your collection of abusive posts and banned accounts.
    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

  • Powershell - Select-Object -Unique vs Group-Object

    Hi,
    I have the following problem with powershell.
    I have a list of strings call it $machine_list which
    I know there are duplicates.
    The following  code produces the following output:
    $machine_list.count -- 15375
    $a = $machine_list | Select-Object -Unique
    $a.Count -- 12134
    $b = $machine_list | Group-Object -NoElement
    $b.Count -- 12082
    I am trying to get a unique list and looking at different
    ways of doing it.
    So in my example above why are the counts different?
    Should they not be the same - $a.Count -eq $b.Count?
    I am hoping somebody can explain this in more detail to me.
    Also is there a way I can compare the results to see how they
    differ? (Comparing $a with the Name Values of $b).
    Thanks,
    Ward.

    Dirk - another way to think this out.  "group" means that each named group has a unique name.  In a list of strings the group name and object are identical so the list of group names is the list of identical strings.
    Select -unique and sort -unique produce an identical set of lists.  Select -unique, however, does not necessarily produce a sorted output although the output is guaranteed to be unique.  What you may be mixing up is that many learned to add sort
    in PowerShell V1 because they did not get a sorted output from a unique operation.  As I posted above, this issue has come up constantly as people start to learn databases.  A company that I used to work for wrote its own 'uniquing' code.  It
    always produced a sorted output as a byproduct of the method.  When we implemented SQL database technology the programmers could not understand why select unique in SQL did not produce a sorted output.  They constantly complained that it was a bug.
    In most cases we would like a uniquing operation or not sort the results.  Suppose I have a result set order a specific way.  Now I want group it on a column but I do not want the order of the records changed.  Grouping and select unique should
    not change the order.  There are many discussions in the database field as to why this needs to be.  I am not sure which set of standards PS follows.  In PS1 it appeared to follow the industry standard.  Maybe I will test it later.
    ¯\_(ツ)_/¯

  • How to combine "Object-to-XML (OXM)" and "Direct to XML Type" mapping?

    hi
    If I have an XMLType column in my table (wich I can map using TopLink) and I have defined the structure of the contents of this XMLType column using XML Schema (wich I can map using Toplink), how can I combine both types of TopLink mappings "as transparently as possible"?
    for "Object-to-XML (OXM)" mapping
    see http://www.oracle.com/technology/products/ias/toplink/technical/tips/ox/index.htm
    for "Direct to XML Type" mapping
    see http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/_html/relmapun004.htm#CHDFIFEF
    thanks
    Jan Vervecken

    Thanks for your reply James Sutherland.
    Although I haven't used a "TopLink Converter" before, this seems like a good idea.
    The thing is that the "TopLink Workbench Editor" for my "Direct to XML Type" mapping doesn't have a "Converter" tab, some other mapping type editors do have such a "Converter" tab.
    I'm not sure if I completely understand how such a "TopLink Converter" is supposed to work. How many attributes do I need in the "XMLRow" Java object for the "MY_XML" column in the "XML_TABLE" table I try to map to?
    I suppose I should try to get a situation where the "XMLRow" Java object has an "myXML" attribute of Java class type "MyXML" (where "MyXML" has been mapped to an XML Schema), not?
    So do I also still need an attribute "myXMLDocument" of type org.w3c.dom.Document as I do now for the "Direct to XML Type" mapping?
    Oh, by the way ... for anyone who hits this forum thread looking for the reason why the TopLink Workbench reports the problem "Attribute must be assignable to java.lang.String, org.w3c.dom.Document, or org.w3c.Node" while your attribute is of such a type, read this forum post
    Re: Toplink WB 10.1.3 - Aggregate field mapping bug and XMLType question
    For me the "Direct to XML Type" mapping works fine, just ignoring the waring. This is supposed to be bug number 5071250.
    thanks
    Jan Vervecken

  • Powershell - Select-object - exclusion if null

    Hi All,
    I hope someone can help a powershell beginner. I currently have a script that pulls out users and certain information that gets added to a csv file. I would like to know if it possible to remove any contacts that don't have a TITLE in AD so the TITLE is
    null.
    We dont want these users added to the csv file. I thought i may be have been able to do this with an ExcludeProperty but not sure how to go about it. 
    This is what i have so far: 
    Import-Module activedirectory
    Get-ADUser -Filter * -Properties Name,Title,Manager,EmployeeID -SearchBase "OU=OU" | select-object Name,Title,Manager,EmployeeID | Export-Csv "C:\List.csv" -NoTypeInformation
    Any help is much appreciated. 
    Thanks,

    Hi,
    You can filter this by piping where-object:
    Get-ADUser -Filter * -Properties Name,Title,Manager,EmployeeID -SearchBase "OU=OU" | select-object Name,Title,Manager,EmployeeID | where-object {$_.Title -ne $null} | Export-CSV "C:\List.csv" -NoTypeInformation
    This will list all objects where the attribute Title is not equal (-ne) to $null
    Kind regards,
    Armand
    "The beginning of knowledge is the discovery of something we do not understand."

  • Combining Objects into one object

    I have just learned Live Cycle this past week without assistance and so far so good.  My question is, I am trying to create a single object from multiple objects that I can repeat and insert through a button using the Action Command.  Is there a way to turn the multiple objects grouped into one item.  When I go into Action Builder, I keep getting the same message - "Subfolder container not flowed" and "Subform configured to be repeatable".  Can anyone help?

    Post the question in the forum for LiveCycle Designer?

  • PowerShell Adding Objects to a Hash/Scope

    Hi All,
    I realize this isn't directly related to SMO/DMO, but the overall script is. :) The problem I am having is that I am writing errors out to an Exception table and trying to capture the ID returned into a Hash table in the CATCH block. That part works just
    fine. now, if I just reference the $Errors Hash table in the CATCH block it prints out to the screen showing data in it. However, if I reference the $Errors Hash table outside of the catch block it shows nothing.  Can someone tell me what I am doing
    wrong here? I can only guess its getting reset, but I am just not sure.
    function Import-Data
    $Errors = @{}
    [string] $tsConnections = @"
    SELECT instance from dbo.Instances
    [string] $tsProperties = @"
    SELECT name FROM sys.databases
    try
    $dtConnections = Get-DataTable -ConnectionString:$Repository -Query:$tsConnections;
    foreach ($drConnections in $dtConnections.Rows)
    $dtProperties = Get-DataTable -ConnectionString:$drConnections[5] -Query:$tsProperties;
    foreach ($drProperty in $dtProperties.Rows)
    $drProperty[0]
    catch [system.exception]
    $Message = $_.Exception.Message
    $ReturnCode = Call-ProcedureWithResult -ConnectionString:$Repository -Procedure:"upException" -Parameters:@{Module="Import-Data"; Exception=$Message}
    $Value = $ReturnCode.Value
    $Errors.Add("Exception", $Value)
    Continue;
    $Errors
    John M. Couch

    OK, so, I modified the code a bit, and moved the attempt to print out the Errors into a finally block and it works. My only guess is that it won't print outside of the try/catch/finally because of scope, but I am confused as to why when I declared
    the hash table outside of the block itself. Maybe because when you use the ADD method it actually drops the hash table and recreates a new one with the old values + the new value??? Grasping at straws, but its the only logical explanation I can think of.
    This is the modified portion of the code that works.
    catch [system.exception]
    $Message = $_.Exception.Message
    $ReturnCode = Call-ProcedureWithResult -ConnectionString:$Repository -Procedure:"upException" -Parameters:@{Module="Import-Data"; Exception=$Message}
    $Errors[$drProperty[0]] = $ReturnCode.Value.ToString()
    Continue;
    finally
    $Errors
    John M. Couch

  • PowerShell Moving Object Issue

    I have a script that I wrote to pull PC names from a csv file, disable them, modify the description then move them to a specified OU.  I'm running into a small issue.  For instance, I have a PC named desktop1 that I want to disable and move. 
    It's also moving desktop10, desktop11, etc.
    I'm using the following command:
    Get-QADComputer $ComputerID | Move-QADObject -NewParentContainer $DisabledOU
    Is there an easy way to tell it to only copy desktop1 instead of searching for all pcs with that string in the name?

    Actually I forgot.  Haven't used Quest for a bit.
    The default match method is ANR.  You need to force this by explicitly using the name
    $ComputerID='desktop1'
    Get-QADComputer -Name
    $ComputerID
    By using the 'Name' parameter you will force an exact match instead of an ANR match.
    Using a Where can be an issue because it will retrun everything and filter afterwards.  When a CmdLet has a filter mechanism, and most do, use the filter.  It is more efficient.
    Another way to filter is:
    $ComputerID='desktop1'
    Get-QADComputer -SamAccountName "$ComputerID$"
    ¯\_(ツ)_/¯

  • How to add a project into master project by Powershell

    How to add a master project and sub-projects powershell
    I use project server 2013, I want inserting multiple sub-project plans into a project master

    Hello,
    You can't do this directly in PowerShell using the PSI etc. as the PSI can't create master projects / insert subprojects. You could however do this in VBA if required or automate Project using PowerShell COM object.
    Paul
    Paul Mather | Twitter |
    http://pwmather.wordpress.com | CPS

  • Powershell Array Export Issues

    Hey everyone! So I might just be going about this the wrong way but here's my issue. The script functions as I need it to however, when I export the values to my .csv, the columns are in the wrong order than the way I think they should be. Here's what I've
    got:
    $list = Get-content targets.txt
    Foreach($_ in $list) {
    $SAM = Get-RegValue -ComputerName $_ -Key Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI -Value LastLoggedOnSAMUser
    $User = Get-RegValue -ComputerName $_ -Key Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI -Value LastLoggedOnUser
    @('Name','LastUserAccessed','LastUserLoggedOn')
    New-Object PSObject -Property @{
    Name = ($SAM).ComputerName
    LastUserAccessed = ($User).Data
    LastUserLoggedOn = ($SAM).Data
    } | Export-csv Results.csv -notypeinformation -append}
    I would like it to read Name, LastUserAccessed, and LastUserLoggedOn but it comes out to be LastUserAccessed, Name, LastUserLoggedOn. Any ideas as to why this is happening? Thanks in advance!

    Okay, then instead of using 'New-Object PsObject -Property', use [pscustomobject].
    http://blogs.interfacett.com/powershell-v3-object-creation-accelerator
    EDIT: Or you can just use [ordered] if you'd prefer:
    http://stackoverflow.com/questions/7802406/use-cases-of-ordered-the-new-powershell-3-0-feature
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Cant tell when Merge drawing model vs. Object drawing model

    I keep drawing shapes on the same layer, overlapping them,
    and then trying to delete one of the shapes to cut a shape out of
    the first. This does not work automatically as Help says it does, I
    have to go to "Modify > Combine Objects > Union" to merge
    them, THEN I can cut my shape out. When is this supposed to occur
    "automatically"? How am I supposed to know what mode I'm in?

    sifupeter,
    > I keep drawing shapes on the same layer, overlapping
    > them, and then trying to delete one of the shapes to cut
    > a shape out of the first. This does not work
    automatically
    > as Help says it does
    It depends entirely on what mode you're in. ;) When you have
    a drawing
    tool selected (Rectangle, Pencil, etc.), take a look at the
    "circle" button
    near the "magnet" button at the bottom of the Tools panel.
    Hover over the
    circle button to see the "Object Drawing" tool tip. When that
    button is
    pressed in, you're in Object Drawing mode; when it's not
    pressed in, you're
    not.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

Maybe you are looking for

  • Dump while running MRP: MD03:   PERFORM_CONFLICT_TAB_TYPE CX_SY_DYN_CALL_IL

    Dear All, I am trying to run MRP for a single item at a single level. The program is giving a dump. If anyone knows a way around kindly tell me. Thanks. Anu. SHORT DUMP: Runtime errors         PERFORM_CONFLICT_TAB_TYPE                                

  • PNG is no longer transparent!

    I have been using Photoshop since PS7. I love it. I am also a professional graphic and web designer/developer. This problem has never occured to me in the 8 years I've been using the program. So, needless to say I'm stumped! When slicing up my design

  • HT1338 i can't update my java

    i tried to updat my java software but i cant. i have already pressed the apple icon then software upadate but it poped out said your software is up to date, so what can i do to update my java???

  • Creating Client-side Image Map in Web Dynpro

    Hi, How can I create a client-side Image Map in Web Dynpro application? My application consists of a screen-size image in which several areas will have to link to URLs and actions. I have browsed through the "Web Dynpro UI Element Reference Guide," b

  • Mutilple Filter Objects - Changing where clause and or

    Is it possible to have a query as below using filter commands. (obj1 = 'value11' and obj2 = 'value21') or (obj1 = 'value12' and obj2 = 'value22') or The objective is to manipulate the where clause and , or . Thanks in Advance Bhanu Mohanty