I've used stackoverflow for years, but today is the first time I've felt the need to ask a question. I would like to know if the following code could be made more efficient, this is because I'm writing multiple copies of the script, entering into different SQL tables.
What it does:
- Querys VMware, outputs to $Data
- Truncates SQL table
- Inserts $Data into dbo.T_VM_GUEST_DETAILS
- Inserts everything from dbo.T_VM_GUEST_DETAILS into dbo.T_VM_GUEST_DETAILS_HISTORY
Ideas for efficiency:
Just above ForEach ($Line in $Data), is it possible to include something like "foreach column in $data" which would then dynamically build a 'standard' SQL INSERT query, based on the count of columns, their names & values.
Or is there an easier way to insert $Data into a SQL table elsewhere and I'm making it extra difficult for myself? I am keeping my SQL table column names to the same as the Powershell Output which should help?
The following block fills $Data with a list of VMs (PowerCLI):
$Data = @()
$AllVMs = Get-VM | SELECT *
$Entry = @()
Foreach ($VM in $AllVMs) {
$Entry = "" | Select Name,PowerState,Version,Notes,NumCpu,MemoryGB,VMHost,UsedspaceGB,ProvisionedSpaceGB,GuestId
$Entry.Name = $VM.Name
$Entry.PowerState = $VM.PowerState
$Entry.Version = $VM.Version
$Entry.Notes = $VM.Notes
$Entry.NumCpu = $VM.NumCpu
$Entry.MemoryGB = $VM.MemoryGB
$Entry.VMHost = $VM.VMHost
$Entry.UsedspaceGB = $VM.UsedspaceGB
$Entry.ProvisionedSpaceGB = $VM.ProvisionedSpaceGB
$Entry.GuestId = $VM.GuestId
$Data += $Entry
}
This then populates $SQL with many SQL commands (could be hundreds or thousands of lines):
$SQL = $NULL
$SQL = $SQL + "
TRUNCATE TABLE dbo.T_VM_GUEST_DETAILS
"
ForEach ($Line in $Data) {
$Name = $NULL
$PowerState = $NULL
$Version = $NULL
$Notes = $NULL
$NumCpu = $NULL
$MemoryGB = $NULL
$VMHost = $NULL
$UsedspaceGB = $NULL
$ProvisionedSpaceGB = $NULL
$GuestId = $NULL
$Name = $Line.Name.tostring()
$PowerState = $Line.PowerState.tostring()
$Version = $Line.Version.tostring()
$Notes = $Line.Notes.tostring()
$NumCpu = $Line.NumCpu.tostring()
$MemoryGB = $Line.MemoryGB.tostring()
$VMHost = $Line.VMHost.tostring()
$UsedspaceGB = $Line.UsedspaceGB.tostring()
$ProvisionedSpaceGB = $Line.ProvisionedSpaceGB.tostring()
$GuestId = $Line.GuestId.tostring()
$SQL = $SQL + "
INSERT INTO dbo.T_VM_GUEST_DETAILS (
Name,PowerState,Version,Notes,NumCPU,MemoryGB,VMHost,UsedspaceGB,ProvisionedSpaceGB,GuestId,DATE_TIME
)
VALUES (
'$Name','$PowerState','$Version','$Notes','$NumCPU','$MemoryGB','$VMHost','$UsedspaceGB','$ProvisionedSpaceGB','$GuestId',GETDATE()
)
"
}
$SQL = $SQL + "
INSERT INTO dbo.T_VM_GUEST_DETAILS_HISTORY (
Name,PowerState,Version,Notes,NumCPU,MemoryGB,VMHost,UsedspaceGB,ProvisionedSpaceGB,GuestId,DATE_TIME
)
SELECT Name,PowerState,Version,Notes,NumCPU,MemoryGB,VMHost,UsedspaceGB,ProvisionedSpaceGB,GuestId,DATE_TIME FROM dbo.T_VM_GUEST_DETAILS
"