clone vm change network identity - powershell

I'm trying to script (powershell/powercli) the cloning of our QA environment (261 servers).
Basically I want to make a new copy of each server just changing the VM name, the hostname, and the IP address. Ideally I'd want the new clone on the domain (90% of them are Windows OS). And many of my servers have many large hard drives that won't all fit on one datastore so I have to be able to clone to multiple datastores.
I started off with New-VM for the servers that were small enough to fit on one datastore, but OSCustomization only works about 30% of the time. The rest of the time I have to login to Windows and manually remove from the domain to rename the hostname. Most of the time Set-OSCustomizationNicMapping works But specifying -Domain -DomainUsername/Password never works (at best it renames the server and puts in the "domain-name" workgroup but it never joins it to the domain).
To workaround the multidatastore issue I discovered $vm.ExtensionData.CloneVM using VMWare.Vim.VirtualMachineRelocateSpec to specify which hard drives go to which datastores and that works great, but I don't know how to customize the hostname or NIC settings.
So the basic requirements are: clone to multiple datastores changing hostname and IP settings. Does anyone have any recommendations or solutions?
Here's some of my code snippets:
Setting up the OSCustomizationSpec for New-VM
$spec = New-OSCustomizationSpec -Name "PowerCLI Scripting for $NewHostName" -Spec "PowerCLI Scripting" -WhatIf:$False
Set-OSCustomizationSpec $spec -Workgroup "WORKGROUP" -DomainUsername "qajoin#qa.company.com" -DomainPassword (Get-Password -Username "qa\qajoin") -ProductKey $ProductKey -AdminPassword (Get-Password $Script:LuserName) | Out-Null
Get-OSCustomizationSpec "PowerCLI Scripting for $NewHostName" `
| Get-OSCustomizationNicMapping `
| Set-OSCustomizationNicMapping `
-IPMode:UseStaticIP `
-IPAddress $NewIPAddress `
-SubnetMask "255.255.248.0" `
-DNS "10.26.40.115","10.26.40.116" `
-DefaultGateway $NewDFGW | Out-Null
The New-VM command:
$VM = New-VM -VMHost $VMHost -VM $Hostname -Name $NewHostName -Description "$Description" -OSCustomizationSpec "PowerCLI Scripting for $NewHostName" -Location (Get-Folder -Id $Location) -Datastore $MostFreeSpace -ErrorAction Stop
Here's the multi-datastore clone:
$VMXtargetDatastore = Get-Datastore ($MapInfo | Where-Object {$_.Name -eq "Hard disk 1"}).NewDataStore
#Create an empty CloneSpec
$spec = New-Object VMware.Vim.VirtualMachineCloneSpec
$spec.Template = $false
$spec.PowerOn = $false
#Create a RelocateSpec (datastore is target for .vmx)
$spec.Location = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.Location.Datastore = $targetDatastore.ExtensionData.MoRef
#For each disk in the current vm
# create a new DiskLocator spec
# populate the datastore and diskid from the current harddisk
# add the spec to RelocateSpec from above
Get-HardDisk -VM $Origvm | %{
$disk = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator
$disk.diskId = $_.ExtensionData.Key #2001,2002,2003,...
$DiskLabel = $_.ExtensionData.DeviceInfo.Label
#$disk.datastore = $_.ExtensionData.Backing.Datastore #type=datastore value=datastore-2790
$dsname = ($MapInfo | Where-Object {$_.Name -eq $DiskLabel}).NewDataStore
$ds = Get-Datastore -Name $dsname
$disk.datastore = $ds.id
$spec.Location.Disk += $disk
}
$CustSpec = New-Object VMware.Vim.CustomizationSpec
$origvm.ExtensionData.CloneVM((Get-Folder -Id $folder).ExtensionData.MoRef, $targetName, $spec)
I'm guessing the next step using the ExtensionData.CloneVM method is to declare a new object of CustomizationIdentitySettings but the documentation (http://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IdentitySettings.html) that I could find isn't really helpful (probably because the settings vary by OS?) and then add that object to my $spec object.
Same would go for OSCustomizationNicMapping (http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/OSCustomizationNicMapping.html) but I can't suss enough information out of the pubs to figure out how to build my $spec object.

Can't you copy to an isolated environment? Just build a set of extra (isolated) VLANs and copy all VMs, keep IP/Names, only switch the VLAN at the VM level.

I finally found this page: http://www.vmdev.info/?p=202
I started with the example they show and it worked, so I kept adding in CloneSpec fields until I got what I wanted:
$nicMaparray = #()
$FirstNic = New-Object VMware.Vim.CustomizationAdapterMapping
$FirstNic.adapter = New-Object VMware.Vim.CustomizationIPSettings
$FirstNic.adapter.dnsDomain = $domain
$FirstNic.adapter.dnsServerList = "10.26.40.115","10.26.40.116"
$FirstNic.adapter.gateway = $DefGW
$FirstNic.adapter.ip = New-Object Vmware.Vim.CustomizationFixedIp
$FirstNic.adapter.ip.IpAddress = $NewIP
$FirstNic.adapter.subnetMask = "255.255.248.0"
$nicMaparray += $FirstNic
$folderobj = $origvm.parent
$vm = Get-VM $sourceName | Get-View
$cloneName = $targetName
$cloneFolder = Convert-PathToFolderObject -FolderPath $folderpath
$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
$cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec
$cloneSpec.Location.Host = (Random(Get-VMHost | Where {$_.Name -like "*esxiqa*"}) | get-view).MoRef
$targetDatastore = ($MapInfo | Where-Object {$_.Name -eq "Hard disk 1"}).NewDataStore
$cloneSpec.Location.Datastore = (Get-Datastore $targetDatastore | get-view).MoRef
$cloneSpec.customization = New-Object VMware.Vim.CustomizationSpec
$cloneSpec.customization.globalIPSettings = New-Object VMware.Vim.CustomizationGlobalIPSettings
$cloneSpec.customization.globalIPSettings.dnsServerList = "10.26.40.115","10.26.40.116"
$cloneSpec.customization.identity = New-Object VMware.Vim.CustomizationSysprep
# $spec.customization.identity.guiRunOnce = New-Object VMware.Vim.CustomizationGuiRunOnce
$cloneSpec.customization.identity.guiUnattended = New-Object VMware.Vim.CustomizationGuiUnattended
$cloneSpec.customization.identity.guiUnattended.autoLogonCount = 0
$cloneSpec.customization.identity.guiUnattended.password = New-Object VMware.Vim.CustomizationPassword
$cloneSpec.customization.identity.guiUnattended.password.plainText = $true
$cloneSpec.customization.identity.guiUnattended.password.value = Get-Password -Username "Administrator"
$cloneSpec.customization.identity.identification = New-Object VMware.Vim.CustomizationIdentification
$cloneSpec.customization.identity.identification.joinWorkgroup = "WORKGROUP"
# $spec.customization.identity.licenseFilePrintData = $null
$cloneSpec.customization.identity.userData = New-Object VMware.Vim.CustomizationUserData
$cloneSpec.customization.identity.userData.computerName = New-Object VMware.Vim.CustomizationFixedName
$cloneSpec.customization.identity.userData.computerName.name = $cloneName
$cloneSpec.customization.identity.userData.productID = $ProductKey
$cloneSpec.customization.nicSettingMap = $nicMaparray
#nicMaparray build above
# $cloneSpec.customization.options = $null
$cloneSpec.powerOn = $true
Get-HardDisk -VM $sourceName | %{
$disk = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator
$disk.diskId = $_.ExtensionData.Key #2001,2002,2003,...
$DiskLabel = $_.ExtensionData.DeviceInfo.Label
$dsname = ($MapInfo | Where-Object {$_.Name -eq $DiskLabel}).NewDataStore
$ds = Get-Datastore -Name $dsname
$disk.datastore = $ds.id
$cloneSpec.Location.Disk += $disk
}
Write-Verbose "Cloning $sourceName"
try
{
$vm.CloneVM( $cloneFolder, $cloneName, $cloneSpec)
return $true
}
catch
{
$_.Exception
return $false
}

Related

List of all Windows VMs under all subscriptions under a single Tenant

I want to write a script (preferably PowerShell calling the Az cli modules) that lists of all Windows VMs (whether allocated or de-allocated), subscription, resource-group, vm-name, the os system, the OS version, latest patch information under all Azure subscriptions under a single Azure Tenant. Want this in table format.
There are a number of scripts on the internet but use the 'old' Az modules.
I need help in identifying the Az modules to use and fields to query.
My high level pseudo logic.
$tenant_id = xxxx-xxxx-xxxx-xxxx
$subscription_array = Get-All-Subcriptions -tenant $tenant_id
for(each $sub in $subscription_array)
{
$vm_array = Get-Windows-Vms -subscription $sub
for(each $vm in $vm_array)
{
$vm_name = $vm.name
$vm_os = $vm.os -- Windows-2019, Windows_server-2012 etc...
$vm_rg = $vm.resource_group
$vm_patch_version = $vm.latest_patch_no
$collection_of_vm_records.add($vm_name, $vm_os, $vm_rg, $vm_patch_version)
}
}
Write $collection_of_vm_records to csv file
This will give you both windows and linux vm's details.
$report = #()
$subs = Get-AzSubscription
Foreach ($sub in $subs)
{
select-AzSubscription $sub | Out-Null
$subName = $sub.Name
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select-Object VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, PrivateIpAddress, OsType, PublicIPAddress, Subscription, Cores, Memory, CreatedDate
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
[string]$sku = $vm.StorageProfile.ImageReference.Sku
[string]$os = $vm.StorageProfile.ImageReference.Offer
$osDiskName = $vm.StorageProfile.OsDisk.Name
$info.VMName = $vm.Name
$info.OsType = $os + " " + $sku
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$vmLocation = $vm.location
$info.VmSize = $vm.HardwareProfile.VmSize
$info.VirtualNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.Subscription = $subName
if ($vmLocation)
{
$sizeDetails = Get-AzVMSize -Location $vmLocation | Where-Object {$_.Name -eq $vm.HardwareProfile.VmSize}
}
$info.Cores = $sizeDetails.NumberOfCores
$info.Memory = $sizeDetails.MemoryInMB
$osDisk = Get-AzDisk -ResourceGroupName $vm.ResourceGroupName -DiskName $osDiskName
$info.CreatedDate = $osDisk.TimeCreated
$report+=$info
}
}
$csv = $report | Select-Object VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, PrivateIpAddress, OsType, PublicIPAddress, Subscription, Cores, Memory, CreatedDate
$csv | Export-Csv C:\temp\Inventory.csv -NoTypeInformation

Ping then DNS lookup before I purge an asset

So I am trying to Purge IPs from tool that we use. Before I can purge the assets we need to make sure the host is not pingable and not in DNS. I am new to PS and cant seem to wrap my head around on doing this. Any help is greatly appreciated. I have been doing this as a manual process by pinging the list of IPs and hostnames and doing a nslookup in cmd prompt before selecting the IPs that are needing to be removed. I have about 13k IPs left to do.
Update:
I want to implement this portion into it. Where In cell A it will have the IP
cell B will let me know if it is up or down. And Cell D will let me know if it is DNS aswell. Below is the script I got for pinging and checking if up or down and checking AD to see if the hostname is still in AD. I want it similar to this.. Please excuse my english
$path = ".\results.xls"
$objExcel = new-object -comobject excel.application
if (Test-Path $path)
{
$objWorkbook = $objExcel.WorkBooks.Open($path)
$objWorksheet = $objWorkbook.Worksheets.Item(1)
}
else {
$objWorkbook = $objExcel.Workbooks.Add()
$objWorksheet = $objWorkbook.Worksheets.Item(1)
}
$objExcel.Visible = $True
#########Add Header####
$objWorksheet.Cells.Item(1, 1) = "HostName"
$objWorksheet.Cells.Item(1, 2) = "Result"
$objWorksheet.Cells.Item(1, 3) = "MachineIP"
$objWorksheet.Cells.Item(1, 4) = "Active Directory"
$machines = Get-Content .\machinelist.txt
$row=2
$machines | foreach-object{
$ping = $null
$iname = $null
$machine = $_
$ping = Test-Connection $machine -Count 1 -ea silentlycontinue
$checkAD = try {$comp = Get-ADComputer -Identity $machine -ErrorAction
Stop
if ($comp){"Yes"}else{throw}
}
catch {"No"}
$objWorksheet.Cells.Item($row,4) = $checkAD
if($ping){
$objWorksheet.Cells.Item($row,1) = $machine
$objWorksheet.Cells.Item($row,2) = "UP"
$iname = $ping.IPV4Address.IPAddressToString
$objWorksheet.Cells.Item($row,3) = $iname
$row++}
else {
$objWorksheet.Cells.Item($row,1) = $machine
$objWorksheet.Cells.Item($row,2) = "DOWN"
$row++}
}
Here's a start, using Test-Connection and Resolve-DnsName, assuming you have a list of hosts' IP and name separated by a space, with a carriage return between each host:
$Assets = #"
127.0.0.1 localhost
255.255.255.255 fakehost
"#
$FailedPing = #()
$NoDNS = #()
$Assets -split "`r" | %{
$ipaddress = ($_.split(' ')[0]).trim()
$hostName = ($_.split(' ')[1]).trim()
Write-Host "IP: $ipaddress HOST: $hostName "
Try {
Test-Connection -ComputerName $ipaddress -Count 2 -ErrorAction Stop | Out-Null
}Catch {
$FailedPing += [pscustomobject]#{IP=$ipaddress; HostName = $hostName}
}
Try {
Resolve-DnsName -Name $hostName -ErrorAction Stop | Out-Null
}Catch {
$NoDNS += [pscustomobject]#{HostName = $hostName;Problem = $Error[0].Exception}
}
}
$FailedPing | ft
$NoDNS | ft

Counting Services on multiple servers

I'm still a beginner with powershell, but love to learn and research all the things it can do.
So with that, I am looking to create a script that will output to a datagridview table. I created a simple enough form that has a multi-line text box where you can enter in a list of servers and then just a simple "check" button that calls my function to actually query each server for their services and outputs that info into the datagridview below it.
That part was easy enough for me to create. My thing is, I want it to do the following":
query each server and pull the list of all services on that server
then in the datagridview, I want it to show the service name in column 1, and then the count of how many servers have that service in column 2
Hope this make since. Can't really provide any code as I don't know how to properly write it! I'm thinking there is someway to generate the full list, then do a loop and count type thing, but not sure.
I thank you for any assistance with this. Been googling and reading up like crazy. Either not correct search criteria or something just isn't clicking for me.
Update - Adding in current script I have:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$xForm = 800
$yForm = 800
$SVCForm = New-Object System.Windows.Forms.Form
$SVCForm.Text = "Automatic Services Query"
$SVCForm.Size = New-Object System.Drawing.Size($xForm,$yForm)
$SVCForm.FormBorderStyle = "FixedSingle"
$SVCForm.StartPosition = "CenterScreen"
$SVCForm.ControlBox = $true
$SVCForm.KeyPreview = $True
$SVCForm.ShowIcon = $false
$SVCForm.MinimizeBox = $True
$SVCForm.MaximizeBox = $false
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(365,720)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$x=$CancelButton.Text;$SVCForm.Close()})
$SVCForm.Controls.Add($CancelButton)
$ServerListGroup = New-Object System.Windows.Forms.GroupBox
$ServerListGroup.Location = New-Object System.Drawing.Size(5,10)
$ServerListGroup.size = New-Object System.Drawing.Size(780,300)
$ServerListGroup.text = "Enter list of servers you want to check:"
$SVCForm.Controls.Add($ServerListGroup)
$ServerList = New-object System.Windows.Forms.TextBox
$ServerList.Location = New-object System.Drawing.Size(5,25)
$ServerList.Size = New-Object System.Drawing.Size(280,270)
$ServerList.Multiline = $True
$ServerList.ScrollBars = "Vertical"
#$ServerList.add_TextChanged({ONValButton})
$ServerListGroup.Controls.Add($ServerList)
$SVCButton = New-Object System.Windows.Forms.Button
$SVCButton.Location = New-Object System.Drawing.Size(505,140)
$SVCButton.Size = New-Object System.Drawing.Size(180,22)
$SVCButton.Text = "SVC Check"
$SVCButton.Enabled = $True
$SVCButton.Add_Click({SvcCheckCount})
$ServerListGroup.Controls.Add($SVCButton)
$SvcListGroup = New-Object System.Windows.Forms.GroupBox
$SvcListGroup.Location = New-Object System.Drawing.Size(5,330)
$SvcListGroup.size = New-Object System.Drawing.Size(780,380)
$SvcListGroup.text = "Automatic Running/Not-Running Services are listed below:"
$SVCForm.Controls.Add($SvcListGroup)
#$SvcList = New-object System.Windows.Forms.TextBox
#$SvcList.Location = New-object System.Drawing.Size(5,25)
#$SvcList.Size = New-Object System.Drawing.Size(765,350)
#$SvcList.Multiline = $True
#$SvcList.ScrollBars = "Vertical"
#$SvcList.Readonly= $True
#$SvcListGroup.Controls.Add($SvcList)
$SvcGrid = New-Object System.Windows.Forms.DataGridView
$SvcGrid.Location = New-Object System.Drawing.Size(5,15)
$SvcGrid.Size = New-Object System.Drawing.Size(760,360)
$SvcGrid.ColumnHeadersBorderStyle = [System.Windows.Forms.DataGridViewHeaderBorderStyle]::Single
$SvcGrid.CellBorderStyle = [System.Windows.Forms.DataGridViewCellBorderStyle]::Single
$SvcGrid.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::DisableResizing
$SvcGrid.GridColor = [System.Drawing.Color]::Black
$SvcGrid.RowHeadersVisible = $false
$SvcGrid.AllowUserToAddRows = $false
$SvcGrid.AllowUserToResizeColumns = $False
$SvcGrid.AllowUserToResizeRows = $false
$SvcGrid.ColumnHeadersHeight = 23
$SvcGrid.SelectionMode = [System.Windows.Forms.DataGridViewSelectionMode]::FullRowSelect
$Scroll = New-Object System.Windows.Forms.VScrollBar
$Scroll.Dock = [System.Windows.Forms.DockStyle]::Right
$Scroll.width = 18
$Scroll.isAccessible = $false
$SvcGrid.Controls.Add($Scroll)
$SvcGrid.Columns.Add("Name","Service Name") > $null
$SvcGrid.Columns["Name"].Width = 200
$SvcGrid.Columns["Name"].HeaderCell.Style.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft
$SvcGrid.Columns["Name"].DefaultCellStyle.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft
$SvcGrid.Columns["Name"].ReadOnly = $False
$SvcGrid.Columns.Add("StartMode", "Start Mode") > $null
$SvcGrid.Columns["StartMode"].Width = 180
$SvcGrid.Columns["StartMode"].HeaderCell.Style.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft
$SvcGrid.Columns["StartMode"].DefaultCellStyle.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft
$SvcGrid.Columns["StartMode"].ReadOnly = $False
$SvcGrid.Columns.Add("Running","Running") > $null
$SvcGrid.Columns["Running"].Width = 180
$SvcGrid.Columns["Running"].HeaderCell.Style.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
$SvcGrid.Columns["Running"].DefaultCellStyle.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
$SvcGrid.Columns["Running"].ReadOnly = $true
$SvcGrid.Columns.Add("NotRunng","Not Running")>$null
$SvcGrid.Columns["NotRunng"].Width = 180
$SvcGrid.Columns["NotRunng"].HeaderCell.Style.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
$SvcGrid.Columns["NotRunng"].DefaultCellStyle.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
$SvcGrid.Columns["NotRunng"].ReadOnly = $true
$SvcListGroup.Controls.Add($SvcGrid)
Function SvcCheckCount
{
$SvcGrid.Rows.Clear()
$Servername = $ServerList.Text.Split("`n")|%{$_.trim()}
foreach($Server in $Servername)
{
$Server = $Server.ToUpper()
$svctest = Get-WmiObject Win32_Service | Where-Object {$_.StartMode -eq 'Auto'} | Select-Object Name, Startmode, State
Foreach ($svc in $svctest)
{
$name = $svc.Name
$startmode = $svc.StartMode
$state = $svc.State
If($state-eq"Running"){$SvcGrid.Rows.add($name,$startmode,$state)}
If($state-eq"Stopped"){$SvcGrid.Rows.add($name,$startmode,$null,$state)}
}
}
}
$SVCForm.Topmost = $True
$SVCForm.Add_Shown({$SVCForm.Activate()})
[void] $SVCForm.ShowDialog()
Since you already have the GUI portion of this functioning I am going to focus us the grouping of the data you are looking for. Going into this the one thing I am fuzzy on is why you have the if statements are for but we can work on that if need be. The following is meant to be in place of your foreach loop
$services = #()
foreach($Server in $Servername){
$Server = $Server.ToUpper()
$services += Get-WmiObject Win32_Service -ComputerName $Server -Filter 'StartMode="Auto"' |
Select-Object Name, Startmode, State |
Add-Member -MemberType NoteProperty -Value $Server -Name "Server" -PassThru
}
$services | Group-Object Name | ForEach-Object{
$SvcGrid.Rows.add($_.Name,$_.Count)
}
First thing: you were not using the $server variable in your wmi call so all the results would have been from the one machine you were running this from. Also, I moved the Where into a -Filter so that should speed up processing on remote machines.
Collect all of this information into an array (adding the computer name in case it becomes useful later). Then, using the results from that use Group-Object to get the counts you were looking for. Pipe that into another ForEach-Object to get the results in your grid ( which i have not tested.)
Side note: If you just want the info in a grid you can use Out-GridView
$services | Group-Object Name | Select name,count | Out-GridView

Powershell - Store all Computers in AD into Array

So at the moment I have some code which can lock down to a specific OU via ADSI in Powershell, loop through, and store them into an Array. In turn I loop through this and run a Test-Connection. I have my reasons...
Anyway, is it possible (using only inbuilt cmdlets, i.e. no Quest stuff) to recurse through the whole of AD and add all Computer Objects to the array?
$myArrayOfComputers = #()
$orgUnit = [ADSI]"LDAP://OU=foo,DC=foo,dc=co,dc=uk"
ForEach($child in $orgUnit.psbase.Children) {
if ($child.ObjectCategory -like '*computer*') { $myArrayOfComputers += $child.Name }
}
ForEach($i in $myArrayOfComputers) {
Test-Connection $i
}
In PowerShell V2.0 you can try :
Import-module ActiveDirectory
$computers = Get-ADComputer *
In PowerShell V1.0 You can try :
# dom.fr is the DNS root name of the domain
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://dom.fr:389/dc=dom,dc=fr","administrator#dom.fr","admin")
# Look for computers
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
$Rech.filter = "((objectClass=computer))"
$Rech.SearchScope = "subtree"
$Rech.PropertiesToLoad.Add("sAMAccountName");
$Rech.PropertiesToLoad.Add("lastLogon");
$Rech.PropertiesToLoad.Add("distinguishedname");
$computers = $Rech.findall()
On V2 using .net:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement | out-null
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = new-object 'System.DirectoryServices.AccountManagement.PrincipalContext'($ct, "foo.co.uk", "OU=foo,DC=foo,dc=co,dc=uk");
$cpp = New-Object 'System.DirectoryServices.AccountManagement.Computerprincipal'($pc)
$ps = new-object 'System.DirectoryServices.AccountManagement.PrincipalSearcher'
$ps.QueryFilter = $cpp
$MyListArray = $ps.FindAll() | select -expa name

Booting from an ISO image using PowerCLI scripts

How do I make the following script work? Currently I am able to create a new virtual machine in my server. I wish to also load the Windows ISO image and do an unattended installation in the virtual machine. How shall I edit the script to make this work?
# Virtual Center Details
$server_address = "xxxxx"
$username = "xxxxx"
$password = "xxxxx"
$iso = "WINXP_X86_SP3_CD.ISO"
Get-VIServer -Server $server_address -Protocol https -User $username -Password $password
foreach ($vmm in $array)
{
$vmm = "VirtualMachine"
New-VM -name $vmm -DiskMB 20000 -memoryMB 2000
Get-VM $vmm | Get-CDDrive | Set-CDDrive -IsoPath $iso -StartConnected $true -Confirm:$false
$value = "5000"
$vm = Get-VM $vmname | Get-View
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.BootOptions = New-Object VMware.Vim.VirtualMachineBootOptions
$vmConfigSpec.BootOptions.BootDelay = $value
$vm.ReconfigVM_Task($vmConfigSpec)
Start-vm -vm $vmname
}
my issue is with the ISO PATH image. I am getting the error "Invalid datastore format"
You are specifying isopath using IsoPath parameter, which is the datastore path to the ISO, not simply the ISO name. From your code you are not indicating any datastore.
The syntax for a datastore path is:
"[yourdatastore] IsoFolder\$iso"
Example got from PowerCLI reference online:
$cd = New-CDDrive -VM $vm -ISOPath "[sof-20666-esx:storage1] ISO\testISO.iso"
Set-CDDrive -CD $cd -StartConnected -Connected