vin01's Posts

I tried your script but after restart-vmguest completed the script never ends even though .ExtensionData.Guest.GuestOperationsReady is True
I am trying to perform a restart-vmguest operation on a single vm and wait till restart is done. After that script will look for vmware tools GuestOperationsReady state and once its true then vm ... See more...
I am trying to perform a restart-vmguest operation on a single vm and wait till restart is done. After that script will look for vmware tools GuestOperationsReady state and once its true then vm should shutdown and get the vm name. However the below script is not working its getting struck in a while loo. Can I get the proper way to perform the above explained operation. $vm=Get-VM -Name TestVM01 $vmguestrestartstate=Restart-VMGuest -VM $vm.Name -Confirm:$false while($vmguestrestartstate.State -eq 'Running'){     sleep 2 $vmguestrestartstate.ExtensionData.UpdateViewData("Gueststate")       } while($vm.ExtensionData.Guest.GuestOperationsReady -ne "True"){ Start-Sleep -Seconds 3 $vm.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } Stop-VMGuest -VM $vm -Confirm:$false while($vm.PowerState -eq 'PoweredOn'){ sleep 2 $vm.ExtensionData.UpdateViewData("Runtime.Powerstate") } Get-VM $vm.Name |Select Name,Powerstate
Yes you are right I am trying to use a vSphere object (returned by Get-View). This time I tried like this and it worked. $templatevm= Get-VM 'Win2k16_Std_64bit-testClone' $pg1=Get-VirtualPortG... See more...
Yes you are right I am trying to use a vSphere object (returned by Get-View). This time I tried like this and it worked. $templatevm= Get-VM 'Win2k16_Std_64bit-testClone' $pg1=Get-VirtualPortGroup -VMHost $templatevm.VMHost.Name $dhcpportgroup=Get-VirtualPortGroup -VMHost $templatevm.VMHost |?{$_.ExtensionData.config.DefaultPortConfig.Vlan.VlanId -eq '2067'} Get-NetworkAdapter -VM $templatevm.Name |Set-NetworkAdapter -Portgroup $dhcpportgroup -Confirm:$false
Which PowerCLI version are you using? Did you try without specifying the Name property, like -PortGroup $dhcpPortgroup? yes.
I am trying to set port group for a vm by specifying Set-NetworkAdapter -Portgroup but its failing. However if i specify as like this its working Set-NetworkAdapter -NetworkName Not sure what is... See more...
I am trying to set port group for a vm by specifying Set-NetworkAdapter -Portgroup but its failing. However if i specify as like this its working Set-NetworkAdapter -NetworkName Not sure what is the difference? $templatevm= Get-VM 'Win2k16_Std_64bit-testClone' $dhcpportgroup= Get-View -Id $templatevm.VMHost.ExtensionData.Network |?{$_.config.DefaultPortConfig.Vlan.VlanId -eq '2067'} #$dhcpportgroup.Name Get-NetworkAdapter -VM $templatevm.Name |Set-NetworkAdapter -Portgroup $dhcpportgroup.Name -Confirm:$false |fl
Thanks it’s working 
You can use the Wait-Task cmdlet instead of the While-construct. Yes wait-task is working as expected. How ever the script output is displaying the results while wait-task is in progress. Is it ... See more...
You can use the Wait-Task cmdlet instead of the While-construct. Yes wait-task is working as expected. How ever the script output is displaying the results while wait-task is in progress. Is it something expected? or should I do (Wait-Task -Task $tasks -Verbose |Out-Null) For failed vms I believe its not writing complete error output. Sample output for  failed vms: Yes, that 'interactive window' requirement is also discussed in the thread I mentioned in your other post on this subject. Thanks I will fix manually for 'interactive window' issue vms.
I am trying to change administrator password on windows machines using invoke-vmscript in runasync mode but observed two issues with the script 1.All Invoke-VMScript @sInvoke -RunAsync tasks a... See more...
I am trying to change administrator password on windows machines using invoke-vmscript in runasync mode but observed two issues with the script 1.All Invoke-VMScript @sInvoke -RunAsync tasks are kept under $tasks+ array and passed to a while loop but  I'm not clear where I need to keep this while loop because its waiting till all the tasks are completed and moving to next line.(foreach ($task in $tasks)). I am expecting in $tasks array if any tasks state is completed then it should write output and go in a loop and wait till next task to be completed. 2. The output of each vm is repeating multiple times. Looks like some issue in loop. 3.Anyway to run the script inside the guest os with runas administrator  because the account 'admin' which I am using to invoke has administrator  privilege on the machines. However on few machines its failing with "This operation requires an interactive window station". UAC setting issue I believe run as administrator mode will fix the issue. $script = @' $NewPassword='password' try { $user=Get-WmiObject win32_useraccount |?{$_.Name -eq 'Administrator'} $ComputerName=(“WinNT://”+$user.caption).replace(“\”,”/”) $account = [ADSI]"$ComputerName,user" $account.psbase.invoke("setpassword",$NewPassword) $result= "Password Change completed successfully" } catch { #$status = "FAILED" $result= "Failed to Change the administrator password. Error: $_" } $result '@ $tasks = @() foreach($singlevm in Get-VM "TestVM01", "TestVM02", "TestVM03", "TestVM04", "TestVM05"){ $sInvoke = @{ VM            = $singlevm.Name GuestUser     = 'admin' GuestPassword = '' ScriptText    = $script ScriptType    = 'Powershell' ErrorAction   = 'Stop' } $tasks+=Invoke-VMScript @sInvoke -RunAsync -Confirm:$false } foreach ($task in $tasks) { while ($tasks.State -contains 'running') { Start-Sleep 1 } $task.Result.ScriptOutput.Split("`n") | Where-Object { $_ -ne '' } | Select-Object @{N='VM';E={$task.Result.VM.Name}}, @{N ='Result'; E={$_.Trim("`r`n")}} }
Thanks. I will using this examples and modify my script accordingly.
But you could consider implementing a timeout on each loop. Then when the timeout occurs, the script fails for that template and continues with the next template. How to implement timeout in a ... See more...
But you could consider implementing a timeout on each loop. Then when the timeout occurs, the script fails for that template and continues with the next template. How to implement timeout in a while loop? In below example while($templatevm.ExtensionData.Guest.GuestOperationsReady -ne "True"){  Start-Sleep -Seconds 3  $templatevm.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")  } A Transcript captures stdout and stderr output. If you want to see additional info in there, you will have to send it in your script to one of those streams. Use for example Write-Output to send something to stdout. For example if it failed in below line.Then how do I use Write-Output to send to stdout. Get-NetworkAdapter -VM $templatevm.Name |Set-NetworkAdapter -NetworkName $dhcpportgroup.Name -Confirm:$false
Hi LucD, Can you show me an example please.
Hello Community I need few correction on below script. I have written this script to do windows updates on each template. Process I have defined in the script is 1. I have created a dhcp vl... See more...
Hello Community I need few correction on below script. I have written this script to do windows updates on each template. Process I have defined in the script is 1. I have created a dhcp vlan and mapped to all the hosts in vc. 2.Script will connect to a datacenter in vc and get all the windows templates with Template name,portgroup and vcname in $alltemplates var 3.Then its taken in a foreach loop $singletemplate and set each template to vm and assign the dhcp port group and poweron. (This will auto assign dhcp ip and connects to wus server which is already configured in templates.) 4. VM will wait for GuestOperationsReady to ready and checks if tools are outdated then it will update. 5.if tools are updated then it will wait for GuestOperationsReady eq true then do invoke in RunAsync mode to pass code in $script 6. All invoke tasks are kept $tasks+ array 7.when ever task state completed it will do Restart-VMGuest to apply patches. 8.Again it will wait till GuestOperationsReady -eq true. 9.then do Stop-VMGuest and writes Invoke-VMScript output which is in $task variable to $report 10.Then it will send email with status report 11.Again it will convert portgroup status of template vms to old one $alltemplates and set each vm back to template. ------------- Tested the script on 30 templates and working as expected. I required help in below points 1.Lot of while loops in the script so if any vm struck in a loop then the script will not completes for ever. So by looking the script in any line can we use alternate method or reduce while loops 2.For logfile i am using Start-Transcript but the problem is in the logfile  is it will write what ever displayed in powershell window so if we get error for a vm whose character doesn't fit in powershell window it will write as below. Any alternate to get the full windows output. Sample log data from Start-Transcript logfile. At C:\My Data\Working\windowsupdateprototypescript_updated.ps1:75 char:18 + Update-Tools -VM $task.Result.VM.Name -NoReboot +                  ~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : InvalidData: (:) [Update-Tools], ParameterBindingValidationException     + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.UpdateVmTo    ols W_Win10_64_MSDNNe...  PoweredOff 1        0.250 (No Fullname for vm (....) are represented so it hard to find if vmname) Start-Transcript -Path "C:\My Data\Notepad++\logfile.txt" -NoClobber -Force -Confirm:$false $script = @' $finalresult=@() $ErrorActionPreference = "SilentlyContinue" If ($Error) { $Error.Clear() } $Today = Get-Date $UpdateCollection = New-Object -ComObject Microsoft.Update.UpdateColl $Searcher = New-Object -ComObject Microsoft.Update.Searcher $Session = New-Object -ComObject Microsoft.Update.Session $Result = $Searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0") If ($Result.Updates.Count -EQ 0) { $finalresult+= "There are no applicable updates for this computer." } Else { For ($Counter = 0; $Counter -LT $Result.Updates.Count; $Counter++) { $DisplayCount = $Counter + 1     $Update = $Result.Updates.Item($Counter) $UpdateTitle = $Update.Title } $Counter = 0 $DisplayCount = 0 $Downloader = $Session.CreateUpdateDownloader() $UpdatesList = $Result.Updates For ($Counter = 0; $Counter -LT $Result.Updates.Count; $Counter++) { $UpdateCollection.Add($UpdatesList.Item($Counter)) | Out-Null $ShowThis = $UpdatesList.Item($Counter).Title $DisplayCount = $Counter + 1 $Downloader.Updates = $UpdateCollection $Track = $Downloader.Download() If (($Track.HResult -EQ 0) -AND ($Track.ResultCode -EQ 2)) { $finalresult+="Download Status:SUCCESS" } Else { $finalresult+="Download Status: FAILED With Error -- $Error()" $Error.Clear() } } $Counter = 0 $DisplayCount = 0 $Installer = New-Object -ComObject Microsoft.Update.Installer For ($Counter = 0; $Counter -LT $UpdateCollection.Count; $Counter++) { $Track = $Null $DisplayCount = $Counter + 1 $WriteThis = $UpdateCollection.Item($Counter).Title $Installer.Updates = $UpdateCollection Try { $Track = $Installer.Install() $finalresult+="Update Installation Status:SUCCESS" } Catch { [System.Exception] $finalresult+= "Update Installation Status: FAILED With Error -- $Error()" $Error.Clear() } } } $finalresult -join ',' '@ $tasks = @() $alltemplates=Get-Template "Template01", "Template02", "Template03", "Template04", "Template05" |Select-Object @{N='Name';E={$_.Name}},@{N="Portgroup";E={((Get-View -Id $_.ExtensionData.Network).name)}},@{N="vCenter";E={([System.Net.Dns]::GetHostEntry($_.Uid.Split(“:”)[0].Split(“@”)[1])).HostName}} foreach($singletemplate in $alltemplates){ Set-Template -Template $singletemplate.Name -ToVM -Confirm:$false $templatevm= Get-VM $singletemplate.Name $dhcpportgroup= Get-View -Id $templatevm.VMHost.ExtensionData.Network |?{$_.config.DefaultPortConfig.Vlan.VlanId -eq '2067'} Get-NetworkAdapter -VM $templatevm.Name |Set-NetworkAdapter -NetworkName $dhcpportgroup.Name -Confirm:$false Start-VM -VM $templatevm.Name -Confirm:$false while($templatevm.ExtensionData.Guest.GuestOperationsReady -ne "True"){ Start-Sleep -Seconds 3 $templatevm.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } if($templatevm.ExtensionData.guest.toolsversionstatus -eq 'guestToolsNeedUpgrade'){ Update-Tools -VM $task.Result.VM.Name -NoReboot while($templatevm.ExtensionData.Guest.GuestOperationsReady -ne "True"){ Start-Sleep -Seconds 3 $templatevm.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } else { while($templatevm.ExtensionData.Guest.GuestOperationsReady -ne "True"){ Start-Sleep -Seconds 3 $templatevm.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } $sInvoke = @{ VM            = $templatevm.Name GuestUser     = 'administrator' GuestPassword = '' ScriptText    = $script ScriptType    = 'Powershell' ErrorAction   = 'Stop' } $tasks+=Invoke-VMScript @sInvoke -RunAsync -Confirm:$false }} while ($tasks.State -contains 'running') {   Start-Sleep 1 } $report=@() $CurrentDate = Get-Date -Format 'MM-dd-yyyy_hh-mm-ss' $csvFiles = @() foreach ($task in $tasks) { Restart-VMGuest -VM $task.Result.VM.Name -Confirm:$false while($task.Result.VM.ExtensionData.Guest.GuestOperationsReady -eq "True"){ Start-Sleep -Seconds 3 $task.Result.VM.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } Get-VM -Name $task.Result.VM.Name |Out-Null while($task.Result.VM.ExtensionData.Guest.GuestOperationsReady -ne "True"){ Start-Sleep -Seconds 3 $task.Result.VM.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } Stop-VMGuest -VM $task.Result.VM.Name -Confirm:$false while($task.Result.VM.ExtensionData.Guest.GuestOperationsReady -eq "True"){ Start-Sleep -Seconds 3 $task.Result.VM.ExtensionData.UpdateViewData("Guest.GuestOperationsReady") } $report+=$task.Result.ScriptOutput.Split("`n") | Where-Object { $_ -ne '' } | Select-Object @{N='VM';E={$task.Result.VM.Name}}, @{N ='Status'; E={$_.Trim("`r`n")}} } $filename = "C:\AllTemplatepatchstatusreport.csv as on dated $($CurrentDate).csv" $csvFiles += $filename $report |Export-Csv -Path $filename -NoTypeInformation -NoClobber -UseCulture Send-MailMessage -From "" -To "" -Subject "Script POC Template Patching" ` -Body "The attachment contains templates patching status" ` -Attachments $csvFiles -SmtpServer '' $alltemplates |ForEach-Object -Process { Get-NetworkAdapter -VM $_.name |Set-NetworkAdapter -NetworkName $_.Portgroup -Confirm:$false Set-VM -VM $_.Name -ToTemplate -Confirm:$false } Stop-Transcript
Thanks Sir.
I am using Invoke-VMScript with RunAsync switch to execute parallel and after script execution state is success it should write vmname and the result of invoke cmdlet. But in Invoke-VMScript wit... See more...
I am using Invoke-VMScript with RunAsync switch to execute parallel and after script execution state is success it should write vmname and the result of invoke cmdlet. But in Invoke-VMScript with RunAsync if I list the process I don't fine the vmname so is it possible to get the vmname? Here is the sample code and output $script=@' Get-NetAdapter |select Name '@ $vm=Get-VM 'TestVM01'Test02 $output=@() $vm.Name | ForEach-Object -Process { $output+=Invoke-VMScript -VM $_ -GuestUser '' -GuestPassword '' -ScriptText $script -ScriptType Powershell -RunAsync -Confirm:$false } $output |fl Here if I do format-list how can i get the vmname. I can see the result of the execution but if I need to export to csv I need to know which result belongs to which VM.
Yeah You are right LucD. I have checked in psversion 5.1 and its showing up the results. Thanks letting me know the issue.
Hello Community Members, I am seeing the below error when  I try to do Format-List for a array variable. What could be the issue? $vm=Get-VM 'Test01','Test02' $output=@() $vm.Name | For... See more...
Hello Community Members, I am seeing the below error when  I try to do Format-List for a array variable. What could be the issue? $vm=Get-VM 'Test01','Test02' $output=@() $vm.Name | ForEach-Object -Process { $output+=Invoke-VMScript -VM $_ -GuestUser '' -GuestPassword '' -ScriptText 'dir' -ScriptType Powershell -RunAsync -Confirm:$false } $output |fl
Hello, I have written the below script to check ThinProvision property is available to blueprint or not. Till this extend I can get the report correctly. Once I get the list of blueprints whic... See more...
Hello, I have written the below script to check ThinProvision property is available to blueprint or not. Till this extend I can get the report correctly. Once I get the list of blueprints which doesn't contains  ThinProvision property then I need to add the property to that blueprint. However I don't find any rest method to add custom property to the blueprints in vRA 7.6 API documentation. So my question - Is it possible to add  custom property(ThinProvision) to blueprints using restmethods. If yes please give me an example. $cred=Get-Credential  $allorgs='',''  foreach($org in $allorgs){  $vra_server=''  $identityRequest = @{  "username"= $cred.UserName  "password"=$cred.GetNetworkCredential().password  "tenant"=$org      }      $json = $identityRequest | ConvertTo-Json      $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"      $headers.Add("Accept", 'application/json')         $response = Invoke-RestMethod "https://$($vra_Server)/identity/api/tokens" -Headers $headers -Method Post -Body $json -ContentType 'application/json'      $token = $response.ID      $restHeaders = @{"Content-Type"="application/json";"Authorization"="Bearer $token"}      $uri="https://$($vra_Server)/catalog-service/api/consumer/catalogItems"      $CatalogItem=Invoke-RestMethod -Method Get -Uri $uri -Headers $restHeaders      foreach($singlecatalogid in  $CatalogItem.content){      $uri1="https://$($vra_Server)/catalog-service/api/consumer/entitledCatalogItems/$($singlecatalogid.id)/requests/schema"      $CatalogItemschema=Invoke-RestMethod -Method Get -Uri $uri1 -Headers $restHeaders      $VirtualMachinethin=$CatalogItemschema.fields.datatype.schema.fields |Where-Object{$_.id -match 'VirtualMachine.Admin.ThinProvision'}      if(-not $VirtualMachinethin){      $VirtualMachinethin="ThinProvision Property not added"      }      else {          $VirtualMachinethin="ThinProvision Property added"          }     New-Object PSObject -Property (      [ordered]@{          TenantName = $org          BluePrint  = $singlecatalogid.name          ThinProvisionPropertystatus = $VirtualMachinethin                })  }  } 
I know this is not related to actual powercli question. If any one can answer it could be more helpful. There is no official vRA module yet. I don't why vMware not giving much love to its vRA pro... See more...
I know this is not related to actual powercli question. If any one can answer it could be more helpful. There is no official vRA module yet. I don't why vMware not giving much love to its vRA product! Here is the requirement. I have written the below script to check ThinProvision property is available to blueprint or not. Till this extend I can get the report correctly. Once I get the list of blueprints which doesn't contains  ThinProvision property then I need to add the property to that blueprint. However I don't find any rest method to add custom property to the blueprints in vRA 7.6 API documentation. So my question - Is it possible to add  custom property(ThinProvision) to blueprints using restmethods. If yes please give me an example. $cred=Get-Credential $allorgs='','' foreach($org in $allorgs){ $vra_server='' $identityRequest = @{ "username"= $cred.UserName "password"=$cred.GetNetworkCredential().password "tenant"=$org     }     $json = $identityRequest | ConvertTo-Json     $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"     $headers.Add("Accept", 'application/json')       $response = Invoke-RestMethod "https://$($vra_Server)/identity/api/tokens" -Headers $headers -Method Post -Body $json -ContentType 'application/json'     $token = $response.ID     $restHeaders = @{"Content-Type"="application/json";"Authorization"="Bearer $token"}     $uri="https://$($vra_Server)/catalog-service/api/consumer/catalogItems"     $CatalogItem=Invoke-RestMethod -Method Get -Uri $uri -Headers $restHeaders     foreach($singlecatalogid in  $CatalogItem.content){     $uri1="https://$($vra_Server)/catalog-service/api/consumer/entitledCatalogItems/$($singlecatalogid.id)/requests/schema"     $CatalogItemschema=Invoke-RestMethod -Method Get -Uri $uri1 -Headers $restHeaders     $VirtualMachinethin=$CatalogItemschema.fields.datatype.schema.fields |Where-Object{$_.id -match 'VirtualMachine.Admin.ThinProvision'}     if(-not $VirtualMachinethin){     $VirtualMachinethin="ThinProvision Property not added"     }     else {         $VirtualMachinethin="ThinProvision Property added"      }    New-Object PSObject -Property (     [ordered]@{         TenantName = $org         BluePrint  = $singlecatalogid.name         ThinProvisionPropertystatus = $VirtualMachinethin             }) } }
Perfect I can get the report what I’m expected and also vms sorting with Harddisk Fixed the vms order in sequence. I will change back the (Get-Date).AddDays(-1) and schedule it on few vcenters an... See more...
Perfect I can get the report what I’m expected and also vms sorting with Harddisk Fixed the vms order in sequence. I will change back the (Get-Date).AddDays(-1) and schedule it on few vcenters and monitor for couple of days if any issues in output I’ll update you. Thanks for your support Guru.
What I have did is before running the script logged into vc and  I have powered off all the vms and executed the script 1st time then a report is generated with all vms as below: VM,CPU,Memory,p... See more...
What I have did is before running the script logged into vc and  I have powered off all the vms and executed the script 1st time then a report is generated with all vms as below: VM,CPU,Memory,powerstate,Harddisk vm1,2,       4,    Poweredoff,       harddisk1 vm2,2,       2,    Poweredoff,       harddisk1 vm3,4,       8,    Poweredoff,       harddisk1 after 15 mins I logged into vcenter and added hard disk to VM1 and changed cpu and memory for vm1,vm2,vm3 and powered on all the vms. waited for 1 hr and executed 2nd time. And here is the output VM,CPU,Memory,powerstate,Harddisk vm1,2,       4,    Poweredoff,       harddisk1 vm2,4,       6,    Poweredoff,       harddisk1 vm3,2,       4,    Poweredoff,       harddisk1 vm1,4,      12,   Poweredoff,       harddisk2 powerstate is not changed. What sequence do you mean? the VM1 output is not sequence in csv after 2nd execution. Do you see the corresponding events when you do a Get-VIEvent? yes I can see the events in vc. note: I have changed $start = (Get-Date).AddMinutes(-1) in the script.