Returns a copy of the hash table
I have problems by returning a copy of a hash that is normally stored in the persistent store table.
final class SyncCentres { private static Hashtable syncCentres; private static PersistentObject persist; private static final long ID=0xdfeab99e040a223aL; static{ persist=PersistentStore.getPersistentObject(ID); syncCentres=(Hashtable)persist.getContents(); synchronized(persist){ if(syncCentres==null){ syncCentres=new Hashtable(4); persist.setContents(syncCentres); persist.commit(); } } } static Hashtable getSyncCentres(){ return syncCentres; } } // Class
When I get the hash table in another class by using the static method.
Hashtable hash=SyncCentres.getSyncCentres();
It turns out that it is not a copy. Change the hash variable will edit the SyncCentres class as well. Is this normal? How can I get a copy of it?
Java, copy and pass the reference by value, not the object.
See
http://www.Yoda.arachsys.com/Java/passing.html
or
http://www.JavaWorld.com/JavaWorld/javaqa/2000-05/03-QA-0526-pass.html
If you want a true copy of the hash table you need to clone and each of its objects.
You can also copy all objects to a new hash table, but these are always references to the same objects as in the first hash table.
Tags: BlackBerry Developers
Similar Questions
-
ListField using the hash table
Hi guys, new here so please, be gentle.
I was wondering if there is way to a ListField (or something similar) but using a hash instead of a vector table. I searched through the forums without success. And if it is would it be possible to display the incredible list. (List in the hash table and sort by alphabetical order, via the keys)
The hash table structure K = String (name of player), V = object reader.
If this can be done using a hash table, is there a way to do this using a vector. So that I could search the data structure for a players name and return the object.
Sorry if it's confusing or vague. I'm not not used to describe my problems!
Thank you very much for the help.
You can also move forward and persist in the hash table, and then build an index using a few stores of SimpleSortingVector who keys in order.
There are a lot of options... you just need to decide which is best for you.
-
PageContext.forwardimmediatly works not when the hash table is used.
Hello
I try to use as below:
HashMap hm = new HashMap (1);
HM.put ("conc_called", "Yes");
pageContext.forwardImmediately ("OA.jsp?page=/XXX/xxPG",
NULL,
OAWebBeanConstants.KEEP_MENU_CONTEXT,
NULL,
GMC
true,
"N");
But I get an error message indicating that the method does not exist. Any suggestion would be appreciated.
Thank you
PKMake sure the hash table is of the type com.sun.java.util.collections.HashMap and not java.util.HashMap
-
SQLite3 command-line copy at the other Table? Help
Hi all.
I'm trying to copy a row in a table and copy it to another table.
That's what I currently have.
Insert into Table2 select * from Table2 where ROWID = 1;
But I get on to a General Protection Fault by the following SQLitefunction, which is located in the sqlite3.c file
/*
* Report the allocated size of the prior return of xMalloc()
* or xRealloc().
*/
public static int sqlite3MemSize(void *pPrior) {}
sqlite3_int64 * p;
If (pPrior == 0) return 0;
p = (sqlite3_int64 *) pPrior;
p-- ;
Return (int) p [0];
}Can someone please help me solve this problem?
-
update to column values (false) in a copy of the same table with the correct values
Database is 10gr 2 - had a situation last night where someone changed inadvertently values of column on a couple of hundred thousand records with an incorrect value first thing in the morning and never let me know later in the day. My undo retention was not large enough to create a copy of the table as it was 7 hours comes back with a "insert in table_2 select * from table_1 to timestamp...» "query, so I restored the backup previous nights to another machine and it picked up at 07:00 (just before the hour, he made the change), created a dblink since the production database and created a copy of the table of the restored database.
My first thought was to simply update the table of production with the correct values of the correct copy, using something like this:
Update mnt.workorders
Set approvalstat = (select b.approvalstat
mnt.workorders a, mnt.workorders_copy b
where a.workordersoi = b.workordersoi)
where exists (select *)
mnt.workorders a, mnt.workorders_copy b
where a.workordersoi = b.workordersoi)
It wasn't the exact syntax, but you get the idea, I wanted to put the incorrect values in x columns in the tables of production with the correct values of the copy of the table of the restored backup. Anyway, it was (or seem to) works, but I look at the process through OEM it was estimated 100 + hours with full table scans, so I killed him. I found myself just inserting (copy) the lines added to the production since the table copy by doing a select statement of the production table where < col_with_datestamp > is > = 07:00, truncate the table of production, then re insert the rows from now to correct the copy.
Do a post-mortem today, I replay the scenario on the copy that I restored, trying to figure out a cleaner, a quicker way to do it, if the need arise again. I went and randomly changed some values in a column number (called "comappstat") in a copy of the table of production, and then thought that I would try the following resets the values of the correct table:
Update (select a.comappstat, b.comappstat
mnt.workorders a, mnt.workorders_copy b
where a.workordersoi = b.workordersoi - this is a PK column
and a.comappstat! = b.comappstat)
Set b.comappstat = a.comappstat
Although I thought that the syntax is correct, I get an "ORA-00904: 'A'. '. ' COMAPPSTAT': invalid identifier ' to run this, I was trying to guess where the syntax was wrong here, then thought that perhaps having the subquery returns a single line would be cleaner and faster anyway, so I gave up on that and instead tried this:
Update mnt.workorders_copy
Set comappstat = (select distinct)
a.comappstat
mnt.workorders a, mnt.workorders_copy b
where a.workordersoi = b.workordersoi
and a.comappstat! = b.comappstat)
where a.comappstat! = b.comappstat
and a.workordersoi = b.workordersoi
The subquery executed on its own returns a single value 9, which is the correct value of the column in the table of the prod, and I want to replace the incorrect a '12' (I've updated the copy to change the value of the column comappstat to 12 everywhere where it was 9) However when I run the query again I get this error :
ERROR on line 8:
ORA-00904: "B". "" WORKORDERSOI ": invalid identifier
First of all, I don't see why the update statement does not work (it's probably obvious, but I'm not)
Secondly, it is the best approach for updating a column (or columns) that are incorrect, with the columns in the same table which are correct, or is there a better way?
I would sooner update the table rather than delete or truncate then re insert, as it was a trigger for insert/update I had to disable it on the notice re and truncate the table unusable a demand so I was re insert.
Thank youHello
First of all, after post 79, you need to know how to format your code.
Your last request reads as follows:
UPDATE mnt.workorders_copy SET comappstat = ( SELECT DISTINCT a.comappstat FROM mnt.workorders a , mnt.workorders_copy b WHERE a.workordersoi = b.workordersoi AND a.comappstat != b.comappstat ) WHERE a.comappstat != b.comappstat AND a.workordersoi = b.workordersoi
This will not work for several reasons:
The sub query allows you to define a and b and outside the breakets you can't refer to a or b.
There is no link between the mnt.workorders_copy and the the update and the request of void.If you do this you should have something like this:
UPDATE mnt.workorders A -- THIS IS THE TABLE YOU WANT TO UPDATE SET A.comappstat = ( SELECT B.comappstat FROM mnt.workorders_copy B -- THIS IS THE TABLE WITH THE CORRECT (OLD) VALUES WHERE a.workordersoi = b.workordersoi -- THIS MUST BE THE KEY AND a.comappstat != b.comappstat ) WHERE EXISTS ( SELECT B.comappstat FROM mnt.workorders_copy B WHERE a.workordersoi = b.workordersoi -- THIS MUST BE THE KEY AND a.comappstat != b.comappstat )
Speed is not so good that you run the query to sub for each row in mnt.workorders
Note it is condition in where. You need other wise, you will update the unchanged to null values.I wouold do it like this:
UPDATE ( SELECT A.workordersoi ,A.comappstat ,B.comappstat comappstat_OLD FROM mnt.workorders A -- THIS IS THE TABLE YOU WANT TO UPDATE ,mnt.workorders_copy B -- THIS IS THE TABLE WITH THE CORRECT (OLD) VALUES WHERE a.workordersoi = b.workordersoi -- THIS MUST BE THE KEY AND a.comappstat != b.comappstat ) C SET C.comappstat = comappstat_OLD ;
This way you can test the subquery first and know exectly what will be updated.
This was not a sub query that is executed for each line preformance should be better.Kind regards
Peter
-
Defeated by tri-objet in the hash Table
Hi guys, I need someone who is smarter than me to help please, suck for 3 days now.
The Script below uses a CSV file as a database to pull total VMs in my vcenter in a bar chart, showing the trend upward. . My boss wants it as soon as possible.
I can not however the $HT variable to sort by date (sorting and tri-objet doesn't seem to work, sort of NAME or WEEK)
Need help please, I'm stumped.
Note, tips cut off when I pasted it, like}'s and impossible.
# Created by ELMO
Add-pssnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
$Date = Get-Date -Format yyyy/MM/dd
$VCRUN = ' Ma Blanked to vCenter '
$Report = @()
$USER = "Ma Blanked user"
$PWD = "Ma Blanked on pwd"
Write-Host ' Connection to $VCRUN"" "".
VIserver disconnect -Confirm:$false
Se connect-VIServer -Server $VCRUN -User $USER -Password $PWD -wa 0
$VMsON = Get-VM | Where-Object {$_. PowerState -eq "PoweredOn"}
$VMsTotal = $VMsON. County
$Row = "" | Select Week, VMsTotal
$Row . Week = $Date
$Row . VMsTotal = $VMsTotal
$Report += $Row
$ReportView = $Report | Export-Csv -Path C:\PS\Output\VMTrendDB.csv -Append -NoTypeInformation #-Append the data at the bottom of the existing file
$MyData = Import-Csv C:\PS\Output\VMTrendDB.csv | Select-Object week ,VMsTotal
$HT = @{}
foreach ($Data in $MyData) {
$HT. Add($Data. Week , $Data . VMsTotal)
}
$HT = $HT | Tri # read on the Technet site as tri-objet does not change the actual table, but only the output. Thus uses only sort. $HT = HT Triedd | Sort = Name object AND object week type, they do not change my picture on the order of dates
Function Créer-Chart() {
Param(
[String] $ChartType ,
[String]$ChartTitle,
[String] $FileName ,
[,String]$XAxisName,
[String] $YAxisName ,
[Int]$ChartWidth,
[Int]$ChartHeight,
[HashTable]$DataHashTable
[Sub] [Reflection.Assembly]:LoadWithPartialName ("System.Windows.Forms"( )
[Sub] [Reflection.Assembly]:LoadWithPartialName ('System.Windows.Forms.DataVisualization'( )
#Create our graphic object
$Chart = new-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart. Width = $ChartWidth
$Chart. Height = $ChartHeight
$Chart. Left = 10
$Chart. Top = 10
#Create a chartarea to profit and add this to the table
$ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$Chart. ChartAreas . Add ($ChartArea)
[void]$Chart. Series . Add("Data")
$Chart. ChartAreas [0]. AxisX . Interval of = '1' #Set to 1 (default is auto) and allows all the values of the X axis appears correctly
$Chart. ChartAreas [0]. AxisX . IsLabelAutoFit = $false;
$Chart. ChartAreas [0]. AxisX . LabelStyle . Angle = "-45"
#Add real data to our table
$Chart. Series ["Data"]. Points . DataBindXY ($DataHashTable. ) Key , $DataHashTable. Values)
if (($ChartType -eq "Pie") -or ($ChartType -eq "pie")) {
$ChartArea. AxisX . Title = $XAxisName
$ChartArea. AxisY . Title = $YAxisName
$Chart. Series ["Data"]. ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]:Pie
$Chart. Series ['Data'] ['PieLabelStyle'] = "Outside"
$Chart. Series [« Data »] [« PieLineColor »] = "Black"
$Chart. Series ['Data'] ['PieDrawingStyle'] = "Concave"
($Chart. Series ["Data"]. Points . FindMaxByValue()) ["Exploded"] = $true
$Chart. Series ["Data"]. Label = ' #VALX = #VALY\n ' # make a X & Y Label of the data in the (useful for Pie chart) plot area (display the axis labels, use: Y = # ControlChars.LF = #VALX)
elseif (($ChartType -eq "Bar") -or ($ChartType -eq "bar")) {
#$Chart.Series ["Data"]. Sort ([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]: descendant, "Y")
$ChartArea. AxisX . Title = $XAxisName
$ChartArea. AxisY . Title = $YAxisName
# Find point with max/min values and change color
$maxValuePoint = $Chart. Series ["Data"]. Points . FindMaxByValue()
$maxValuePoint. Color = [System.Drawing.Color]:Red
$minValuePoint = $Chart. Series ["Data"]. Points . FindMinByValue()
$minValuePoint. Color = [System.Drawing.Color]:Green
# make the bars in the 3d cylinders
$Chart. Series [« Data »] [« DrawingStyle »] = "Cylinder"
$Chart. Series ["Data"]. Label = '#VALY' # Label Y to the data in the plot (useful for the diagram bar) area
else {
Write-Host "no Chart Type has been defined. Try again and enter Pie or Bar for the ChartType parameter. The table will be created in the form of standard bar graphic chart for now. " -ForegroundColor Cyan
#Set the title of the chart for the date and time
$Title = new System.Windows.Forms.DataVisualization.Charting.Title
$Chart. Titles . Add($Title)
$Chart. Titles [0]. Text = $ChartTitle
Graphic to a file #Save
$FullPath = ($FileName + ".png")
$Chart. SaveImage ($FullPath 'png'( )
Write-Host ' saved chart in $FullPath"" " -ForegroundColor Green .
back $FullPath
Create Chart -ChartType bar ChartTitle - "machines virtual VMware in DC1" -FileName C:\inetpub\ELMO\Graphic\VMsTrendChart -XAxisName 'Date' -YAxisName 'number of VMs' -ChartWidth 800 -ChartHeight 800 -DataHashTable $HT
All by setting the variable $HT, you define it as a Table of hash, sort or Sort-Object does not work on hash Tables, they work on arrays. Your definition is
$HT = @ {}
Use $HT = @)
Instead, which will create a table and you would be able to define objects and then use the Sort-Object there. With Hash Tables, since they hold any objects you can not sort using Sort-Object.
-
How can I publish the data to the hash table using regulator netui?
Could someone help me on how to display the data of the hash to netui in the controller.
There are altogether 18 survey questions (each question will have a list of surveyquestionanwer)
but I see only 14 issues of the investigation during the validation in the controller and also I see all the answers of the survey instead of the one that is selected on the jsp.
Here is my sample code.
Appreciate your help.setQuestionSurveyAnswers(Set<Entry<String, Collection<SurveyQuestionAnswer>>> surveyAnswers) Map<String, Collection<SurveyAnswer>> surveyQuestionAnswerList = new HashMap<String, Collection<SurveyAnswer>>(); surveyQuestionAnswerList contains <questionId, List<SurveyQuestionAnswer>> --------------------------------------------------------------------------------------------------------------- <netui-data:repeater dataSource="pageFlow.surveyForm.surveyAnswers"> <netui-data:repeaterItem> <netui:span value="${container.item.key}" /> <netui:radioButtonGroup dataSource="container.item.key" orientation="horizontal"> // is anything wrong here? <netui-data:repeater dataSource="container.item.value"> <netui-data:repeaterItem> <netui:radioButtonOption value="${container.item.answerText}"> <netui:label value="${container.item.answerText}" /> </netui:radioButtonOption> </netui-data:repeaterItem> </netui-data:repeater> </netui:radioButtonGroup> </netui-data:repeaterItem> </netui-data:repeater> --------------------------------------------------------------------------------------------------------------- data structure: --------------------------------------------------------------------------------------------------------------- questionId answerId answerText surveyQuestionLabel --------------------------------------------------------------------------------------------------------------- 1 1 Yes Do you want to take the survey? <SurveyQuestionAnswer> 1 2 No Do you want to take the survey? <SurveyQuestionAnswer> 2 1 Beginner Your expertese Level? <SurveyQuestionAnswer> 2 2 Expert Your expertese Level? <SurveyQuestionAnswer>
Thank youHello
It won't work, you bind the data of the hashmaps key, which does not work (you have a vo as the key)
I believe that your structure should be something like[QuestionAnswer] where QuestionAnswer has the label of the Question as well as a map of string, the string (AnswerId v/s AnswerText) (this may be an implicit method that traverses all objects and creates a map of AnswerId, AnswerText) and a single field of selectedAnswer.
Your outer loop will make a loop on QuestionAnswer and print the label of the Question and the inner loop will be the RadioButtonGroup, the data source must be the field of selectedAnswer (because you want to fill only) and the optionsDataSource is the AnswerId card, AnswerText
concerning
Deepak -
HashMap.hashCode () for the hash table with keys matching their values
Hello
I found something strange with Hashmaps:
in the following code:
HashMap < integer, whole > m1 = new HashMap < integer, whole > ();
HashMap < integer, whole > m2 = new HashMap < integer, whole > ();
M1.put (1,1);
M1.put (2.2);
M2.put (2.2);
M2.put (1,1);
M2.put (5.5);
System.out.println (M1. Equals (m2));
System.out.println (M1.hashCode ());
System.out.println (m2.hashCode ());
The result is:
0
0
fake
It seems that when a HashMap receives if key-value pairs the key = its hashCode value becomes 0!
I'm sure that I did not just fall on a bug in Collections so could someone please explain to me why this happens?
PS: If you're wondering why the hell would someone do such a Hashmap, I found it useful in the following situations:
class MyCount {}
int count;
The name of the string;
int age;
MyCount (String name, int age) {}
myIdName = name;
This.Age = age;
Count = 0;
}
void add (int c) {}
Count += c;
}
public int hashCode() {}
return 31 * age + name.hashCode ();
}
}
Class MyCountClusterer {}
Collection < MyCount > cluster (counts MyCount []) {}
< MyCount, MyCount > HashMap countMap = new HashMap < MyCount, MyCount > ();
for (MyCount c: account) {}
MyCount CHP = countMap.get (c);
If (mapC == null) {}
CHP = new MyCount (c.name, c.age);
countMap.put (c, c);
}
mapC.add (c.count);
}
Return countMap.values ();
}
}It is an unfortunate result of the way in which HashEntry.hashCode () is defined.
In your case I remove the class MyCount count and change the value to an AtomicInteger.
-
It's the stumping me. I add a key and a value in a hash table, pass in the key and retrieve the value. Basic enough, but when I go to retrieve the value a second time (after the restart of the application), it returns null.
If it isn't exactly the code that would be the basic scheme:
class A { private static Hashtable table = new Hashtable(); public static Object getObject(Class clazz) } return A.table.get(clazz); } public static void setObject(Class clazz, Object obj) } A.table.put(clazz, obj); } //Code stuff... } class B { public static void main(String[] args) { A.setObject(C.class, new C()); Object obj = A.getObject(C.class); //This works } //Code stuff... } class C { //Code stuff... }
What happens on the 9550 Simulator and is fixed after restarting the Simulator but work always and only the first time through. If the app is closed, then reopened, then it returns null, even if the hash table was always the same items.
Ah. When you run the application a second time, he rebuilt serializers to persistent store. Unfortunately, your objects of the class are new instances, so that they cannot be used as persistent hash keys. I suggest you use class names as keys rather than objects of class themselves.
-
Removal of the strings in a hash table
Hello to all PowerCLI'ers out there. This is what, I hope, will be an easy one for you guys.
I built a hash named $hostInfo table that contains information about our VMHosts. According to the information when displayed in a table format Name, UsedMemoryGB, TotalMemoryGB, FreeMemoryPct.
The release of "Format-Table" looks like this:
Name UsedMemoryGB TotalMemoryGB FreeMemoryPct
--------- ----------------------- ------------------------ -----------------------
us1esx0201.company.local 89.07421875 95.989414215087890625 92.79587700202785441462201182
us1esx0209.company.local 84.8193359375 95.989414215087890625 88.36321862267168020854706439
us1esx0211.company.local 83.681640625 95.989414215087890625 87.17798864517570982753322143
us1esx0205.company.local 83.3310546875 95.989414215087890625 86.81275468644519191613067240
us1esx0403.company.local 96.3408203125 111.989383697509765625 86.02674390344222204017427325
us1esx0401.company.local 95.689453125 111.989383697509765625 85.44511092539192491691602221
US1-vmhesx - p0515.company.local 81.6171875 95.989383697509765625 85.02730651672824441211219264
us1esx0303.company.local 95.1884765625 111.989383697509765625 84.99776802023479984310570319
US1-vmhesx - p0512.company.local 81.4462890625 95.9893798828125 84.84927099428367955541142883
us1esx0113.company.local 81.3212890625 95.98944091796875 84.71899438605549341860543489Here is the code snippet that generates the hash table:
$hostInfo = get-VMHost |
Select name "
@{N = "UsedMemoryGB"; E={$_. MemoryUsageGB}} '
@{N = "TotalMemoryGB"; E={$_. MemoryTotalGB}} '
@{N = "FreeMemoryPct"; E={(($_. MemoryUsageGB / $_. {{(MemoryTotalGB) * 100)}} |
Sort-Object-descending - property 'FreeMemoryPct ' | Select - 10 first
Here is my challenge... I want to remove the '. '. company.local"of all entries in the"Name"column and only let the real host name. How would I go about iterate the key 'Name' and deleting only this part of the chain?
Any help is appreciated as always!
-jSun311
You can create the table in the right format with just the name of the host if you change the second line of your script in:
Select @{N = "Name"; E={$_. Name.Split('.') [0]}},
If you want to change the variable $hostinfo, then you can use:
$NewHostinfo = $hostinfo | Select-Object - property @{N = "Name"; E={$_. Name.Split('.') [0]}}, UsedMemoryGB, TotalMemoryGB, FreeMemoryPct
-
HI guys,.
I have a script that takes a list of VM and collects various pieces of information on the
- Name, host name, CPU Num, Num disks, IP info, etc...
The script works fine, but I still need to load the data into Excel and manipulate manually until the data can be used with other scripts. I wonder if there is a way to eliminate this manual work?
Specifically, for each computer virtual, the script determines the number of hard drives and returns the following for each disk
- HDDx name
- HDDx data store
- Path of HDDx (file and hard in the data store name)
I can be left with dozens of lines for all virtual machines in the hash table, and each virtual computer might have multiple entries for each of the 3 items above.
E.g. HDD1, HDD2, HDD3 Datastore, DataStore DataStore...
What I want to do is take all the 'HDDx DataStore' entries in the hash table and return only the unique entries so that I can then turned off and get specific on these specific data stores information, number of virtual machines, the names of the machines virtual etc...
I tried to use wildcards, which of the statements, etc... I can't make it work.
Fill script I use is attached.
This is the closest that I just get this work but, it is still not add all the information from the data store in the hash table second $dsReport
In the attached script, I have highlighted the lines of $dsReport
$report = @)
$dsReport = @)
...
...
$hdd = 1
$Computer | Get-hard drive | {foreach}
Name of $GeneralProp.Add ("HDD$ ($hdd) ', $_.") Name)
$GeneralProp.Add ("HDD$ ($hdd) data store", $_. ") FileName.split("") [0]. TrimStart("["). TrimEnd("]"))
$GeneralProp.Add ("HDD$ ($hdd) path', $_.") FileName.split("") [1]. TrimStart("["). TrimEnd("]"))
Capacity of $GeneralProp.Add ("HDD$ ($hdd) ', $_.") CapacityGb)
$dsProp=@{Name = $_. FileName.split("") [0]. TrimStart("["). TrimEnd("]")}
$hdd ++
}...
...
$dsReport | SELECT name - Unique
Any help is appreciated
Thank you
Something like that?
Get - vm | {foreach}
$disks = @)
$_ | Get-hard drive | {foreach}
$dsname = $_. Filename.Split("") [0]. TrimStart("["). TrimEnd("]")
$disks += $_. Add-Member - MemberType NoteProperty - name DatastoreName - $dsname - PassThru of value
}
$disks | Group-object - property DatastoreName
}
-
Hello
I'm trying to sort a hastable that contains the key and values.
The keys are New york, los angles, Texas, port Aerizona
And values are 60.123, 34.3434, 56.4544, 67.565, 56.7878
Now, I want to sort the hash table based on the values which is lesser in value.
I tried comparer class using vector simplesorting, but I can only adjust the values but the keys remains unchanged in its position.
Please help me how to sort hastable with keys and values
I want the output of this title
34,3434 losangles
Texas 56.4544
port 56.7878
nwyork 60.123
aerizona 67.565
Thanks in advance
I suggest that you check out all the hastable keys and add to a SimpleSortingVector. You can them iterate thought the sorted keys, by using the keys to retrieve objects from the hash table.
-
Hi I have the following script which should provide an array with the names of vm and the datastorecluster they are on: -.
$hashT = @ {}
$vmlist = import-Csv "C:\vmMove\vm3.csv".
foreach ($vm to $vmlist)
{
$vmname = get - vm $vm.name
$dscname = get-datastorecluster - vm $vm.name
$hashT = @ {}
VMNAME = $vmname
DSCLUSTER = $dscname
}
}
$props = New-Object psobject-property $hashT
$props | FT - AutoSize
There are four hosts listed in the csv file, but when I run this table only wrote a line for the last host does not include the first three hosts. What I am doing wrong? Why can't that get the hash table to view details for all hosts contained in csv.
I have spent the better part of a day on this and just can't see where I'm wrong - thank you
If you want just a table with these objects in there, you could do
$hashT = @)
$vmlist = import-Csv "C:\vmMove\vm3.csv".
foreach ($vm to $vmlist)
{
$vmname = get - vm $vm.name
$dscname = get-datastorecluster - vm $vm.name
$hashT += new-Object PSObject - property @ {}
VMName = $vm. Name
DscCluster = $dscname
}
}
$hashT
-
Selection of one-dimensional Array objects in a hash table
Suppose I have a hash table with a list of names of virtual machine. I also have a variable array containing objects of virtual machine and all of their properties. I want to scroll the array variable and delete all virtual machine names that do not exist in the hash table. How do I would accomplish this?
Thank you
If your table is called $inArray and your hash table is called $hashTab, you could do something like that
$outArray = $inArray | %{
If ($hashTab.ContainsKey ($_.)) VMName)) {}
$_
}
}
The selected objects will be $outArray table.
-
Asynchronous tasks, hash tables, and berries - best way to do this!
I'm working with a colleague on a script that will deploy a very large number of virtual machines to a CSV file. We started with a purely synchronous process that was very slow by using a simple foreach loop to deploy a virtual machine, configure, a technique of customization and start all this according to the CSV data.
The obvious bottleneck in the process is waiting for the clone operation is completed before you perform the remaining tasks. The synchronous line of New - VM in a foreach loop, it is very slow.
We have since changed to deploy an asynchronous virtual machine using the foreach loop according to the CSV data in a table. Once the foreach loop started all clonings, he finishes and then a monitoring task loop 'while' kickoff and then perform the rest tasks. The while loop is based on code from the LucD found here: http://www.lucd.info/2010/02/21/about-async-tasks-the-get-task-cmdlet-and-a-hash-table/ (thanks Luke!).
Now code Luke used a hash table, so it had to be modified to use the CSV table at best. Table CSV contained information to perform the configuration and customization of the virtual machine. I couldn't really find a way for this very cleanly, I'm looking for suggestions on making it a little better.
Right now I use a simple counting mechanism to browse table to determine if the cloning operation is complete or not. The problem with this is that if there are 100 VM being cloned, and I walk through the table one row at a time so he could take a long time between the success of the clone operation and monitoring loop actually pick up on it. It would be nice to have a way to identify which line in the table has data customization and configuration required without walking through it in a loop, rather referring to an item in the table (TaskID) using another method (is this one?-still find such things powershell).
Here is the modified version of the code of Luke:
# $csv is the array in question with the required data. # Used to count which line in the array $csvline = 0 # Count all the running tasks to feed into the while loop $tasks = $csv | %{$_.TaskID} | ?{$_ -match "Task"} $runningTasks = $tasks | measure | %{$_.count} while($runningTasks -gt 0){ # Completion Meter $percomplete = (1 / $runningTasks)*100 Write-Progress -activity 'Waiting for cloning operation to complete' -status 'Please wait...' -percentComplete ($percomplete) # Here is where it starts to get messy, there has to be a better way than using $csv[$csvline] and walking though if ((get-task | select id,state | ?{$_.id -eq $csv[$csvline].TaskId}).state -eq "Success"){ Set-VM $csv[$csvline].name -NumCpu $csv[$csvline].vcpu -MemoryMB $csv[$csvline].MemoryMB -Description $csv[$csvline].Notes -Confirm:$false Get-vm -name $csv[$csvline].name | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $csv[$csvline].Network -StartConnected:$true -Confirm:$false Get-VM $csv[$csvline].name | Start-VM -RunAsync -Confirm:$false $csv[$csvline].TaskId = "" $runningTasks-- } elseif ((get-task | select id,state | ?{$_.id -eq $csv[$csvline].TaskId}).state -eq "Error"){ $csv[$csvline].TaskId = "" $runningTasks-- } # Increment $csvline $csvline++ # Wash rinse repeat over and over (not very pretty) # Reset $CSV array line counter when greater than count of lines (minus 1 because the array/count starts at zero). if ($csvline -gt ($csv.count - 1)){ $csvline = 0 } # Slow down the runningTasks loop since we are waiting for cloning operations to complete. # IMPACT: If you deploy 100 VM's it could take up to 200 seconds AFTER a VM is finished cloning before being noticed by the while loop Start-Sleep -Seconds 2 }
It would be nice to create a Get-task monitoring loop who does not walk in the table. But shoot any 'Sucess' ful tasknames and determine which line in the table of $csv it is (using the TaskId element).
Is it possible to do another nesting a foreach ($line in $csv) inside the Get task monitoring loop and compare the TaskId values? (It's perhaps faster without worrying - have not yet tested).
I hope that I have explained things clearly enough.
Thanks for your time.
Andy
Andy, have a look at the thread called error with Get-OsCutomizationNicMapping, he does something similar to what you want to do I guess.
Inside the loop of Import-Csv, the new virtual machine is created in Async and the Id of the task as well as some specific values of the CSV stored in the part of the value of the hash table.
Later, these values are used to configure the new virtual machine further.
Maybe you are looking for
-
Google maps report problem fails: sending automated messages
When I submit a problem report, I get: "we're sorry: your computer or your network sends automated... answers. "It works well with IE and Opera but not Firefox. URL of affected sites http://maps.Google.com/
-
Update problem bios satellite A210-199
When I try to update bios for (Q 28158310)I get the error I can do maybe I can try another tool?
-
Create a diagonal matrix whose elements are determined by a control
Hello How can I create a diagonal matrix whose diagonal elements are determined by a control? As [lamda lamda 0; 0] Thanks in advance. Chuan
-
&#60; Fn &#62; keys stopped working after XP updates
I have XP Home Edition sp3. I was invited for 6 updates for XP. After installation and restarting in now my keys on laptop are not working. None of them work. Other combinations of keys are OK. + C, etc are OK. Is there a way to remove the updates th
-
When I try to reset my pass., microsoft wonder mail recovery; I type correctly, but the automatic writing is @hotmail.iit with 2 i, you will understand everything in the image: http://imageshack.com/a/img538/7405/zNYQjR.png