Quantcast
Channel: VMware Communities : Discussion List - VMware PowerCLI
Viewing all 14549 articles
Browse latest View live

Get-OMResource - finding related items

$
0
0

Hi All,

 

We have vRealize Operations Manager and the Management Pack for vCloud Director. One of the things we're trying to get is the ORG_VDC_STORAGE_PROFILE data for particular ORG_VDC items. We can use Get-OMResource to find the resource kinds, but I can't see a method of finding the "Related Objects" (e.g. Get-OMResource -ResourceKind ORG_VDC -name MyOrgVDC, then find the ORG_VDC_STORAGE_PROFILE's related to that resource).

 

We are specifically looking to get the vRealize Operations Manager OMResource similar to getting them from Get-OMResource command (and specifically the stats related to these objects)

 

Anyone know how to do that if it's possible?


Move, Remove, or Copy an orphaned VMDK all result in a Flat file?

$
0
0

I'm working with a modified version of LucD's script to automate clearing down of orphaned VMDK files.

The script works as expected as far as mapping PSDrives to the locations and targeting the correct files specified.

 

The problem is using any of the cmdlets Move-Item, Remove-Item, or Copy-DatastoreItem all yield the same results:

 

A less than 1KB VMDK file is moved to the target location and a full sized Flat file is left in its place.

Once the small VMDK is moved back it replaces the flat file.

 

The VMDK files I'm targeting are verified as orphaned and can be moved manually using the Datastore Browser.

Is it possible to get New-Datastore to mount a datastore without explicitly specifying the path and nfs host info?

$
0
0

I have a script I'm trying to write, that for some reason I thought I had working before.  I basically am asking a user to connect to a vCenter, find a datastore they want to mount, list the available hosts, select a host and then mount it to that host.  However when I use this code:

 

New-Datastore -VMHost $esxhost -Nfs -Name $datastore.Name -Path $datastore.RemotePath -NfsHost $datastore.RemoteHost

 

It fails.  $esxhost is the host selected by the user and $datastore is the datastore previously selected by the user as well.  Is this possible or do we have to hard code in the path and nfshost info?

Using PowerCLI with Visual Studio (.Net VB)

$
0
0

Anyone know a  quick Dummys guide to getting PowerCLI to work with Visual Studio .Net VB?

Note, not looking to use C#.

 

Need how to's and example codes.

 

Thanks

PowerCli - Hide Password From Script

$
0
0

$PasswordFile = "\\xxx.xx\xx\xx\xx\xx xx\xx.txt"

$KeyFile = "\\xx.com\xx\xx\xx\xx xx\xx.key"

[Byte[]] $key = (1..16)

$vPassword = "xxxxx" | ConvertTo-SecureString -AsPlainText -Force

$vPassword | ConvertFrom-SecureString -key $key | Out-File $PasswordFile

[Byte[]] $key = (1..16)

Get-Content $PasswordFile | ConvertTo-SecureString -Key $key

 

After above i do below and i get error :

 

Connect-VIServer -Server xx.xx.x.xx -User xxx -Password $vPassword

 

Error:

Cannot complete login due to an incorrect user name or password.

PowerCLI not connecting to vCenter in another domain

$
0
0

Hi All,

I am facing an issue with powercli, one of the Vcenter with different domain is not connecting via powercli.

getting the below error.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Connect-VIServer : 7/17/2018 9:00:37 AM    Connect-VIServer        Could not

resolve the requested VC server.

Additional Information: There was no endpoint listening at

https://servername/sdk that could accept the message. This is often caused

by an incorrect address or SOAP action. See InnerException, if present, for

more details.   

At line:1 char:1

+ Connect-VIServer servername

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (:) [Connect-VIServer], ViServer

   ConnectionException

    + FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_NameR

   esolutionFailure,VMware.VimAutomation.ViCore.Cmdlets.Commands.ConnectVISer 

  ver

 

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 

I have already tried with get-powercliconfiguration and set-powercliconfiguration commands,.

but still no luck.

can someone help on this.

Datastore CapacityGB and FreeSpaceGB

$
0
0

Hi

I need the current capacity for a new infrastructure platform. But I can’t export the values for Datastore CapacityGB and FreeSpaceGB.

Hope someone can help me.

 

Here's the Script:

 

 

Connect-VIServer -server xxx -User xxx -Password xxx

$VMs = Get-Cluster -Name xxx | Get-VM

$Output = foreach ($VM in $VMs){

Get-VM $VM | select Name,

@{N=”Folder Name”;E={$_.Folder.Name}},

@{N=”Number vCPU”;E={$_.NumCpu}},

@{N=”vMem(GB)”;E={$_.MemoryGB}},

@{N=”CPU Usage(MHz)”;E={$_.ExtensionData.Summary.QuickStats.OverallCpuUsage}},

@{N=”Memory Usage(MB)”;E={$_.ExtensionData.Summary.QuickStats.GuestMemoryUsage}},

@{N=”Provisioned Space(GB)”;E={$_.ProvisionedSpaceGB}},

@{N=”Used Space(GB)”;E={$_.UsedSpaceGB}},

@{N=”Power State”;E={$_.PowerState}},

@{N=”ESXi Host”;E={$_.VMHost}},

@{N=”Cluster”;E={Get-Cluster -VM $_}},

@{N=”Datastore”;E={$_.ExtensionData.Config.DatastoreUrl.Name}},

@{N=”Datastore Capacity(GB)”;E={Get-Datastore -VM $_ | Select CapacityGB}}, -> doesn't work

@{N=”Datastore Free Space(GB)”;E={Get-Datastore -VM $_. | Select FreeSpaceGB}} -> doesn't work

#@{N=”DNSName”;E={$_.ExtensionData.Guest.Hostname}}

}

$Output | Export-Csv D:\Result.csv -NoTypeInformation

Best regards

Andi

Easy points - get list of virtualportgroups that start with "dv-vm-"

$
0
0

I need to get a list of all virtualportgroups from vCenter but filter only for the ones prefixed by "dv-vm-" and pipe it out to a text file.

 

Note, I am pretty new to PowerCLI so simple works best for me...…..lol

 

Thanks


'VMWare.VimAutomation.Core' is not installed on this computer

$
0
0

Hi,

I'm new in PowerCLI world and I need some help.

I'm getting the following error:

Add-PSSnapin : The Windows PowerShell snap-in 'VMWare.VimAutomation.Core' is not installed on this computer.

 

Usefull information from my computer:

PowerCLI Version:

----------------

   VMware PowerCLI 10.0.0 build 7895300

---------------

Component Versions

---------------

   VMware Cis Core PowerCLI Component PowerCLI Component 10.0 build 7893915

   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 10.0 build 7893909

 

$PSVersionTable:

Name                           Value

----                           -----

PSVersion                      5.1.16299.251

PSEdition                      Desktop

PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

BuildVersion                   10.0.16299.251

CLRVersion                     4.0.30319.42000

WSManStackVersion              3.0

PSRemotingProtocolVersion      2.3

SerializationVersion           1.1.0.1

Check if disks are 'Indipendent'

$
0
0

Hello, I would like to extract (csv file) some parameter about disks from a list of vm (txt),

From this base:

 

Get-VM |Select Name,VMHost | Where-Object {$_.name -like "*vm1*" } | Export-Csv -Path C:\Users\gemela\Desktop\vm_info.csv -NoTypeInformation -UseCulture

 

I would like to get: Disk and info about Virtual Device Node, If there are setting to be Independent , Persistent or NonPersistent

 

Thanks

Script to get NSX Edge and Organization in csv

$
0
0

Hi,

 

I'm trying to put a script together to export the nsx edges (name, version) to their organization in csv format so, it will be easier to see which edges need to be upgraded based on the organization.  I was able to get all the edges and their version but, having issues linking it to the organization.  Can't seem to link the tenant and organization id's.  This is what i have so far.  Any assistance would be great.

 

Connect-ViServer -Server $vcenter

$reportPath = "C:\temp\upgradable-VSEs.csv"

$report = @()

 

$edges = Get-View -ViewType virtualmachine -Property Name,Config -Filter @{'Config.VAppConfig.Product[0].Name'='vShield Edge'} | % {

$edge = '' | Select 'Name','Version'

$edge.Name = $_.Name

$edge.Version = $_.config.vappconfig.product[0].version

$report += $edge

}

 

$APIendpoint = "$myendpoint"

$mysessionid = ($global:DefaultCIServers | Where { $_.Name -eq $APIendpoint }).SessionId

$Headers = @{"x-vcloud-authorization" = $mysessionid; "Accept" = 'application/*+xml;version=' + '27.0'}

$headers2 = @{"Accept"="application/*+xml;version=27.0"; "Authorization"="Basic $base64_decode"}

$Request = "https://$APIendpoint/api/org/"

$r = Invoke-RestMethod -Uri ($Request) -Headers $Headers -ContentType "application/xml"

 

$orgs = search-cloud -QueryType Organization (can get org id from this list)

 

(guess i need a foreach loop here which will loop through each edge and match the edge tenant id with the org id from the query above but, not sure where to get tenant id in the edge to match org id)

 

$report | Export-Csv -Path $reportPath -NoTypeInformation -UseCulture

 

How would i go about linking the edges to their org?  Sorry, fairly new to scripting.

 

Thanks,

-b

Advanced Setting comparator function?

$
0
0

/cc LucD

 

I'm wondering if you (Luc) or anyone else has ever seen or made an ESXi advanced setting comparator function. What I'd like to produce (if no one has done it) is to write a script or function which takes a compute cluster as an input object, loops through all the advanced settings on each host gathering the names of the settings and their values, compares them with all the other hosts, and displays a list of those (either name OR value) which differ from the cluster.

 

For example, let's say I wanted to ensure that Net.TcpipHeapSize was consistent at 32 across all hosts in a given cluster. I could dump out the settings of each host and line them up in some sort of view to determine that for myself, but what would be much more helpful is if I could just get told "these are the ones which aren't the same" followed by which host(s) are the odd ball and what that devious setting is. Anyone done/seen this done?

function_structure

$
0
0

Hi Luc,

 

could you check following  when i am running as ps1 i get all three parameters in commnd

 

like below

 

 

however when i convert it to module and then run i dont get all parmeters option only entity is avaliable from command .

 

 

 

 

function Get-logs

 

{

 

    [cmdletbinding()]

 

    param (

 

        [parameter(mandatory = $true,

 

            valuefrompipeline = $true,

 

            valuefrompipelinebypropertyname = $true)]

 

        [string]$vcenter,

        [string]$entity,

        [string]$targetPath

 

       

       

 

    )

   

 

 

 

 

 

 

 

 

 

$cred = Get-Credential

 

connect-viserver -Server $vcenter  -Credential $cred | Out-Null

 

 

#$targetPath = read-host "please provide path"

# "c:\users\in0079d6\desktop\Technicolor_script\logs"

 

 

Try{

    $target = Get-Item -Path $targetPath -ErrorAction stop

}

Catch{

    $target = New-Item -ItemType Directory -Force -Path $targetPath

}

 

if((Get-VM -ErrorAction SilentlyContinue).Name -contains $entity){

    Write-Host "It's a VM" -ForegroundColor Yellow

    $vm = Get-VM -Name $entity

    $ds = Get-Datastore -RelatedObject $vm

    New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root '\' | Out-Null

    #Get-ChildItem -Path DS:\

    Set-Location DS:\

    cd $vm

    #Get-ChildItem vmware.log

    Copy-DatastoreItem -Item vmware.log -Destination $targetpath

    Remove-PSDrive -Name DS -Confirm:$false

}

elseif(((Get-VMHost).Name | %{$_.Split('.')[0]}) -contains $entity){

    Write-Host "It's an ESXi" -ForegroundColor Green

    #specify domain starting with "."

    $domain=Read-Host "specify domain"

    $log_type=Read-Host "specify log type"

    $esxi_name = "$($entity).$($domain)"

    $esxi_name

    $esxi=get-vmhost $esxi_name

    $res1=Read-Host "do yu need log bundle""y/n"

    if($res1 -eq 'y')

    {

        Write-Host "generating log bundle" -ForegroundColor DarkCyan

        Get-Log -VMHost $esxi -Bundle -DestinationPath $target.FullName

    }

    elseif($res1 -eq 'n')

    {

        Write-Host "......."

        $allCondition = Read-Host -Prompt "Should all substrings appear (y/n)?"

        $strings = @()

        do {

            $answer = Read-Host -Prompt "Enter a substring (blank to end)"

            if($answer){

                $strings += $answer

            }

        } until ($answer -eq '')

        if($allCondition -eq 'y'){

            $regexStr = ($strings | %{"(?=.*$_)"}) -join ''

            $regexStr = ".*$($RegexStr).*"

        }  

        else{

            $regexStr = $strings -join '|'

        }

        Get-Log -VMHost $esxi  -key $log_type | Select -ExpandProperty Entries |

            where{$_ -match $regexStr} |

            #Out-File -FilePath "$($target.FullName)\$($esxi_name)-vmkernellog_match.txt"

            out-file -FilePath $targetPath\$esxi_name-vmkernellog_match.txt

 

    }

}

 

 

$res2=read-host "do yu need full log file without mataching expresions"

if($res2 -eq 'y')

{

 

write-host "generating" $log_type "log file"

get-log -VMHost $esxi -Key $log_type | select -ExpandProperty entries|out-file $targetPath\$esxi_name_$log_type.txt

 

 

}

Disconnect-VIServer -Server "*" -Force -Confirm:$false

}

Invoke multiple vcenters from rvtoolsbatch

$
0
0

Hi guys,

 

Can you please help how i can be possible called upon multiple vCenters from rvtoolsbatch and will send all it all as different attachment but in a single mail?

 

From what i read on rvtools documentation, it was suggesting to use a colon as a separator, but i couldnt get like what i want to have and Keep getting error Unhandled exception: Invalid URI: The hostname could not be parsed.

 

I can write multiple lines to invoke multiple vcenters and send email or attachment likewise, but that would beat a purpose as i wanted to have all rvtools report of all vcenters in a single email.

 

Please help.

 

Cheers

patch_esxi_function

$
0
0

Hi Luc ,

 

few days back we discussed about patching esxi using powercli .

 

i am trying to convert that to function so that it can be added to module to make it monolithic.

 

 

however i have few questions related to colred lines (blue,green,red)

1:if i dont save these three in variables(and run commands without storing them in variables) will it cause any issues .?

2:also i dont want to use  -runasync switch or sleep  and then use do untill loop for getting counter .because once blue is completed then it will proceed to green and then to red .

do you think this code will work fine looping from one esxi host to finish patch, reboot and proceeding to next.

 

 

sorry if i asked this previously.

 

 

 

 

 

function Patch-Esxi

   {

     [cmdletbinding()]

 

    param (

 

        [parameter(mandatory = $true,

 

            valuefrompipeline = $true,

 

            valuefrompipelinebypropertyname = $true)]

 

        [string]$clustername

 

    )

 

 

   if((get-module).name -notcontains "vmware.vumautomation")

 

 

   {

   Import-Module -Name VMware.VumAutomation

 

   $cluster=get-cluster -Name $clustername

   $patch=Get-Baseline -BaselineType Patch -Name "TBD"

 

   foreach($esxi in (get-vmhost -Location $cluster))

   {

 

 

  $maint = Set-VMHost -VMHost $esxi -State Maintenance -WhatIf

 

   $AtBL=Attach-Baseline -Entity $esxi -Baseline $patch -WhatIf

$update_esxi=Update-Entity -Baseline $patch -Entity $esxi -WhatIf

 

 

 

 

   }

 

   }

 

 

 

 

 

below is what we did last time to get percentage of maint mode operation but wht i observed that there is counter for powercli commnds .only thing is that it works sometime .

 

 

   <#

 

   Do

 

  {

 

    Write-Host -NoNewline '.'

 

    sleep 1

 

    $esxi = Get-VMHost -Name $esxi.name

 

  } until ($esxi.State -eq "maintenance" -and $maint.PercentComplete -eq 100)

 

Write-Host "`rDone"

 

Write-Output "Task '$($maint.Description)/$($maint.Id)' for $($maint.Result.Name) ended with status $($maint.State)"

 

 

 

 

#>


VMs Disk Usage Report

$
0
0

I got a script that work but want to include a subtotal for each VM and not sure how to insert/add a subtotal line at end of each VM.  The output report will be in CSV.

 

Any help will be greatly appreciated.

 

$FinalResult = @() 

$ALLvms = Get-View -ViewType "VirtualMachine"

$allvms | foreach-object {

       $vm = $_

       $vmname = $vm.name

       $Drives = $vm.Guest.Disk

       $drives  | foreach-object {

            $driveC = $_

            $object = New-Object -TypeName PSObject

            $Capacity = "{0:N0}" -f [math]::Round($DriveC.Capacity / 1MB) 

            $Freespace = "{0:N0}" -f [math]::Round($DriveC.FreeSpace / 1MB)

            $Percent = [math]::Round(($FreeSpace)/ ($Capacity) * 100)

            $PercentFree = "{0:P0}" -f ($Percent/100)

            $object | Add-Member -MemberType NoteProperty -Name "Server Name" -Value $vmname

            $object | Add-Member -MemberType NoteProperty -Name Disk -Value $Drivec.DiskPath

            $object | Add-Member -MemberType NoteProperty -Name "Capacity MB" -Value $Capacity

            $object | Add-Member -MemberType NoteProperty -Name "Free MB" -Value $FreeSpace

            $object | Add-Member -MemberType NoteProperty -Name "Free %" -Value $PercentFree

            $finalResult += $object

        }  

    }

$finalResult | Export-Csv "C:\DiskUsageReport.csv" -NoTypeInformation  -UseCulture    # dump the report to .csv

How to restart vshield-endpoint-mux via powercli?

$
0
0

I have an open ticket with VMWare. They are stumped! We have vm's that are disconnecting because the host is causing all the guest o flap the VSEPLFT from connected to disconnected... If I could somehow script :

/etc/init.d/vShield-Endpoint-Mux start/stop/restart

 

Via PowerCLI to run on all hosts in a cluster that would be great! I am having some difficulty today searching, and running out of ideas I have tested a few different ideas with no success.

The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

$
0
0
I have scripts to clone multiple vms in one folder one by one. it was working perfectly on vsphere environment 5.5. However after we upgrade to 6.5, it sometime gives me an error and quit. Would high appreciate if someone can help. the error message is: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

Remove-VMHostNtpServer not removing anything.

$
0
0

I'm trying to PowerCLI up our configuration for some standalone (non-clustered) ESXi hosts, and I'm having an issue where Remove-VMHostNtpServer doesn't actually remove anything.

 

After importing the PowerCLI modules and connecting to the ESXi host I want to reconfigure, I run the "Remove-VMHostNtpServer" cmdlet with one of the ntp servers I want to remove, see the "update time config" task return a "completed successfully" result in the webclient... but the old NTP servers are not removed, even after a long wait (~30 mins), and restarting the ntp daemon:

 

ESXINTP.png

 

PowerShell console output, for better readability:

 

PS C:\WINDOWS\system32> Get-VMHostNtpServer -VMHost $ESXiServer -Server $ESXiServer;
pool.ntp.org
us.pool.ntp.org

PS C:\WINDOWS\system32> Remove-VMHostNtpServer -NtpServer 'pool.ntp.org' -VMHost $ESXiServer -Server $ESXiServer -Confirm:$false;

PS C:\WINDOWS\system32> Get-VMHostNtpServer -VMHost $ESXiServer -Server $ESXiServer;
pool.ntp.org
us.pool.ntp.org

 

Anyone have any idea about what's going wrong, how to correct it, or even troubleshoot it?

 

I'm running this from PowerShell (ISE) 5.1.16299.431, PowerCLI 10.1.0.8403314 (Though, I'd had the same non-results on PowerCLI 6.5.0 something, and upgraded in hopes of fixing it) against an ESXi host running ESXi 6.5.0 Update 2 (Build 8294253).

shutdown-vmguest and set cpu and mem

$
0
0

will this work?

have not had a chance to test

 

$vms = get-vm -name (get-content vms.txt)

foreach ($vm in $vms) {

get-VM -name $vm | Shutdown-VMGuest -Confirm:$false

if ($VM.PowerState -eq "PoweredOn") {

   Write-Host "Shutting Down" $VMName

   Shutdown-VMGuest -VM $VM

   #Wait for Shutdown to complete

   do {

      #Wait 5 seconds

      Start-Sleep -s 5

      $status = $VM.PowerState

   }until($status -eq "PoweredOff")

}

$vm | Set-VM –MemoryGB 8 –NumCpu 2 –Confirm:$False

$vm  | Start-VM

}

Viewing all 14549 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>