Store 1 Element in array

Hi everyone I have a script to check to see if it can ping a list of IPs. If it cannot reach 1 it stores it in an array. The problem is if only 1 IP is stored in the array it treats each char as an element of that array. 
$psr = $PSScriptRoot
$a = Get-Content $psr\list.txt
$machines = @()
for($i=0;$i -lt $a.length;$i++){
$key = $a[$i]
$info = @()
$info = -split $key
$machines = $info[0]
#Start-Sleep -Seconds 60
for($j=0;$j -lt $machines.length;$j++){
if(!(Test-Connection -ComputerName $machines[$j] -BufferSize 16 -Count 1 -ea 0 -quiet)){
Write-Host $machines[$j]
}else{
Write-Host "All machines are awake"
It happens in the second for loop list is just a snippet of the code. How can I write to host the full IP as 1 element?
Thanks

You have a couple of options.  You can use a foreach loop instead of a for loop, which is a special case in PowerShell.  Even though strings are Enumerable, PowerShell will not enumerate over the characters in the string unless you explicitly call
its GetEnumerator() method.  Alternatively, you can put the @() operator around the call to Get-Content.  This is the array subexpression operator, and essentially tells PowerShell to convert the result to a single-element array if it is not
already an array.
$a = @(Get-Content $psr\list.txt)
# or
foreach ($key in $a)
$info = -split $key
$machines = $info[0]
It looks like you may run into a similar issue in your second loop.  In general, foreach loops are preferred, unless you need to modify the contents of the array within the loop body or do some more complex stepping logic.

Similar Messages

  • Store into an array the results of a PhpService

    Hi all I have a problem with flex and I'm stuck and we need help, this is urgent !!!!!! please
    My problem is that I would like to store in an array or ArrayCollection the result of running a php function (in my case "getTestSesion ()") to make any changes on some of the elements that my array will contain, before placing it on my  DataGrid.dataProvider (when I say change I mean items such as concatenate something to a specific element)
    I leave more and less what I have done.
    This is my table in mysql:
    CREATE TABLE IF NOT EXISTS `sesion` (
      `id_ses` int(1) NOT NULL AUTO_INCREMENT,
      `nombre_sesion` varchar(18) NOT NULL,
      `detalle_sesion` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id_ses`)
    ) ENGINE=InnoDB
    and I create this function to read my table using the Flash Builder wizard for DB connection:
    public function getTestSesion() {
         $stmt = mysqli_prepare($this->connection,
              "select id_ses as id,
                 nombre_sesion as nombre
               from sesion");    
          $this->throwExceptionOnError();
          mysqli_stmt_execute($stmt);
          $this->throwExceptionOnError();
          $rows = array();
          mysqli_stmt_bind_result($stmt, $row->id, $row->nombre);
          while (mysqli_stmt_fetch($stmt)) {
              $rows[] = $row;
              $row = new stdClass();
              mysqli_stmt_bind_result($stmt, $row->id, $row->nombre);
          mysqli_stmt_free_result($stmt);
          mysqli_close($this->connection);
          return $rows;
    and on my aplication i have:
    <fx:Script>
       protected function miDatagrid_creationCompleteHandler(event:FlexEvent):void
              createSesionResult.token = pruebasService.getTestSesion();
    </fx:Script>
    <fx:Declarations>
    <s:CallResponder id="createSesionResult"/>
    </fx:Declarations>
        <mx:DataGrid x="139" y="90" id="dataGrid"
                     creationComplete="miDatagrid_creationCompleteHandler(event)"
                     dataProvider="{createSesionResult.lastResult}">
            <mx:columns>
                <mx:DataGridColumn headerText="id" dataField="id"/>
                <mx:DataGridColumn headerText="nombre" dataField="nombre"/>
            </mx:columns>
        </mx:DataGrid>

    Hello everybody
    please can somebody help me:
    this is another simple example:
    I have this function into my service class:
    public function test($my_string)
      // creating an array by explode command
      $my_array = explode(" ",$my_string);
      return $my_array; // returning the array
    and since my aplication i call this like this:
    var myarray:Array = salfventasseriesService.test("this is a test");
    but i have this error:
    Multiple markers at this line:
    -1067: Implicit coercion of a value of type mx.rpc:AsyncToken to an unrelated type Array.
    -myarray
    How can I put the resul into an ARRAY ?
    can anybody help me ?

  • Can't store new target Array index out of range: 1 - SLD Configuration

    Hello ,
    Issue is regarding SLD configuration , We have ABAP + Java Addin on Suse Linux x86 ( 64 bit ) with Oracle 9.x .
    Java instalaltion competed succesfully , J2EE is up and runnung while configuring SLD , Data Supplier Bridge - Configure the data supplier bridge - Update SLDs
    As I set Update local SLD (sld/active) to true it gives error : Can't store new target Array index out of range: 1
    ( Error recorded in default.trace ,
    #1.5#001635052D79005D000000010000393A00041904004A592B#1153404882278#com.sap.engine.library.monitor.mapping.ccms.Trace##com.sap.engine.library.monitor.mapping.ccms.Trace######87587b2017f911dbc661001635052d79#SAPEngine_System_Thread[impl:5]_82##0#0#Error##Plain###RegisterNode</Services/Web Services/Requests Number/sap.com/com.sap.engine.heartbeat/GRMGWSTest/CurrentClient>: com.sap.mona.api.JMonException: com.sap.mona.api.JMonAPIException: Internal error in tree structure#
    #1.5#001635052D790049000000060000393A000419040226E9F1#1153404913510#com.sap.lcr.sagent.BuilderDirector#sap.com/com.sap.lcr#com.sap.lcr.sagent.BuilderDirector#J2EE_ADMIN#317####29009b1017fa11db96bd001635052d79#SAPEngine_Application_Thread[impl:3]_14##0#0#Error#1#/Applications/SLD#Plain###Can't access http store#
    #1.5#001635052D790049000000070000393A000419040226EA90#1153404913511#com.sap.lcr.sagent.BuilderDirector#sap.com/com.sap.lcr#com.sap.lcr.sagent.BuilderDirector#J2EE_ADMIN#317####29009b1017fa11db96bd001635052d79#SAPEngine_Application_Thread[impl:3]_14##0#0#Error##Plain###Thrown:
    com.sap.lcr.api.cimclient.LcrException: java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 1
    I have already through updated Component Repository – SAP Note : 669669 . 
    Regards ,
    Santosh

    Hi,
    I am having exactly the same issue. Would you please advise what the solution was?
    Thanks,
    Murad.

  • Merging elements of array

    Hi,
    I am new to programming.
    I have a sensor that sends a data stream through a serial port. I have collect all that data in a 1D unsigned byte array. Now, lets say my 1-D array is [12][45][65][12]...... where each "[ ]"  is a element of the array. Now to make sense of this data what i need to do is merge two elements the array and multipy it by 2/(2^15). i.e. My converted data should by [1245]*2/(2^15). Basically 2 bytes together makes sense. I can do a simple add of each element. Also the other problem is,data from the sensor is a stored as the 1-D array  of unsigned byte. However, the converted data is supposed to be signed 16-bit integer.
    Please give any suggestions on how to go about doing this.
    Siddhant Shah

    Another option is "decimate&Join". (Here it is easy to change the byte order if needed).
    Message Edited by altenbach on 12-15-2008 06:28 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    8bitTo16BitByteOrder.png ‏5 KB

  • Store in a array

    Hi,
    I have a program with this query script:
    public ResultSet StartQuery() {
            ResultSet rs = null;
            try {
                rs = stmt.executeQuery("SELECT uniqueid, " +
                        "clid, " +
                        "src, " +
                        "dst, " +
                        "billsec, " +
                        "DATE_FORMAT(calldate, '%H:%i:%s'), " +
                        "DATE_FORMAT(calldate, '%Y-%m-%d'), " +
                        "SEC_TO_TIME(billsec) " +
                        "FROM cdr " +
                        "WHERE calldate like '" + this.getTheDate + "%' " +
                        "ORDER BY calldate DESC");
                while (rs.next()) {
                        //How to save it on a array
            } catch (SQLException e) {
                e.printStackTrace();
            //this.secondQuerySQL(rs);
            return rs;
        }I have a code in php where in I can save my result on an array. Let me give you my script:
    public function getQueryPIN(){
              $sql = "SELECT DISTINCT PIN FROM clients";
              //$this->conn1->debug = true;
              $rs = $this->conn1->Execute($sql);
              if ( $rs === false ) return false; // SQL error ocurred
              if ( $rs->EOF ) return false; // no rows returned
              static $count=1;
              while(!$rs->EOF) {
                   //print "<font color=black>".$rs->fields['PIN']."</font> | ";
                   $count++;
                   $data_limit[$rs->fields['PIN']] = array(
                   'PIN' => $rs->fields['PIN']);
                   $rs->MoveNext();
              print $count."<br>";
              //print_r($data_limit);
              return $data_limit;
         }Can you give same process on php that can save on an array??

    ResultSet rs = null;
            Map ResultSets= new HashMap();
            try {
            rs = stmt.executeQuery("SELECT uniqueid, clid, src, dst, billsec, DATE_FORMAT(calldate, '%H:%i:%s'), DATE_FORMAT(calldate, '%Y-%m-%d'), SEC_TO_TIME(billsec) FROM cdr where calldate like '" + this.getTheDate + "%' order by calldate desc");
            while (rs.next()) {
            String[] row = {rs.getString("uniqueid"),
            rs.getString("clid"),
            rs.getString("src"),
            rs.getString("dst"),
            rs.getString("billsec"),
            rs.getString(6),
            rs.getString(7),
            rs.getString(8)
            ResultSets.put(rs.getString("uniqueid"),(String[])row);
    //        Use an *Iterator* to print the results
    //        System.out.println(ResultSets);
            } catch (SQLException e) {
            e.printStackTrace();
            }Above is the corrcted code.
    Now, to display the value by iterating through the map use the below code:
    Map ResultSets = new HashMap();
            Iterator iter = ResultSets.keySet().iterator();
            String[] newRowString = new String[8];
            while(iter.hasNext()){
                 newRowString = (String[])ResultSets.get((String)iter.next());
                 for(int i=0;i<newRowString.length; i++){
                      System.out.println("The element from Array is::: "+newRowString);
    }Edited by: AnishThomas on Mar 14, 2008 11:05 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • The prefix mx for element mx:Array is not bound

    Hi All
    I have a component:
    <?xml version="1.0" encoding="utf-8"?>
      <mx:Array id="arr">
        <mx:Object label="Flex"
          thumbnailImage="http:/someURL"
          fullImage="http://someURL" />
      </mx:Array>
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
    </mx:Canvas>
    This gives me an error
    The prefix "mx" for element "mx:Array" is not bound
    I need a root element here, but I cannot use mx:Canvas, what would be the best choice?
    cheers
    Luca

    Hi Luca,
    Try to put the Array inside your canvas rather than outside ...
    <?xml version="1.0" encoding="utf-8"?
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Array id="arr">
        <mx:Object label="Flex"
          thumbnailImage="http:/someURL"
          fullImage="http://someURL" />
      </mx:Array>
    </mx:Canvas>
    Why  you dont want to use mx:Canvas as root tag of your component.. ?? However which ever component you use try to put the <mx:Array/> inside your root tag of your component, otherwise you will be thrown the same error as mentioned. The error occurs as the the compiler doesn't recognize the namespace mx for the array since you declared it outside the root tag of your component.
    Thanks,
    Bhasker

  • Remove element from array

    hi
    if i have an array
    eg
    int[] array = {4,2,1,2,1};
    how to i remove the index 2 from it and create a new array?
    thanks

    You can't remove the element--an array's size is fixed at creation.
    If you want a new array, create a new one that's one element smaller, then use System.arrayCopy to copy the elements you want to keep.

  • How can i retrieve missing element in array

    how can i retrieve missing element in arrays if array length is exceeded

    Not sure about what the question means, but could it be that OP is not aware that the first element in an array is at index 0 (not 1) ?
    <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html" style="background:url(http://java.sun.com/docs/books/tutorial/figures/java/objects-tenElementArray.gif) no-repeat; width:400; height:145;"></a>

  • How to disable individual elements in array

    How do I disable individual elements in an array at runtime.

    I assume you are referring to the control property "disabled".
    If so there is no way to disable a single element of an array. By definition an array is a collection of data, it is not a collection of controls. A fine line but an important one. So you can configure the single control that makes up the array and defines its type. For example, if you have an array of Booleans, you can change the color of the Boolean. However this will change the color of all the Booleans in the array. It is 1 control, with a lot of values.
    Part of the reason for this is memory. Imagine an array of 1 million elements. If you could set the properties of each element, then to store that array would be incredibly large. It would be 1 million U8s for example, but then all the properties for each 1 million elements would also need to be saved. Therefore your 1 million element array of bytes could easily represent 100 million bytes in memory.
    Let me know if this explanation makes no sense, I usually explain it better, but I think I need more coffee.
    The way around this is clusters. You can change each element in a cluster, so if your array is of a manageable size, change your array control into a cluster of n elements. You can then use the cluster to array function to convert the data to the array of data you need. Unfortunately this method means that before runtime you must know the maximum number of elements you will need. You can always hide the extras, but you can not create more during execution.

  • Shift elements in arrays

    I have 5 arrays: array_0 to array_4
    array_0 contains 5 elements which are in double type:
    array_0 = ( 25.20 , 32.85, 4.24, 5.65, 4.65)
    How can I store in array_1 to array_4 with the same value of array_0 but by shifting the position by 1 to 4 respectively :
    array_1 = (4.65, 25.20, 32.85, 4.24, 5.65)
    array_2 = (5.65, 4.65, 25.20, 32.85, 4.24)
    array_3 = (4.24, 5.65, 4.65, 25.20, 32.85)
    array_4 = (32.85, 4.24, 5.65, 4.65, 25.20)
    Thanks...

    Otherwise known as the brute force approach. :-)okay then, :):class ArrayShift {
         static double array1[] = { 1, 2, 3, 4, 5 };
         static double array2[] = new double[5];
         static {
              for(int k = 0; k < array1.length; k++){
                   array2[ k ] = array1[ (k + (array1.length - 1)) % array1.length ];
                   System.out.println(array2[k] + ", ");
              System.exit(0);
    }

  • How to change a specific element in array

    hi 
    i have an 1d intialized array
    i want to take the existed array and for example add +1 for the 5th element
    how can it be done?
    thanks
    Solved!
    Go to Solution.

    In a typical application you would want to repeat that operation to form a simple histogram. This is most easily achieved by keeping the array in a shift register and repeating the operation in a FOR loop until all data is processed.
    My very simple example from a few years ago can be found here. In this case we are counting the number of occurences of small integers in a 1D array. Modify as needed.
    LabVIEW Champion . Do more with less code and in less time .

  • Web service proxy receiving single element in array

    I've generated a web service proxy over a web service and expect to get multiple elements returned from the web service. However when I excute the proxy I receive only the first element. Testing the web service with the same parameters on the application server shows that I should be receiving 3 elements in total. Not sure where the disconnect is in generating the response message within the proxy. Any suggestions is appreciated.

    Are you looking for SOAP ENC Array feature? Which version are you using 10134 or 11g?

  • Dynamically create empty mcs and asign elements from array and loadmovie

    I'm creating an educational game for my school students.
    A little boy is flying through the city when he encounters objects flying from left to right.
    He hears a SOUND eg: Dog - he must go and click the dog image with the flying cursor. There are at least 5 DIFFERENT objects that should be flying on the screen. There could be various of them at any one time.
    I have the roots of the images in an xml file. And the actual swf are in a file called IMAGE and the sounds in SOUND.
    My problem is that most tutorials I see use the attachmovie method but I don't want to put all the swf's in the library as there are hundreds.
    I have to use the loadmovie method.
    I take it I have to loop through the array and assign each element to an empty movieclip which in turn is in the loop so you get 5 empty clips - I will use i (index). It doesn't seem to be working. I shall keep trying and post back here if I get any luck but I'm running out of ideas.
    Then the objects have to float across the screen. Don't know whether to use tween object or onEnterFrame handler or other. AND someone has mentioned using setinterval to "spit out" the objects.
    BUT if I have five flying across the screen I'm left without clips to stick in any more.
    Oh my head hurts but I will keep going.
    CHEERS if any help is around. This should be quite a standard thng for game developpers. Code at the moment
    function loadEnemies():Void {
    enemy_xml = new XML();
    enemy_xml.ignoreWhite = true;
    enemy_xml.onLoad = function(success:Boolean) {
    if (success) {
    _root.parseEnemyXML();
    //enemy_xml.load("level_"+level+".xml");
    enemy_xml.load("data/animal_catch.xml");
    function parseEnemyXML():Void {
    rows = enemy_xml.firstChild.childNodes.length;
    for (var i:Number = 0; i<rows; i++) {
    var row_string:String = String(enemy_xml.firstChild.childNodes[i].firstChild.firstChild);
    _root["row_"+i+"_array"] = row_string; //MAIN ARRAY holds an array images/dog_a.swf/ images/cat_a.swf etc... all five
    _root.createEmptyMovieClip("enemyObjects", 1);
    enemyObjects.createEmptyMovieClip("holder_"+i, i);
    _root["object"+i] = new Sound(enemyObjects["holder_"+i]);
    trace(row_string);
    loadMovie["row_"+i+"_array"], ["holder_"+i]
    if (level == 1) {
    alerts_mc.play();
    } else {
    currRow = 0;
    rowCounter = 0;
    OK got to about here BUT
    a. I started to get confused around the createEmptyMovieClip part
    b. I KNOW I shouldn't have Sound(enemyObjetcs etc... BUT I copied the code from a tutorial and I don't know what to replace it with.
    I'm close but I need a little polishing.

    It doesn't do you much good to work with borrowed code that you do not understand.  Your best bet will be to start small, creating one functional piece of the puzzle at a time, and work your way up.  Start with making sure you are loading and parsing the xml properly, then set about loading the external content, then see about making that content move around, etc...
    In the code you show, your loadMovie line of code does not resemble anything I have seen before, looking more like (but not quite like) a multi-dimensional array element than a loadMovie() function call.  If you find you need to have control of the items as soon as they load, then you should consider using MovieClipLoader.loadClip instead of loadMovie.  The MovieClipLoader class provides features, such as to be able to determine when items have fully loaded.

  • Add element in array

    Hi,
    I have one String array.
    I need to create another String array with the content of 1st array and additional 1st element in the 2nd array with "Product" text.
    2nd array[0] = Product;
    How do i do it
    Thanks

    String[] array1 = {"1", "2", "3"};
    String[] array2 = {"4", "5"};
    String[] array3 = new String[array1.length+array2.length];
    System.arraycopy(array1, 0, array3, 0, array1.length);
    System.arraycopy(array2, 0, array3, array1.length, array2.length);
    here, the array3 will have all the elements in order ie, 1,2,3,4,5.
    In case you need to use array2, assign array3 to array2 ie, array2 = array3
    Hope that helps.
    Regards,
    Sumant

  • Sort Second Element in Array of Strict Type Def Clusters

    I need to sort the an array of strict type def clusters by the second or third element in the cluster.  In the past I have used 1-D array sort and sorted by the first element of the cluster.  When I need to sort by the second, third, or fourth element of the cluster I just break down the cluster and rebuild it placing the desired sort element in the first position of the new cluster.  This works for simple tasks and clusters, but as the cluster gets more complicated this becomes a pain to do this.  There must be a cleaner way to sort by other elements within the original array of strict type def clusters.  Has anyone succeeded in doing this a different way?

    Hello,
    Here's the way I would do it...just create a new cluster array, where each cluster contains two elements...the unbundled item you want to sort by, and the cluster itself.  Then sort the new cluster array, then unbundle the sorted cluster array to get the original clusters (now sorted).  Here is a screenshot:
    There may be a better way, but this is the first thing I thought of.
    -D
    Message Edited by Darren on 03-16-200610:00 AM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Sorted_cluster.jpg ‏30 KB

Maybe you are looking for