GuilhermeAlves's Posts

Haven't found the post i was looking for... I had this issue a year ago and found some people with the same problem...Some upgraded the PowerShell or PowerCLI version and solved. Some other didn'... See more...
Haven't found the post i was looking for... I had this issue a year ago and found some people with the same problem...Some upgraded the PowerShell or PowerCLI version and solved. Some other didn't. Still looking for an answer...
Have you already tried to use the prompt? I think you`ll have another output, but it'll still hang. I don't clearly remember but this is a bug without a resolution...i'll try to find the document... See more...
Have you already tried to use the prompt? I think you`ll have another output, but it'll still hang. I don't clearly remember but this is a bug without a resolution...i'll try to find the documentation about that.
i Had the same problem using the PowerShell ISE. How do you run your script?
Sorry about that GB... But great! glad to know you made it work.
Well, i have a script that generates what you want. But i use a function which shows the snapshots. You can easily call the function passing the Vcenter connection as parameter Example: $Repo... See more...
Well, i have a script that generates what you want. But i use a function which shows the snapshots. You can easily call the function passing the Vcenter connection as parameter Example: $Report = Get-Snaps (connect-viserver "yourServer") Warn me if you want some help modifying it. function Get-Snaps(){ param($currentVC)       #Filter only Vms which contains Snapshots       Write-Host "`t Generating Report from Server: $($currentVC.name)"       #Filter Templates and non Snapshotteds Vms       $vmsWithSnaps = Get-view -viewType VirtualMachine -Property Name,Config.Template,Snapshot -Server $currentVC -Filter @{'Config.Template'='False'}|where{$_.snapshot -ne $null}       if($vmsWithSnaps){             try{              foreach($vm in $vmswithSnaps){                 $currVM = $vm|Get-VIObjectByVIView                  if($currVM){                         Write-Host "`t`tSnapshots found Here: $($currVM.Name)"                         $VMsnaps = $currVM | Get-Snapshot                         $tempReport = $VMsnaps | Select VM,@{N="Vcenter";E={$currentVC.Name}},@{N="Cluster";E={($currVM|get-cluster|select Name).Name}},@{N="Host";E={$currVM.Vmhost.Name}},Name,@{N="PowerState";E={$currVM.PowerState}},Description,Created,SizeGB,Datastores,FileNames,UserName                         #Get Snapshot Files                         $snapFiles = Get-HardDisk -Snapshot $VMsnaps                         #Get who created it                         $SnapshotEvents = Get-VIEvent -Entity $currVM -type info -MaxSamples 1000 | Where {$_.FullFormattedMessage.contains("Create virtual machine snapshot")}                         try{                             $user = $SnapshotEvents[0].UserName                         }catch [System.Exception] {                             $user = $SnapshotEvents.UserName                         }                         $tempReport|%{                             $_.SizeGB = "{0:N2}" -f $tempReport.SizeGB                             $_.UserName = $user                             $_.Datastores = ([String]($snapFiles|%{$_.Filename.split("]")[0].split("[")[1]}| select -Unique)).replace(" ",",")                             $_.FileNames = ([String]($snapFiles|%{($_.FileName).replace(" ","")})).replace(" ",",")                         }                         $tempReport                     }                 }             }catch{                 #do nothing, let it go             }            }else{             $tempReport = ""| Select VM,PowerState,Vcenter,Name,Description,Created,SizeGB,UserName             $tempReport.VM = "No Snapshots found on $($currentVC.Name)"             $tempReport         } }
Plus, if you want a better approach, here it is: # Adding PowerCLI Snapin if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {         try {             add-pssnapi... See more...
Plus, if you want a better approach, here it is: # Adding PowerCLI Snapin if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {         try {             add-pssnapin VMware.VimAutomation.Core| out-null         } catch {             throw "Could not load PowerCLI snapin"         } } # Set to multiple VC Mode if(((Get-PowerCLIConfiguration -Scope Session).DefaultVIServerMode) -ne "Multiple") {     Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope AllUsers -Confirm:$false | Out-Null     Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope User -Confirm:$false | Out-Null     Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope Session -Confirm:$false | Out-Null } # function connectvCenters{     param($list) $arrayConnectedVC =@()       foreach($itemList in $list){             try{                 $sessionID = $global:defaultviservers | where {$_.Name -like "$itemList*"} |Select -First 1 -ExpandProperty SessionId                                if($sessionId){                     $vc = Connect-VIServer -server $itemList -Session $sessionId -wa 0 -ea stop                     if($vc){                         Write-Host "Successfully reconnected to '$vc'"                         $arrayConnectedVC += $vc                     }else{                        Write-Host "Error connecting to '$vc'"                     }           }else{                     $vc = Connect-VIServer -server $itemList -wa 0 -ea stop                     if($vc){                         Write-Host "Successfully connected to '$vc'"                         $arrayConnectedVC += $vc                     }else{                         Write-Host "Error connecting to '$vc'"                     }                 }             }catch{                 $Errormessage = $_.Exception.MEssage                 Write-Host "Error connecting to '$vc' `n `t$Errormessage"             }        }     return $arrayConnectedVC } # function Get-Snaps(){ param($currentVC)       #Filter only Vms which contains Snapshots       Write-Host "`t Generating Report from Server: $($currentVC.name)"       #Filter Templates and non Snapshotteds Vms       $vmsWithSnaps = Get-view -viewType VirtualMachine -Property Name,Config.Template,Snapshot -Server $currentVC -Filter @{'Config.Template'='False'}|where{$_.snapshot -ne $null}       if($vmsWithSnaps){             try{               foreach($currVM in ($vmswithSnaps|Get-VIObjectByVIView)){                     if($currVM){                         Write-Host "`t`tSnapshots found Here: $($currVM.Name)"                         $tempReport = $currVM | Get-Snapshot | Select VM,@{N="Vcenter";E={$currentVC.Name}},Name,@{N="PowerState";E={$currVM.PowerState}},Description,Created,SizeGB,UserName                         #Get who created it                         $SnapshotEvents = Get-VIEvent -Entity $currVM -type info -MaxSamples 1000 | Where {$_.FullFormattedMessage.contains("Create virtual machine snapshot")}                         try{                             $user = $SnapshotEvents[0].UserName                         }catch [System.Exception] {                             $user = $SnapshotEvents.UserName                         }                         $tempReport|%{                             $_.SizeGB = "{0:N2}" -f $tempReport.SizeGB                             $_.UserName = $user                         }                         $tempReport                     }                }             }catch{                 #do nothing, let it go             }             }else{             $tempReport = ""| Select VM,PowerState,Vcenter,Name,Description,Created,SizeGB,UserName             $tempReport.VM = "No Snapshots found on $($currentVC.Name)"             $tempReport         } } # #Initialize Script # try{    #get Vcenters List from file    $VCStringlist = get-content ".\list.csv" -ErrorAction Stop    #or directly from script   # $VCStringlist = "scltz0009cld"    }catch{     $ErrorMessage = $_.Exception.Message     write-Host "Erro ao obter lista de vCenters do arquivo! `n $ErrorMessage" } #connect to Vcenters $conns = connectvCenters -list $VCStringlist $Report = @() #for each vcenter, generate snapshots list and add it to the main Report $conns|%{     if($_){         $Report += Get-Snaps $_         Disconnect-VIServer $_ -Force -Confirm:$false|out-null     } } $htmlReport = @" <style type='text/css'> .heading {   color:#3366FF; font-size:12.0pt; font-weight:700; font-family:Verdana, sans-serif; text-align:left; vertical-align:middle; width:auto } .colnames {   color:white; font-size:10.0pt; font-weight:700; font-family:Tahoma, sans-serif; text-align:center; vertical-align:middle; border:.5pt solid windowtext; background:#6495ED; } .text { color:windowtext; font-size:10.0pt; font-family:Arial; text-align:center; vertical-align:middle; border:.5pt solid windowtext; background:#FFFFFF; } </style> <title>Snapshot Report</title> <table border=0 cellpadding=0 cellspacing=0 width=555 style='border-collapse:collapse;table-layout:fixed;width:600pt'> <tr style='height:15.0pt'>   <th colspan=5 height=40 width=555 class="heading"> vSphere Snapshots Daily Report</th> </tr> <tr>   <th class="colnames">VCenter</th>   <th class="colnames">Virtual Machine</th>   <th class="colnames">Power State</th>   <th class="colnames">Description</th>   <th class="colnames">Size (GB)</th>   <th class="colnames">Date Created</th>   <th class="colnames">User Name</th> </tr> "@ foreach($snapshot in $Report){     $htmlReport = $htmlReport +     "<tr><td class='text'>" + $snapshot.Vcenter + "</td>" +     "<td class='text'>" + $snapshot.VM + "</td>" +     "<td class='text'>" + $snapshot.PowerState + "</td>" +    "<td class='text'>"+ $snapshot.Description + "</td>" + "<td class='text'>" + $snapshot.SizeGB + "</td>" + "<td class='text'>" + $snapshot.Created + "</td>"+     "<td class='text'>" + $snapshot.UserName + "</td></tr>" } $htmlReport = $htmlReport + "</table>" #Write Report to a html File $dataTD = get-date $dd = $dataTD.Day $mm =$dataTD.Month $yy = $dataTD.Year $hh = $dataTD.Hour $mmm = $dataTD.Minute $ss = $dataTD.Second $TDformatted = "($dd-$mm-$yy) $hh"+"h"+"-$mmm"+"m-$ss"+"s" $htmlReport  | Out-File ".\SnapShotReport $TDformatted.html" <# Generate the report and email it as a HTML body of an email if($Report -ne ""){     $SmtpClient = New-Object system.net.mail.smtpClient     $SmtpClient.host = "my.smtp.host"   #Change to a SMTP server in your environment     $MailMessage = New-Object system.net.mail.mailmessage     $MailMessage.from = "System.Automation@example.com"   #Change to email address you want emails to be coming from     $MailMessage.To.add("yomomma@example.com")    #Change to email address you would like to receive emails.     $MailMessage.IsBodyHtml = 1     $MailMessage.Subject = "VMware Snapshots Report $TDformatted "     $MailMessage.Body = $htmlReport     $SmtpClient.Send($MailMessage) } #> Now better than before. That's what i'm using on my environment.
You can try this: # Adding PowerCLI Snapin if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {         try {             add-pssnapin VMware.VimAutomation.Core| out... See more...
You can try this: # Adding PowerCLI Snapin if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {         try {             add-pssnapin VMware.VimAutomation.Core| out-null         } catch {             throw "Could not load PowerCLI snapin"         } } $VIServer = "vcenter1","vcenter2" $Report = @() foreach($VCserver in $VIserver){     $currentVC = Connect-VIServer -Server $VCserver -Protocol https -User administrator -Password Pass@123     $Header = @"             <style>                 TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}                 TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}                 TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}                 .odd  { background-color:#ffffff; }                 .even { background-color:#dddddd; }             </style>             <title>Snapshot Report - $VcServer</title> "@ $a = Get-VM -Server $currentVC | Get-Snapshot | Select VM,@{N="VCname";E={$currentVC.Name}},Name,Description,Created,SizeMB,SizeGB     If (-not $a){         $a = New-Object PSObject -Property @{         VCname = "No snapshots found on any VM's controlled by $($currentVC.Name)"         VM = ""         Name = ""         Description = ""         SizeGB = ""         Created = ""         }     } Disconnect-VIServer $currentVC -Force -Confirm:$false $Report += $a } $Report = $report | Select VCname,VM,Name,Description,SizeGB,Created | ConvertTo-Html -Head $Header -PreContent "<p><h2>Snapshot Report</h2></p><br>" $Report | Out-File "C:\VM-operations\dailyreport\SnapShotReport.html"
Do i need to thank again? hehehe :smileylaugh: You're the best Luc! This script is part of another i've did here => https://communities.vmware.com/docs/DOC-26302 Initially i was using RVTo... See more...
Do i need to thank again? hehehe :smileylaugh: You're the best Luc! This script is part of another i've did here => https://communities.vmware.com/docs/DOC-26302 Initially i was using RVTools to export some information...and i'm still exploring the Steve Jin's VI Java API Until I get good on it, i'll try to get faster responses with PowerShell/Cli. It Never lets me down!
Is there a way to make the above script faster? I know that is a problem with Get-scsiLun and Get-ScsiLunPath. They are very lazy when querying againsta too much hosts or too much paths.. I w... See more...
Is there a way to make the above script faster? I know that is a problem with Get-scsiLun and Get-ScsiLunPath. They are very lazy when querying againsta too much hosts or too much paths.. I wanna know if there is a way to get this info using get-view or something... $esxs = Get-Vmhost $esx = $esxs[1] $multipathInfos=@() #Get information about Multipath $multipathInfos += $esx | Get-ScsiLun -LunType disk  |%{     $VMHostScsiLun=$_         $VMHostScsiLunPaths = $VMHostScsiLun | Get-ScsiLunPath         $VMHostScsiLunPaths | Select @{N="Hostname"; E={$esx.Name}}, @{N="Number of Paths"; E={($VMHostScsiLunPaths|measure).count}}, Sanid, ScsiCanonicalName, State,@{N="Policy"; E={$VMHostScsiLun.MultipathPolicy}} }$multipathInfos
$VIServer = "myserver" $user = "mydomain\myuser" $password = "**********" $FilePath = "c:\users\myuser\desktop\mycred.xml" #Creates a new file with your credentials New-VICredentialStoreIt... See more...
$VIServer = "myserver" $user = "mydomain\myuser" $password = "**********" $FilePath = "c:\users\myuser\desktop\mycred.xml" #Creates a new file with your credentials New-VICredentialStoreItem -Host $VIServer -User $user -Password $password -File $FilePath #Get your credentials from file and keeps on a new variable $cred = Get-VICredentialStoreItem -Host $VIServer -File $FilePath #Connects using the VICredentialStoreItem Connect-VIServer -User $cred.User -Password $cred.Password -Server $VIServer #To remove the credential File Remove-Item -Path $FilePath -Force
Maybe your vcenter session has forcelly disconnected by someone...That happened to me too! try disconnecting all sessions and connect again.. it Works for me.      Disconnect-Viserver * ... See more...
Maybe your vcenter session has forcelly disconnected by someone...That happened to me too! try disconnecting all sessions and connect again.. it Works for me.      Disconnect-Viserver * -Force -Confirm:$false
lkujala, here we do the same. Remove the failed esxi from inventory and add manually the Vms to another host by browsing datastore and using the "Add to Inventory" Option when clicking on the .vm... See more...
lkujala, here we do the same. Remove the failed esxi from inventory and add manually the Vms to another host by browsing datastore and using the "Add to Inventory" Option when clicking on the .vmx file. You say you can not remove the VM from the offline host and add to the existing host. Try to remove the first host from inventory before adding the VMs to the new one. Have you try that? This is almost equal to Anjani's post up here but it Works for me like a charm.
You'll have this answer while the pipelined parameter for the Get-view cmdlet were null You can try this: $null | get-view This may show you the same error In the script, the error... See more...
You'll have this answer while the pipelined parameter for the Get-view cmdlet were null You can try this: $null | get-view This may show you the same error In the script, the error will appear while the $datastoresPerCluster variable remains null. You have to make sure that the following variables are properly filled: =>$myvc      This will show your vcenter connection, if successfull: PS C:\users\user\Documents> $myvc Name                           Port  User                          ----                           ----  ----                          myserver                     443   DOMAIN\user =>$myclusters      This will show you a table with your clusters info: PS C:\users\user\Documents> $myclusters Name                           HAEnabled  HAFailover DrsEnabled DrsAutomationLe                                           Level                 vel            ----                           ---------  ---------- ---------- --------------- mycluster                          True       1          True       FullyAutomated mycluster-1                        True       2          True       FullyAutomated mycluster-4                       True       1          True       FullyAutomated mycluster-3                       True       1          True       FullyAutomated mycluster-2                        True       1          True       FullyAutomated After that, you can run this part of the script: foreach($cluster in $myclusters){       $cluster|Get-VMhost|Get-Datastore } Then you'll see if the $datastorePerCluster variable is null or not.
Nice! Let me know if you find some answer. I'll give a try when I could. --- Mensagem Original --- De: "Craig Baltzer" <communities-emailer@vmware.com> Enviado: 27 de março de 2014 22:4... See more...
Nice! Let me know if you find some answer. I'll give a try when I could. --- Mensagem Original --- De: "Craig Baltzer" <communities-emailer@vmware.com> Enviado: 27 de março de 2014 22:45 Para: "GuilhermeAlves" <guilhermestela@hotmail.com> Assunto: New message: "Freeze when running PowerCLI cmdlets via invoke-command" VMware Communities<https://communities.vmware.com/index.jspa> Freeze when running PowerCLI cmdlets via invoke-command created by Craig Baltzer<https://communities.vmware.com/people/Craig+Baltzer> in VMware vSphere™ PowerCLI - View the full discussion<https://communities.vmware.com/message/2362569#2362569>
Did you managed your script to work Craig?
Did you ran all the code? Run everything: #loading powercli environment  if(!(get-pssnapin|where{$_.name -eq"vmware.vimautomation.core"})) {  try{      add-pssnapin VMware.VimAutoma... See more...
Did you ran all the code? Run everything: #loading powercli environment  if(!(get-pssnapin|where{$_.name -eq"vmware.vimautomation.core"})) {  try{      add-pssnapin VMware.VimAutomation.Core  } catch{      $ErrorMessage=$_.Exception.Message      Write-host "$ErrorMessage"  }  }  #change the parameter Server to your vCenter  $myvc= connect-viserver -Server "yourServer" -wa 0  #you can get the datastores by the Hosts in your clusters  $myclusters=Get-Cluster -Server $myvc  $info2export=@()  foreach($cluster in $myclusters){        $datastoresPerCluster = $cluster|Get-VMhost|Get-Datastore  foreach($datastore in $datastoresPerCluster){         $view = ($datastore | get-view | select -expandproperty summary)         $partialInfo=""|select ClusterName,DatastoreName,ProvisionedSpace,CapacitySpaceUsed,FreeSpace           $partialInfo.ClusterName =$cluster.Name           $partialInfo.DatastoreName =$datastore.Name           $Uncommitted = [math]::round(($datastore|get-view |select -expandproperty summary).Uncommited/1GB,2)         $partialInfo.CapacitySpaceUsed = [math]::round($view.Capacity/1GB,2)         $partialInfo.FreeSpace = [math]::round($view.FreeSpace/1GB,2)         $partialInfo.ProvisionedSpace = ($view.CapacityGB – $view.FreeSpaceGB + $Uncommitted)         $info2export+=$partialInfo    }    }  #Export to csv in the path you want  $path="c:\temp\datastoreList.csv"  $info2export|Export-Csv -Path $path -NoTypeInformation -UseCulture
Agree Luc, I think mark have to change the approach to get things work. Maybe testing with simpler scripts and making a step by step with the desired script... That requires a lot of patience ... See more...
Agree Luc, I think mark have to change the approach to get things work. Maybe testing with simpler scripts and making a step by step with the desired script... That requires a lot of patience for sure!
so...there's no more discussion anymore, i think....i've answered myself hehehehe What can we do with this discussion?
Try to use this fragment on the script: $info2export=@() foreach($cluster in $myclusters){      $datastoresPerCluster = $cluster|Get-VMhost|Get-Datastore foreach($datastore in $datasto... See more...
Try to use this fragment on the script: $info2export=@() foreach($cluster in $myclusters){      $datastoresPerCluster = $cluster|Get-VMhost|Get-Datastore foreach($datastore in $datastoresPerCluster){        $view = ($datastore | get-view | select -expandproperty summary)        $partialInfo=""|select ClusterName,DatastoreName,ProvisionedSpace,CapacitySpaceUsed,FreeSpace         $partialInfo.ClusterName =$cluster.Name         $partialInfo.DatastoreName =$datastore.Name         $Uncommitted = [math]::round(($datastore|get-view |select -expandproperty summary).Uncommited/1GB,2)        $partialInfo.CapacitySpaceUsed = [math]::round($view.Capacity/1GB,2)        $partialInfo.FreeSpace = [math]::round($view.FreeSpace/1GB,2)        $partialInfo.ProvisionedSpace = ($view.CapacityGB – $view.FreeSpaceGB + $Uncommitted)        $info2export+=$partialInfo  }  }
For this script i had an inspiration of Mauro Bonder needs. This function retrieves a report with all user sessions that has been idle about 8 hours and the next Terminates that sessions. ... See more...
For this script i had an inspiration of Mauro Bonder needs. This function retrieves a report with all user sessions that has been idle about 8 hours and the next Terminates that sessions. function Get-ViIdleSessions{ <# .SYNOPSIS    Get Idle sessions from vcenters .DESCRIPTION    This script gets all the sessions in the last 8 hours inactive .NOTES   Authors:  Guilherme Alves Stela             Mauro Bonder .PARAMETER vclist    This parameter specifies the connection(s) to any vcenters wanted.    .PARAMETER excluded    This parameter specifies the file container of the list of users who will be excluded from the output list of inactive sessions. .EXAMPLE    $vcs = Connect-viserver -Server "myserver" -AllLinked:$true    $usersToExclude = Get-content (myfile.txt)    Get-viIdleSessions -vclist $vcs -excluded $usersToExclude       This command retrieves information about all users logged on the servers specified in the variable $vcs #> param($vclist,$excluded) $report=@() foreach($vc in $vclist){ $sessMgr = Get-View SessionManager -Server $vc     #Loop under SessionManager from vcenter     foreach($sess in $sessMgr){         #Get All Sessions         foreach($subsess in $sess.Sessionlist){             #if last active time less than 8 hours, add to oldsessions list             if(((($subsess.LastActiveTime).AddHours(8)) -lt (Get-date)) -and ($excluded -notcontains $subSess.Username)){                 $row ="" | select Username,FullName,TimeStamp,Server,LoginTime,LastActiveTime,Key                 $row.Username = $subsess.UserName                 $row.FullName = $subsess.FullName                 $row.TimeStamp = Get-Date                 $row.Server = $vc.Name                 $row.LoginTime = $subsess.LoginTime                 $row.LastActiveTime = $subsess.LastActiveTime                 $row.Key = $subsess.key                 $report += $row             }         }     } } return $report } Simple Example: $report = Get-ViIdleSessions -vclist (connect-viserver "myserver") -excluded (Get-Content "./excluded-users.txt") And to disconnect the users: function Disconnect-ViIdleSessions { param($list,$vcs) $list |%{ $key = $_.Key $server = $_.Server     $vcs| %{         if($_.Name -eq $server) {             $SessionMgr = Get-View $_.ExtensionData.Client.ServiceContent.SessionManager             $SessionMgr.TerminateSession($key)             }     } } } Simple Example: Disconnect-ViIdleSessions -list $Allreport -vcs $conns An Example to view and terminate Idle Sessions: # # Starting script Execution # # Try to get vCenter String List from file try{     $VCStringlist = get-content "myvclist" -ErrorAction Stop }catch{     $ErrorMessage = $_.Exception.Message     Write-Host $ErrorMessage } # # Connect to vCenters # $conns = connectvCenters $VCStringlist # # Generate Report about Idle sessions # $Allreport = Get-ViIdleSessions -vclist $conns -excluded (Get-Content "./excluded-users.txt") # # Terminate Idle Sessions # $choice = Read-Host "Are you sure you want to Terminate theses Sessions?(y/n)" if($choice -eq "y"){     Disconnect-ViIdleSessions -list $Allreport -vcs $conns     Write-Host "Sessions Disconnected" }else{     Write-Host "Sessions Maintained" }