PowerShell - Start-Job - Synchronised Array list

Hi all,
I am trying to write a script using start-job against a list of machines. The script is to query a target machine event log using get-winevent cmdlet. I supply the whole code that queries the eventlog in a scriptblock. In order to capture the output (one
psobject for each of the scriptblock jobs) I am trying to use a synchronised arraylist. I do not know the full details of how to use the synchronised arraylist but I have put together the below script (by referring to some of the online articles). But the
script does not work as intended. The individual scriptblocks do not seem to be referring to the global arraylist variable while appending the results.
Would any of you be able to shed any light on it?
Please note, the script without the PowerShell Jobs works fine(that is linear execution which is really time-consuming). Also, even with using psJobs, the script works when I try to dump the result of each job into a csv from within the job itself. But I
want to avoid this situation because due to the asynchronous execution there might be contention for the csv by more than one jobs at the same time. Hence I want to use the synchronised array list.
$InputCSV = "$(Split-Path $SCRIPT:MyInvocation.MyCommand.Path -parent)\backupexec.csv"
$OutputCSV = "$(Split-Path $SCRIPT:MyInvocation.MyCommand.Path -parent)\Reports\BackupExec_Output_$(Get-Date -format "ddMMyyyy")_$((Get-Date).DayOfWeek).csv"
$OutputArray = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
$counter=1
$jobs=@{};
$jobcounter=0;
Import-CSV $InputCSV | ForEach {
$Comp_Name=$_.ServerName;
$Counter+=1;
$Scriptblock={
Try {
$IsthereAnyResult= @()
$IsthereAnyResult= Get-WinEvent -ComputerName $Using:Comp_Name -ErrorAction SilentlyContinue -FilterHashTable @{LogName='application';ProviderName='Backup Exec';ID=57755; StartTime=(Get-Date).AddDays(-1)}
$props = @{
"Server Name" = ($event.MachineName -split '\.')[0];
"Event ID" = $event.ID;
"Time Logged" = $event.TimeCreated;
"Backup Result" = Switch ($event.ID) { '57755' {"Success - Skipped"}
'34113' {"Failed"}
'34112' {"Success"} };
"Message" = $event.Properties[0].value -replace '\n' -replace '\r';
$OutputArray += New-Object PSObject -Property $props
} #end try get-winevent
Catch { } #end Catch
} #end scriptblock
$jobs[$jobcounter]= Start-job -name $("Job_$jobcounter") -ScriptBlock $Scriptblock
$jobcounter+=1;
While((Get-Job -State 'Running').Count -ge 10) {
Start-Sleep -Milliseconds 10
} # end main foreach
Get-Job | Wait-Job
$OutputArray | Select-Object "Server Name","Event ID","Time Logged","Backup Result","Message" | Export-CSV -force -Path $OutputCSV -NoTypeInformation -Append

How about this?
I use wmi win32_ntlogevent which i prefer ..  Timeservice is just for example ...
Change the scriptblock to your needs and report the result :]
Param ([int]$BatchSize=2)
#list of servers
[array]$source = (get-adcomputer -filter {name -like "server*"}) |select -expandproperty dnshostname
$blok = {
get-wmiobject Win32_NTLogEvent -Filter "(Logfile='System') and (SourceName = 'Microsoft-Windows-Time-Service')" |select -first 10 |select __server,@{n="EventCode";e={switch($_.EventCode){37{"37 - Receiving"}35{"35 - Synchronizing"}129{"129 - NTP Fail"}default{"Other EventCode"}}}},@{n="Date";e={$_.ConvertToDateTime($_.TimeGenerated)}},message
$elapsedTime = [system.diagnostics.stopwatch]::StartNew()
$result = @()
$itemCount = 0
## checking running jobs
if (get-job|? {$_.name -like "Script*"}){
write-host "ERROR: There are pending background jobs in this session:" -back red -fore white
get-job |? {$_.name -like "Script*"} | out-host
write-host "REQUIRED ACTION: Remove the jobs and restart this script" -back black -fore yellow
$yn = read-host "Automatically remove jobs now?"
if ($yn -eq "y"){
get-job|? {$_.name -like "Script*"}|% {remove-job $_}
write-host "jobs have been removed; please restart the script" -back black -fore green
exit
$i = 0
$itemCount = $source.count
Write-Host "Script will run against $itemcount servers!"
## Script start time mark
write-host "Script started at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
write-host " (contains $itemCount unique entries)" -back black -fore green
$activeJobCount = 0
$totalJobCount = 0
write-host "Submitting background jobs..." -back black -fore yellow
for ($i=0; $i -lt $itemCount;$i += $batchSize){
$activeJobCount += 1; $totalJobCount += 1; $HostList = @()
$HostList += $source |select -skip $i -first $batchsize
$j = invoke-command -computername $Hostlist -scriptblock $blok -asjob
$j.name = "Script`:$totalJobCount`:$($i+1)`:$($getHostList.count)"
write-host "+" -back black -fore cyan -nonewline
write-host "`n$totaljobCount jobs submitted, checking for completed jobs..." -back black -fore yellow
while (get-job |? {$_.name -like "Script*"}){
foreach ($j in get-job | ? {$_.name -like "Script*"}){
$temp = @()
if ($j.state -eq "completed"){
$temp = @()
$temp += receive-job $j
$result += $temp
remove-job $j
$ActiveJobCount -= 1
write-host "-" -back black -fore cyan -nonewline
elseif ($j.state -eq "failed"){
$temp = $j.name.split(":")
if ($temp[1] -eq "R"){
$temp = @()
$temp += receive-job $j
$result += $temp
remove-job $j
$ActiveJobCount -= 1
write-host "-" -back black -fore cyan -nonewline
else{
write-host "`nFailure detected in job: $($j.name)" -back black -fore red
$temp = @()
$temp += receive-job $j
$result += $temp
remove-job $j
$ActiveJobCount -= 1
if ($result.count -lt $itemCount){
sleep 3
write-host " "
write-host "Script finished at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
write-host (" Elapsed Time : {0}" -f $($ElapsedTime.Elapsed.ToString())) -back black -fore green
$result |select __server,eventcode,Date,message |ft -auto
write-host " Script completed all requested operations at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
write-host (" Elapsed Time : {0}" -f $($ElapsedTime.Elapsed.ToString())) -back black -fore green

Similar Messages

  • PowerShell using start job to run multiple code blocks at the same time

    I will be working with many 1000’s of names in a list preforming multiple function on each name for test labs.
    I notice when it is running the functions on each name I am using almost no CPU or memory.  That led me to research can I run multiple threads at once in a PowerShell program. That lead me to articles suggesting start-job would do just want I am looking
    for. 
    As a test I put this together.  It is a simple action as an exercise to see if this is indeed the best approach.  However it appears to me as if it is still only running the actions on one name at a time.
    Is there a way to run multiple blocks of code at once?
    Thanks
    Start-Job {
    $csv1 = (Import-Csv "C:\Copy AD to test Lab\data\Usergroups1.csv").username
    foreach ($name1 in $csv1) { Write-Output "Job1 $name1"}
    Start-Job {
    $csv2 = (Import-Csv "C:\Copy AD to test Lab\data\Usergroups2.csv").username
    foreach ($name2 in $csv2) { Write-Output " Job2 $name2"}
    Get-Job | Receive-Job
    Lishron

    You say your testing shows that you are using very little cpu or memory in processing each name, which suggests that processing a single name is a relatively trivial task.  
    You need to understand that using a background job is going to spin up another instance of powershell, and if you're going to do that per name what used to require a relatively insignificant amount of memory is going to take around 60 MB.  
    Background jobs are not really well suited for multi-threading short-running, trivial tasks.  The overhead of setting up and tearing down the job session can be more than the task itself.
    Background jobs are good for long-running tasks.  For multi-threading short, trivial tasks runspaces or a workflow would probably be a better choice.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Multidimensional array with start-job

    Hi! I'm trying to improve a script that will read in a CSV file to an array, divide it up to 4 chunks. So I will have 4 arrays and inside each array I have properties for computername, ip addresses and so forth. ($arrComputers[0][56].ComputerName)
    So what I want to do is:
    # Send 1 chunk array at a time to a Start-Job. 1 chunk consits of 100 computers.
    # Read each object,  $arrComputers[index][row].Status ,
    # If Status says "OK" don't continue to check, Else continue to fetch info and write back to
    $arrComputers[index][row].<property>
    So for I've only gotten to 
    $Script={
    Param($comp)
    <Do Check, Read and Write for each computer here>
    for($i=0;$i -lt 4;$i++)
    $compCollection[$i] | Start-Job -ScriptBlock $Script -ArgumentList ($compCollection[$i]
    I hope I have been clear what I'm trying to do. This is my first time trying it, so wouldn't surprise me if you guys got a better idea how to achieve what I want or what I've done wrong. I'm all ears and also to pointers to guides and such where I can read
    up more about advanced powershelling. 

    $computerlist | 
         ForEach-Object{
             Start-Job -Script $script
    -ArgumentList $_
    but
    $script={Param($computer)
    if($computer.Status -eq "OK"){
    #Do Nothing
    else
    #Do Something
    $computer.Status = #Assign new value
    #write back the same chunk it derived from.
    for($i=0;$i -lt 4;i++){
    $computerlist[$i] |
    ForEach-Object{
    Start-Job -Script $script -ArgumentList $_

  • Accessing Array and Iterating Array list - Need Oracle Pro Assistance

    Hi,
    This is the third time i am posting the question, :( .
    I want some advice on how to iterate through a Array list which has an array of tasks/processes and make calls to the corresponding subprocess for each element in the list.
    We are looking for a BPMN approach.
    Any example or ideas would be of great help.
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).
    In Oracle BPM 11g I would like to use a multi-instance subprocess to send a task to a user for each item in an array. There are an unknown number of rows in the array. Does anyone have a good example of how to do this?
    I am using BPM Oracle 11g but any help 10 will also help us.
    I am reposting again this question , hoping that someone will help us
    Thanks
    Edited by: user9083699 on Aug 28, 2010 4:03 AM

    I am not the expert on 11g, however, in 10g, if I understand correctly... it sounds like you should be able to use PAPI to notify instances/sub processes, etc....
    With a list of Instances, you can search for that instance and notify it...
    If you have a list of processes, that need to be started, you can create an instance within that process....
    user9083699 wrote:
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).If you are just trying to initiate a sub-process, (btw, why would they have to be subprocesses?), It sounds like you should be able to create a global in the process, and just call it with PAPI...
    I'm still a little fuzzy, on how this business requirement turned up... however, maybe this helps a little?
    -Kevin

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Start-job with datetime arguments

    Hi,
    It is working (of course), I get all objects which are newer then $timeFrom:
    $timeFrom = "2014-03-25 9:00"
    Get-ChildItem c:\temp | ?{$_.CreationTime -gt $timeFrom}
    But is not working:
    $timeFrom = "2014-03-25 9:00"
    Start-Job -ScriptBlock {Get-ChildItem c:\temp | ?{$_.CreationTime -gt $args[0]}} -ArgumentList @($timeFrom)
    I get all objects, but if I replace -gt to -lt the list will be empty. Teherefore any kind of compare working, but I can't understand how...
    Anybody can help me?

    When you're using variables defined outside of the scriptblock you have to pass them into the scriptblock.  I prefer to keep them all the same just because it's easier to understand for me.  Yours probably would have worked if you'd included the
    param part:
    Start-Job -ScriptBlock {param($args)Get-ChildItem c:\temp | ?{$_.CreationTime -gt $args[0]}} -ArgumentList
    @($timeFrom)
    but I'm not sure whether or not using $args works at all in this context.  It probably does, but without param it definitely wouldn't.
    I hope this post has helped!

  • How to use Start-Job?

    Hello folks,
    I am trying to setup a simple Start-Job command.  This basic command works for me and copies the file correctly.
    Start-Job -Scriptblock {Copy-Item -Path \\192.168.32.25\share\butterfly.jpg -Destination c:\test\ -Recurse -Verbose}
    However, it does not work when I try using variable like this.
    $source = "\\192.168.32.25\share\butterfly.jpg"
    $target = "c:\test\"
    Start-Job -Scriptblock {Copy-Item -Path $source -Destination $target -Recurse -Verbose}
    Anyone have suggestions for getting this to work with variables?
    Thanks,
    romatlo

    Hi,
    Here's some information:
    http://powershell.org/wp/forums/topic/passing-parameter-to-start-job/
    https://social.technet.microsoft.com/Forums/scriptcenter/en-US/ff644fca-1b25-4c8a-9a8a-ce90eb024389/in-powershell-how-do-i-pass-startjob-arguments-to-a-script-using-param-style-arguments?forum=ITCG
    Basically, look at using -ArgumentList:
    http://ss64.com/ps/start-job.html
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • MSX - post 'Start Job' instructions to specific target servers

    I have an MSX server with about 150 targets.  I'm trying to post download instructions for specific targets (not all targets) to 'Start Job' for a given job.  According to http://technet.microsoft.com/en-us/library/ms178327%28v=sql.110%29.aspx,
    I can target specific servers with instructions.  Instruction types defect, set polling interval, and synchronize clocks all work when specific targets are selected.  However, start job does not work for me.  My test is as follows:
    Instruction Type:  Start Job
    Job name:  Test Database Mail
    Recipients:  These target servers.  I select one or more from the list of 150 targets.
    When I click OK, I get a warning that 'Job is already in process.' for each selected target.  The job is never started and yet the job is not actually in progress.  Am I missing a setting somewhere?  Is this a bug?  I can't find anything
    online regarding other people having this issue.
    My MSX server is running SQL 2012 sp1 ENT.  My targets range from 2005 sp1 up to 2012 sp1.
    Ryan

    Hi PHC_DBA,
    According to your description, I do a test in my environment, it indeed show the warning of “Job is already in progress.” . Personally, I recommend you that submit a feedback to Microsoft such issues at this link
    https://connect.microsoft.com/SQLServer/Feedback.
      This connect site will serve as a connecting point between you and Microsoft, and ultimately the large community for you and Microsoft to interact with. Your feedback enables Microsoft to offer the best software and deliver
    superior services, meanwhile you can learn more about and contribute to the exciting projects on Microsoft Connect.
    In addition, one MSX server can control multiple TSX servers. There is no explicit limit defined in the system; however, for practical purposes and to reduce extra load on the master server due to frequent polling connections, it is recommended to
    keep the number of TSX servers under 100. For more information, see:http://www.yaldex.com/sql_server_tutorial_3/ch08lev1sec5.html
    Thanks,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • How to schedule job with spool list recipient in CPS ?

    Dear Guru,
    i import job with spool list recipient from r3 to cps and schedule in CPS, job is finished but there is no spool send to the recipient ?
    Please advise ?
    Best regards,
    Supat Jupraphat.

    What job definition did you use? SAP_AbapRun? SAP_AbapRunPrint? SAP_AbapRunPrintExt?
    Do you have XBP 2.0 or 3.0 in the SAP system? (check SE38 > INITXBP2)
    Have you loaded the CPS transport files in the SAP system?
    Note that using spoollist recipients either involves SAP_AbapRunPrintExt in combination with XBP3.0
    OR
    It involves SAP_AbapRun or SAP_AbapRunPrint and XBP 2.0 using transportation files in the SAP System.
    Please check the section of the CPS admin guide called: "Enhanced SAP Interfaces with Redwood Transports"
    Regards,
    David

  • Is possible to pass array/list as parameter in TopLink StoredProcedureCall?

    Hi, We need to pass an array/List/Vector of values (each value is a 10 character string) into TopLink's StoredProcedureCall. The maximum number of elements on the list is 3,000 (3,000 * 10 = 30,000 characters).
    This exposed two questions:
    1. Is it possible to pass a Vector as a parameter in TopLink's StoredProcedureCall, such as
    StoredProcedureCall call = new StoredProcedureCall();
    call.setProcedureName("STORED_PROCEDURE_NAME");
    call.addNamedArgument("PERSON_CODE");
    Vector strVect = new Vector(3000);
    strVect.add(“ab-gthhjko”);
    strVect.add(“cd-gthhjko”);
    strVect.add(“ef-gthhjko”);
    Vector parameters = new Vector();
    parameters.addElement(strVect);
    session.executeQuery(query,parameters);
    2. If the answer on previous question is yes:
    - How this parameter has to be defined in Oracle’s Stored Procedure?
    - What is the maximum number of elements/bytes that can be passed into the vector?
    The best way that we have found so far was to use single string as a parameter. The individual values would be delimited by comma, such as "ab-gthhjko,cd-gthhjko,ef-gthhjko..."
    However, in this case concern is the size that can be 3,000 * 11 = 33, 000 characters. The maximum size of VARCHAR2 is 4000, so we would need to break calls in chunks (max 9 chunks).
    Is there any other/more optimal way to do this?
    Thanks for your help!
    Zoran

    Hello,
    No, you cannot currently pass a vector of objects as a parameter to a stored procedure. JDBC will not take a vector as an argument unless you want it to serialize it (ie a blob) .
    The Oracle database though does have support for struct types and varray types. So you could define a stored procedure to take a VARRAY of strings/varchar, and use that stored procedure through TopLink. For instance:
    StoredProcedureCall call = new StoredProcedureCall();
    call.setProcedureName("STORED_PROCEDURE_NAME");
    call.addNamedArgument("PERSON_CODE");
    oracle.sql.ArrayDescriptor descriptor = new oracle.sql.ArrayDescriptor("ARRAYTYPE_NAME", dbconnection);
    oracle.sql.ARRAY dbarray = new oracle.sql.ARRAY(descriptor, dbconnection, dataArray);
    Vector parameters = new Vector();
    parameters.addElement(dbarray);
    session.executeQuery(query,parameters);This will work for any values as long as you are not going to pass in null as a value as the driver can determine the type from the object.
    dataArray is an Object array consisting of your String objects.
    For output or inoutput parameters you need to set the type and typename as well:
      sqlcall.addUnamedInOutputArgument("PERSON_CODE", "PERSON_CODE", Types.ARRAY, "ARRAYTYPE_NAME"); which will take a VARRAY and return a VARRAY type object.
    The next major release of TopLink will support taking in a vector of strings and performing the conversion to a VARRAY for you, as well as returning a vector instead of a VARRAY for out arguments.
    Check out thread
    Using VARRAYs as parameters to a Stored Procedure
    showing an example on how to get the conection to create the varray, as well as
    http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/varray/index.html on using Varrays in Oracle, though I'm sure the database docs might have more information.
    Best Regards,
    Chris

  • Adding two array lists together and a text file to an array list

    I'm having problems coding these two methods... Could someone explain how to do this? I can't find information on it anywhere... :(
    "MagazineList" is the class I'm coding in right now, and I already declared "list" as an array list of another class called "Magazine".
    public boolean addAll(MagazineList magazines)
           if (list == magazines) {
               return false;
            else {
                list.addAll(magazines);
           return true;
       public boolean addAll(String filename)
           Scanner in = ResourceUtil.openFileScanner(filename);
            if (in == null) {
               return false;
            String line = source.nextLine();
            while (!line.equals("")) {
              list.add(Magazine(source));
           in.close();
       }

    I assume "addAll(MagazineList magazines)" is defined in the MagazineList class?
    Then,
    list.addAll(magazines);probably needs to be something like:
    list.addAll(magazines.list);This uses the private variable ( should be private) list from the input MagazineList, and adds all of those Magazine objects to the list in the current MagazineList.
    But, yes, describe your problems more clearly, and you'll get better answers more quickly (because people will be able to understand you and give you a suggestion without asking you another question first).

  • How do I extract the length of an element in an Array List

    Hello there,
    I am facing this problem with an Array List of elements. I am trying to extract the individual length of a particular element in the array list . Now if I know the element is a String is this valid?
    int lengthOfElement = 0;
    lengthOfElement = ((String)parms.get(i)).length();
    Your answer is much appreciated
    Regards

    Snap!I don't know how many times I've seen people post
    saying that they have a list where each element is a
    String, but they keep on getting ClassCastException :)Damn those Integers!
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Accessing Array and Iterating Array list

    Hi,
    I want some advice on how to iterate through a Array list which has an array of tasks/processes and make calls to the corresponding subprocess for each element in the list using BPM 11g
    We are looking for a BPMN approach.
    Any example or ideas would be of great help.
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).
    In Oracle BPM 11g I would like to use a multi-instance subprocess to send a task to a user for each item in an array. There are an unknown number of rows in the array. Does anyone have a good example of how to do this?
    I am using BPM Oracle 11g but any help 10 will also help us.
    I am reposting again this question , hoping that someone will help us
    Thanks

    Others probably are getting it, but I'm not really sure what it is that you're tyring to do with the list of instances.
    I'm getting lost in two areas. First, you mentioned you have a rules engine returning a list of instances. Mostly out of curiosity - why do you have an array of instances being created by a rules engine? What is the use case? Asking because I'm sure to learn something new from you on this - I'm used to seeing a lot of things coming back from an invoked rule, but never an array of instances before.
    Second (sure you know this), in both 10g and 11g there is a Split-N activity that you can use to parse (as the name implies) "N" number of instances. This "N" is discoverable at runtime. If you have 14 instances in your array at runtime, it would go into a Split-N activity and 14 instances would automatically be spawned. The 14 instances would flow from the Split-N to its corresponding Join activity in the process.
    Dan

  • Object in array list

    Is it possible that object can be store in array list.
    package{
    // Importing object from flash libary
        import flash.text.TextField;
        import flash.display.Sprite;
    // Creating class
         public class Show extends Sprite {
         //Attribute
        private var txt:Array = new Array();
         // Constructor 
           function Show()
                   txt[0]:TextField =  new TextField();
                     addChild(txt[0]);
                     txt[0].width=320;
                     txt[0].height=25;
                     txt[0].x=0;
                     txt[0].y=0;
                     txt[0].border=true;
                   txt[0].text="nepalikto";
    Error
    Description : Label must be a simple identifier
    Location : Above orange textcolor line

    Not sure if this all is 100% technically correct but:
    You only use datatyping if you actually create a variable. Like:
    var myArray:Array = new Array();
    if you do not declare the var with the var keyword, you can't use datatyping either.
    // this is wrong
    myArray:Array = new Array()
    It is good practice to use datatyping whenever possible since it can help you debug an application:
    Flash finds the possible errors in code where one variable contains different datatypes at different times which can be confusing
    Flash helps with the codecompletion feature once a variable is typed so there's less chance of typos.
    The items in the array, unlike CS4's new Vector datatype aren't typed. Probably has some memory usage reason in the onderlying C++ code but I'm not sure. If you have CS4 you could possibly use:
    var txt:Vector.<TextField> = new Vector.<TextField>();
    To tell you the truth I haven't used the CS4 Vector Datatype so I'm not sure if aside from faster code execution there's errorcheckings on it's contents like mentioned above.
    Hope this helps some

  • Cant add to the end of the array list

    Hey everyone
             for(String word : dictionary){
                 if(word.equalsIgnoreCase(newWord) == false && word.compareToIgnoreCase(newWord) >= 0){
                     dictionary.add(dictionary.indexOf(word), newWord);
                     save();
                     break;
        }i am struggling to see the bug in my code, why will it not allow me to enter anything to the end of the array list, but anywehere other is fine?
    thanks very much

    Try posting a SSCCEE. Your code could be better written:
    1. You are using the enhanced for loop, then you have to turn around and use indexOf to see where you are in the list. Think about that.
    2. Are you sure you have to use both equalsIgnoreCase and compareIgnoreCase to get the result you need?

Maybe you are looking for

  • What cables do I need to print wirelessly if i don't have an Airport Basestation?

    I recently bought an Epson Stylus NX230 with wireless capabilities but I am unsure about how to enable AirPrint feature because I don't understand the terminology in the manuals. Firstly, I don't know how to join my printer to my network (or if I act

  • User of TCS- getting error when launching Captivate

    I am a TCS user, which comes with Captivate. I have been using FM and RoboHelp for sometime now... and now we want to start using Captivate. When I go to launch Captivate off my start menu, I am unable to do so- I get this error: "This Product is alr

  • I am having problems with Elements 11 loading photos into the Photomerge tool. They become distorted

    I have updated and reinstalled the software with no luck. I'm using Windows 8. Has anyone else had this problem or now how to fix it? Any help would be appreciated.

  • Missing text in ordered books - Fixed?

    I have had the problem with missing text when generating books and calendars. However, after the latest updates (6.0.4) this problem seem to be solved. Now, when I print the books as PDF all text is placed where it is supposed to be. Are there anyone

  • Re : Maintenance view

    Hi       We created two customized table and alos set foregin key relation ship. That was working fine. Then we try to create maintanance view for the above two table. There I include the base table, then I selected relation bush button to add the se