Giter Club home page Giter Club logo

powercli-example-scripts's Introduction

PowerCLI Community Repository

Principles of Operations

Table of Contents

Abstract

This document will serve for collaboration to identify the operating principles of a centralized PowerCLI Community Repository on GitHub.

The central PowerCLI repo will be located at: https://github.com/vmware/PowerCLI-Example-Scripts

Content Restrictions

Type of Content

The repository has been provided to allow the community to share resources that leverage VMware’s PowerCLI. This can include:

  • Sample Scripts
  • Modules
  • DSC Resources
  • PowerActions scripts
  • Pester Tests
  • Tools built with PowerShell

Getting Started

Accessing the Repository

Downloading the Repository for Local Access

  1. Load the GitHub repository page: https://github.com/vmware/PowerCLI-Example-Scripts
  2. Click on the green “Clone or Download” button and then click “Download ZIP”
  3. Once downloaded, extract the zip file to the location of your choosing
  4. At this point, you now have a local copy of the repository

Creating Your Own GitHub Based Access Point

  1. Login (or signup) to GitHub
  2. Load the GitHub repository page: https://github.com/vmware/PowerCLI-Example-Scripts
  3. Click on the Fork button, which will create a copy of the repository and place it in the GitHub based location of your choosing.

Adding Resources

GitHub - Copy/Paste Option

  1. Browse to the appropriate section (example: Scripts)
  2. Select the “Create new file” button
  3. On the new page, enter a file name, enter the resource’s information
  4. Within the “Commit new file” area, enter the title and description, then select “Create a new branch for this commit…” and enter a sensible branch name
  5. Click “Propose new file”
  6. On the “Open a pull request” page, click “Create pull request”

GitHub - Upload files Option

  1. Browse to the appropriate section (example: Modules)
  2. Select the “Upload files” button
  3. On the new page, drag or choose the files to add
  4. Within the “Commit changes” area, enter the title and description, then select “Create a new branch for this commit…” and enter a sensible branch name
  5. Click “Propose new file”
  6. On the “Open a pull request” page, click “Create pull request”

Meta Information

This section will provide guidance on information which should be included with each submitted PowerCLI resource. Information listed in the Suggested Information will not be required for commit of a pull request to the repo, but will certainly increase ease of use for users of the resource.

Pull Request Requirements

To comply with VMware's Client License Agreement (CLA), each commit in a Pull Request requires a sign-off acknowledging the Developer Certificate of Origin (DCO) https://cla.vmware.com/dco before your changes are merged. Your commit should be in the following format:

The body of your commit message
Signed-off-by: John Doe <[email protected]>

The text can either be manually added to your commit body, or you can add either -s or --signoff to your usual git commit commands. The e-mail address used to sign must match the public e-mail address of the Git author.

git commit --signoff --message 'This is my commit message'

DCO-Required error

If you have authored a commit that is missing the signed-off-by line, you can amend your commits and push them to GitHub with the following:

git commit --amend --signoff

If you've pushed your changes to GitHub already, you'll need to force push your branch after this with:

git push -f

Required Information

The following information must be included with each submitted scripting resource. Please include the information in the appropriate location based upon the submitted scripting resource.

  • Author Name
    • This can include full name, Twitter profile, or other identifiable piece of information that would allow interested parties to contact author with questions.
  • Date
    • Date the resource was written
  • Minimal/High Level Description
    • What does the resource do
  • Any KNOWN limitations or dependencies
    • vSphere version, required modules, etc.

Note Placement Examples:

Script: Top few lines
Module: Module manifest

Required Script Note Example:

<#
Script name: script_name.ps1
Created on: 07/07/2016
Author: Author Name, @TwitterHandle
Description: The purpose of the script is to …
Dependencies: None known
#>

Suggested Information

The following information should be included when possible. Inclusion of information provides valuable information to consumers of the resource.

  • vSphere version against which the script was developed/tested
  • PowerCLI build against which the script was developed/tested
  • PowerShell version against which the script was developed/tested
  • OS platform version against which the script was tested/developed
  • Keywords that make it easier to find a script, for example: VDS, health check

Suggested Script Note Example:

<#
Script name: script_name.ps1
Created on: 07/07/2016
Author: Author Name, @TwitterHandle
Description: The purpose of the script is to …
Dependencies: None known

===Tested Against Environment====
vSphere Version: 6.0
PowerCLI Version: PowerCLI 6.3 R1
PowerShell Version: 5.0
OS Version: Windows 10
Keyword: VM
#>

Suggested Quality Management

This section describes guidelines put in place to maintain a standard of quality while also promoting broader contribution.

General Best Practices

Resource Naming

  • Give the resource a name that is indicative of the actions and/or results of its running

Fault Handling

Alias Usage

  • Avoid any alias usage within all submitted resources.

Global Variable Usage

  • Avoid changing any global variables

Help Information

  • All resources should have inline documentation.

Scripts

  • The script should be easy to read and understand
  • Place user-defined variables towards the top of the script

Modules

  • The module file, PSM1, should contain only functions. A module manifest file, PSD1, should also be created and included. A module formatting file (format.ps1xml) is desirable but not a requirement.
  • Use only standard verbs

Security

  • Usage of PowerShell’s strict mode is preferred, but not required.
  • Remove any information related to one’s own environment (examples: Passwords, DNS/IP Addresses, custom user credentials, etc)

Resource Maintenance

Maintenance Ownership

Ownership of any and all submitted resources are maintained by the submitter. This ownership also includes maintenance of any and all submitted resources.

Filing Issues

Any bugs or other issues should be filed within GitHub by way of the repository’s Issue Tracker.

Resolving Issues

Any community member can resolve issues within the repository, however only the owner or a board member can approve the update. Once approved, assuming the resolution involves a pull request, only a board member will be able to merge and close the request.

Additional Resources

Discussions

Join in on the discussion within the VMware Code Slack team's PowerCLI channel: https://code.vmware.com/slack/

VMware Sample Exchange

It is highly recommended to add any and all submitted resources to the VMware Sample Exchange: https://developercenter.vmware.com/samples

Sample Exchange can be allowed to access your GitHub resources, by way of a linking process, where they can be indexed and searched by the community. There are VMware social media accounts which will advertise resources posted to the site and there's no additional accounts needed, as the VMware Sample Exchange uses MyVMware credentials.

VMWARE TECHNOLOGY PREVIEW LICENSE AGREEMENT

The VMware Technology Preview License Agreement: https://github.com/vmware/PowerCLI-Example-Scripts/blob/master/LICENSE.md

Repository Administrator Resources

Table of Contents

  • Board Members
  • Approval of Additions

Board Members

Board members are volunteers from the PowerCLI community and VMware staff members, board members are not held responsible for any issues which may occur from running of scripts inside this repository.

Members:

  • Josh Atwell (Community Member)
  • Luc Dekens (Community Member)
  • Jonathan Medd (Community Member)
  • Alan Renouf (VMware)
  • Kyle Ruddy (VMware)
  • Rynardt Spies (Community Member)

Approval of Additions

Items added to the repository, including items from the Board members, require a review and approval from at least one board member before being added to the repository. The approving member/s will have verified for a lack of malicious code. Once an “Approved for Merge” comment has been added from a board member, the pull can then be committed to the repository.

powercli-example-scripts's People

Contributors

aaronwsmith avatar abidlen avatar alanrenouf avatar baoyinqiao avatar blackms avatar bwuch avatar cajunbard avatar community-vsphere-tag avatar crlogic avatar ctolan avatar desrosim232 avatar dmilov avatar dzl84 avatar geo-ron avatar isjwuk avatar jrodsguitar avatar kamennikolov avatar kmruddy avatar lamw avatar lucdekens avatar magneet avatar mallocarray avatar mr-uptime avatar mtelvers avatar praveenmathamsetty avatar qlikq avatar simonfangyingzhang avatar tlindsay42 avatar vkg1215 avatar vmarkusk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powercli-example-scripts's Issues

vCware.Alarms

This is a great module, my current issue with vcenter 6.5 it the reporting frequency being set to 5 minutes by default, and vmware seems to have no easy way to fix it, your module allows me to set it to 0, the only issue I am having at the moment is the entity, I cannot find a way to enter a folder under the VMs and Templates for -Entity, can you please tell me if there is a way around this in your module?

User Entitlement to the pool for New-HVpool

Hi,

I am using New-HVPool function to create a manual pool. Pool is created successfully, but how do I provide user Entitlement to the pool? I see there is a parameter named 'GlobalEntitlement', but I dont think it has been used anywhere in the function. Can you please let me know how we can add an user to the pool either using the same New-HVPool function or through any other function?

New-HVPool

Hello,

I have been trying to use the advanced function to create a new pool. Whenever I try to run my script with the parameters from the psm1 file, I get the error "Failed to create pool with error: No hostOrCluster found with Name: [cbgesx01]". When I run a simple line of code to see all the host available in the particular datacenter, it shows cbgesx01 as being part of the datacenter. What is causing the function not to find the host?

New-HVPool -ReusePreExistingAccounts:$true

New-HVPool -ReusePreExistingAccounts:$true does not work.

I can see where $reusePreExistingAccounts is set from $jsonObject on line 4170, but the spec doesn't appear to be updated from the variable after line 4444. It is probably my misunderstanding because I don't see anything from customizationSettings, viewStorageAcceleratorSettings, virtualCenterStorageSettings, or virtualCenterNetworkSettings.

-ReusePreExistingAccounts is also missing from the function documentation.

Name add-hvdesktop

shouldn't this be named add-hvmachine since it's about a single machine to be added to a desktop pool. there's already get-hvmachine and set-hvmachine so to keep in line with this imho the default name should be add-hvmachine with add-hvdesktop as an alias for backwards compatibility

VMware.VMC module only lists firts 20 Logical networks

The Function Get-VMCLogicalNetwork
os calling the VMC service as described below.

$logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical

in the GUI we see more then 20 logical networks available. The above only results in a table of only the 20 first created networks.

2018-03-12_18-58-35
2018-03-12_18-58-19
gert

New-HVPool -datastores

Hey guys, I have been trying all day to figure out how to specify more than one Datastore in New-HVPool cmdlet.
I have no problem with one..... New-HVPool -Datastores "SEN-Example"
But How I can achieve command with two datastores? I tried:
-Datastores "SEN1,SEN2"
-Datastores "SEN1[0],SEN2[1]"
....and many others combinations. I haven't found any explanation in Detailed help so I don't know where to look more.

Can you help me with this?
Thanks!

Connect-HVserver provides cert issue

Using powercli 6.5 I cannot connect against a Horizon 6.0.1
However script works against 6.2.1

Seems like a cert issue, but cannot fix it. Anybody with an idea?

######################Script###################
$hostvar = $args[0]
$hzUser = $args[1]
$hzPass = $args[2]
$hzDomain = $args[3]
#Import-Module VMware.VimAutomation.Sdk
Import-Module VMware.VimAutomation.HorizonView
$hvServer = Connect-HVServer -server $hostvar -User $hzUser -Password $hzPass -Domain $hzDomain

####################Error####################

Connect-HVServer : Could not establish secure channel for SSL/TLS with authority 'xxxxxx'

VAMI Module - get-vamihealth - standard user

I am looking to query VCSA 6.5 VAMI health but have found that only users with admin rights to the vCenter can pull this info. Is there any way to add permissions to a standard user to allow this data to be pulled via API?

get-hvmachine & get-hvmachinesummary maximum 1000 results

When I do a get-hvmachine or get-hvmachinesummary from the vmware.hv.helper the maxiimum output count is 1000. This is not enough since pools and complete environments can get way bigger then that. It seems to be caused by the queryservice only giving 1000 results as well.

$hvServer1 = Connect-HVServer -Server CONNECTIONSERVER
$Services1= $hvServer1.ExtensionData
$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.limit= 9999
$defn.startingOffset = 20
$defn.maxpagesize = 9999
$defn.queryEntityType = 'MachineNamesView'
$QueryResults = $queryService.queryservice_create($Services1, $defn)
($queryresults.results).count

this always maxes out at 1000 results. If I set the startingoffset to 800 I get 303 results

get-hvmachine on empty pool exits all scripts

I have a simple script like this (modules are already loaded) that I am using as a base to catch all vdi desktops based on a different then the default snapshot

$pools=(get-hvpool)
write-output "All pools"
$pools.base.name
foreach ($pool in $pools){
$poolname=$pool.base.name
if ($pool.type -like "*automated*"){
write-output "Checking pool:"
$poolname
$poolmachines=get-hvmachine ($pool.base.name)
$wrongsnap=$poolmachines | where {$_.managedmachinedata.viewcomposerdata.baseimagesnapshotpath -notlike  $pool.automateddesktopdata.VirtualCenternamesdata.snapshotpath}
write-output "Desktops based on wrong snapshot:"
$wrongsnap.base.name
}
}

This scripts gives a nice message for empty pools:

VDI_Pool95

No Virtual Machine(s) Found with given search parameters

But the script halts with this after any pool that doesn't contain any desktops. I have attached a screenshot of the output:
2017-04-19 10_21_5
(VDI_Pool99 actually contains a desktop based on a different snapshot)

create remove-hvmachine

there's a way to add a machine to a manual pool but not a way to remove them (for example to add them to another connection broker)

this can easily be done like this:
$services1.desktop.Desktop_RemoveMachineFromManualDesktop((get-hvpool -poolname POOLNAME).id, (get-hvmachine -machinename MACHINENAME).id)

Set-AdvancedSetting failure

I'm seeing the following error when attempting to set an advanced setting. This is on ESXi 6.5u1.

A specified parameter was not correct:. Operation failed, diagnostics report: /etc/vmware/esx.conf: read failed: esx.conf parser
-- 7, 44): forward slash expected
FullyQualifiedErrorId : Client20_SystemManagementServiceImpl_GetVmHostAdvancedConfiguration_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetAdvancedSetting

I'm specifically seeing this on the following advanced settings:

  • UserVars.ESXiShellInteractiveTimeOut
  • UserVars.ESXiShellTimeOut
  • Net.BlockGuestBPDU

Doesn't seem to matter if i format the change value as a string or int.

The code i'm running is pretty simple:
$VMhost | Get-AdvancedSetting -Name $AdvancedSetting | Set-AdvancedSetting -Value $AdvancedSettingDesiredValue -Confirm:$false | Out-Null
The "$AdvancedSettingDesiredValue" data is pulled from the ESXi hardening guide that I converted to a CSV.

Set-HVApplicationIcon

Hi,
regarding "Customizing Horizon RDSH Application Icons" https://www.youtube.com/watch?v=CWRGJhNVjPo

...after downloading/installing 6.5 R1 PowerCLI via Gallery on Windows Server 2012R2 and import the hv.helper module from github, i still do not get the Set-HVApplicationIcon commands..how do i fix this?

regards
René

groupfilter breaks get-hventitlement

Always when grabbing an entitlement the groupfilter is added (lines 8021-8023) this should only be the case if the type equals group. Right now this breaks almost everything except when the entitlement from a group is needed.

need help about esxi-image-creator.ps1

Hi All, I want to use esxi-image-creator.ps1 to build ESXi installer but I got erroe while I tried to create the esxi installer.

My command like this:

.\esxi-image-creator.ps1 -NewProfileName HP_55_OEM_550P6 -WriteZip -Files "VMware-ESXi-5.5.0-Update3-3568722-HPE-550.9.6.5.9-Dec2016-depot.zip","ESXi550-201512001.zip","BCM-NetXtremeII-11.0-2371150.zip","hpsa-5.5.0.84-2338296.zip","nx_nic-esx55-5.5.643-2719295.zip","scsi-iomemory-vsl-55L-3.2.15.1699-5351975.zip","VMW-ESX-5.5.0-qlnativefc-1.1.70.0-3659120.zip","VMW-ESX-5.5.0-qlnativefc-1.1.77.0-4679253.zip"

Error as below:

The following VIBs will not be included in HP_55_OEM_550P6:
tools-light
Custom image profile HP_55_OEM_550P6 not created.
The command has stopped,because Preference variable "ErrorActionPreference" or Common Parameters set to Stop: VIB Intel_bootbank_intelcim-provider_0.5-1.8's acceptance level is accepted, which is not compliant with the ImageProfile acceptance level certified

I have checked $ErrorActionPerference is continue and tried to add the -ErrorAction continue at the trail of the script but still got error.

Would anyone can help?
my email is [email protected]

ScriptOutput is appending \r \n to the value.

ScriptOutput is appending \r\n to the $status variable, returned from Invoke-VMScript.
Sample :
$status = get-vm -Name $vmname | Invoke-VMScript -ScriptText $scriptText

$a = "test"
It "Shoudl Match" {
$status.ScriptOutput | Should be $a
}

Output :
Expected: {test}
But was: {test\r\n}

Json for rebalance prep

Hi,
i have to migrate all my pools to a new storage, so have to reconfigure all the datastores (os disk, persistent and replica separatelly) to new ones, it possible to use set-hvpool with json file to do that? If yes can you please provide an example?
Thanks a lot

New-HVPool - vCenter Server not found

Attempting to create a new Instant Clone (v7.3.1) pool in a multi vCenter environment using New-HVPool. Command is aware that multiple vCenters exist but I not certain of of what needs to be inputed.

Error:
Get-VcenterID : vCenter Server not found: [vCenterServerName], please make sure vCenter is added in Connection Server
At C:\Program Files\WindowsPowerShell\Modules\VMware.HV.Helper.psm1:4461 char:32

  • ... virtualCenterID = Get-VcenterID -services $services -vCenter $vCenter
  •                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-VcenterID

If I do not specify a vCenter then this error message is received:
Get-VcenterID : Multiple Vcenter servers found, please specify the vCenter Name
At C:\Program Files\WindowsPowerShell\Modules\VMware.HV.Helper.psm1:4461 char:32

  • ... virtualCenterID = Get-VcenterID -services $services -vCenter $vCenter
  •                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-VcenterID

Run cmdlet against multiple $hvServers at once

Hey guys,

we are oftenly running queries against multiple environments.
For example we have a script that should run set-hvmachine -machinename $vm -maintenance ENTER_MAINTENANCE_MODE against all servers in $hvServer.

Now i see that in one of the lines it does this:
$machines = get-hvmachinesummary -machinename $machinename -suppressinfo $true -hvserver $hvServer which basically only uses $hvServer[0]

Is there an easy fix to run this against all servers that are connected?
I am not good enough to hack this myself, maybe someone else found a solution already.

Thanks!

add-hvdesktop generates error with same name vm's on vcenter

not mine but got it from the Code slack powercli channel:
add-hvdesktop generates error when on the vcenter a desktop is added on 2 vm's with the same name exsist. These don't have to be the vm that is being added. Adding of the desktop does work though.
it's an error at line 354 screenshot: https://drive.google.com/file/d/1FqH-NRTub5EmXROvFF2DeOyNVzFIRjvE/view?usp=sharing
the problem is that Get-MachinesByVCenter function generates a list of all vm's and compares the list the user enters as a parameter to this. imho this should be replaced with a query for each of the vm's the user gives so this at least only will happen if the vm being added itself is double in vcenter

get-hvmachinesummary shows duplicate entries

Hi all,

I am using the problemdesktop script, to schedule the script and restart the problem desktops. I am still testing the script with our environment.
Since two days, when I try to use get-hvmachinesummary command it show more problem desktops than usual that shows in view administrator.

When I checked the individual desktop it shows connected by user without any issue but, when I run the get-hvmachinesummary command with state agent_unreachable it shows the working machines too.

When I use the qurieing the individual machine with get-hvmachinesummary -machine 'name'.
Strange it showed two entries of the machine, one is available status and other is agent_unreachable with different user assigned.
Can you help me with this status, I feel the old entries are still shown up.

Regards,
Naveen. S

Set-HVPool vs Update-AutomaticLinkedClonePool

I used the commands below in a Horizon View 6.x environment to update pools using Multi-Vlan.
With the upgrade to Horizon View 7.3.1 and PowerCLI 6.5 R1 (including VMware.HV.Helper) these scripts no longer work.

I have not succeeded in realizing this with "Set-HVPool"
Any help is welcome

Update-AutomaticLinkedClonePool -Pool_id MyPool -NetworkLabelConfigFile "c:\PowerShell\NetLabel.txt" -ParentVmPath $ParentVM -ParentSnapshotPath $Snapshot

Create a folder for each of the module files to live in

Wanted to start a discussion about getting all of the individual .psm1 module files in /Modules into their own folder. My current dilemma is dealing with automatically injecting them into a Windows Container build. Since four of the modules have directories, but the remainder are just .psm1 files, I'm having to jump through an extra hoop to to create the folders (much like in /Scripts/modules.sh).

Just looking for a streamlined experience.

If we can come to a consensus, I don't have an issue submitting a PR. 🍻

New-HVPool with .json spec throws exception: No datastore found with Name: []

When I'm trying to create new instant clone pool with JSON spec, exception occurs:

 New-HVPool : Failed to create Pool with error: No datastore found with Name: []
 At C:\Powercli\HVPool_JSON.ps1:140 char:9
 +         New-HVPool -Spec $configPath -WhatIf
 +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
     + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,New-HVPool

In JSON file I have following:
"VirtualCenterStorageSettings": {
"Datastores": "SHD3_TestLUN",

So I can't get why datastore name returns null value.

Create get-hvuser and/or create assign-hvmachine

To entitle a user to a manual machine the advanced option for base.user needs to be set with the base.name value from aduserorgroupsummaryview besides creating the query yourself there's no way to do that now
I have done it manually like this:
$username="username"
$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'ADUserOrGroupSummaryView'
$defn.filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='base.name'; 'value' = $userName}
try {
$userid=($queryService.queryservice_create($Services1, $defn)).results[0].id
}
catch {
throw "Can't find $Username, exiting"
}

and feed that to get-hvmachine -machinename machinename| set-hvmachine -key base.user -Value $userid

this imho should receive an own command for it, also with get-hvuser all entitlements could be shown over desktops and applications for that user

Set-HVPool key and value

Hi,
I'm trying to automate my new pool creation with the following:

First clone and disable the pool (this code is working):
Get-HVPool -PoolName 'Test' | New-HVPool -PoolName $name -NamingPattern "$short-{n:fixed=3}" Set-HVPool -PoolName $name -Disable

Then I need to change keys maxNumberOfMachines and ResourcePool, i'm using this:
Set-HVPool -PoolName $name -key 'AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.maxNumberOfMachines' -value $maxvdi Set-HVPool -PoolName $name -key 'AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.ResourcePool' -value $short

but have this error:

Exception calling "Desktop_Update" with "3" argument(s): "ExceptionType : VMware.Hv.InvalidArgument
ErrorMessage : Invalid member name.
ParameterName : AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.maxNumberOfMachines"
At C:\Program Files\WindowsPowerShell\Modules\VMware.Hv.Helper\VMware.HV.Helper.psm1:4329
char:7
       $desktop_helper.Desktop_Update($services,$item,$updates)
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
 FullyQualifiedErrorId : VimException

Can someone please help me?
Thanks

Confirm parameter in New-HardDisk

If we execute "New-HardDisk -vm <vm_name> -datastore <ds_name> -capacityGB ", it wont't ask us about the confirmation even though we didn't mention -confirm as $false.

ex:
PS C:> New-HardDisk -VM Win_1 -Datastore DS_OSDrive_16 -CapacityGB 1

CapacityGB Persistence Filename


1.000 Persistent [DS_OSDrive_16] Win_1/Win_1.vmdk

Backup-VCSAToFile error handling for $BackupAPI.create() not working as intended

Line 75 in Backup-VCSA.psm1 is attempting to write an error message with the exception message from the $BackupAPI.create() call.

But instead of displaying the exception message and halting (with default $ErrorActionPreference), you get a vague "Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown." instead. Additionally since Write-Error is non-terminating, the code continues to try and show progress/status with a null $BackupJob variable and additional error messages are thrown.

Changing the line as follows fixes both problems.

throw $_.Exception.Message

I'm hoping to submit a PR with this fix and one more shortly.

VCHA.psm1 Enhancement

Can you please add a module for Set-VCHAMaintenance $true/$false/etc to be able to use powercli module to put a VCHA cluster into maintenance?

Remove-HVEntitlement removes all entitlements for a given pool

A colleague showed this to me, and I've been able to reproduce it many times. To reproduce, follow these steps...

  1. Create 2 or more entitlements on a pool
  2. Use Remove-HVEntitlement to remove one of those entitlements (e.g., Remove-Entitlement -User 'domain\user1' -ResourceName 'Pool-ID' -ResourceType Desktop)

After this, all entitlements will be removed from the pool. The script will even display the desired user's name while it loops through each user or group that is being removed.

I'm currently testing a fix for this and will submit a PR once verified.

add-hvdesktop doesn't assign user

the add-hvdesktop doesn't assign users even though the parameter is given. The issue is that it only tries to entitle users when the pooltype is automated (where you can't even manually add desktops!) and not if it's a manual vc managed pool

afaik assigning desktops can only be done by setting the advanced setting for that desktop but will dive a bit more into it.

Error Using Set-HVPool to Disable Linked-Clone Pool

I am trying to disable provisioning on an automated linked clone pool. First, I tried something like
Set-HVPool -PoolName 'whatever' -stop
but it gives an error

Set-HVPool : Start/Stop operation is not supported for Poll with name : [.DesktopSummaryData.Name]

If I use the -Enable or -Disable parameter, then it will not affect the provisioning status.

So I tried setting the key directly:
Set-HVPool -PoolName 'whatever' -Key 'automatedDesktopData.virtualCenterProvisioningSettings.enableProvisioning' -Value $true
Enabling works without a problem.

However, if I merely change the Value from $true to $false, then I get two errors:

Set-HVPool : Both
key:[automatedDesktopData.virtualCenterProvisioningSettings.enableProvisioning] and
value:[False] needs to be specified

and

Exception calling "Desktop_Update" with "3" argument(s): "There is an error in the
XML document."
At \\whateverPath\Modules\VMware.Hv.Helper\VMware.HV.Helper.psm1:5913 char:8
$desktop_helper.Desktop_Update($services,$item,$updates)

So what can be done to set this setting without error so that I can disable provisioning in Horizon View 7.2 with PowerShell?

Please let me know if you need any more information. Thanks!

Set-HVPool -PoolName '1531-28' -Disable does not work

Hi,

I tried to disable a floating linked clone Pool named 1531-28 by this code:

Set-HVPool -PoolName '1531-28' -Disable

The Error Message is:

Updating the Pool: 1531-28
Exception calling "Desktop_Update" with "3" argument(s): "ExceptionType : VMware.Hv.InvalidArgument
ErrorMessage : Invalid value for member
ParameterName : automatedDesktopData.vmNamingSettings.patternNamingSettings.namingPattern"
At C:\Program Files\WindowsPowerShell\Modules\VMware.Hv.helper\VMware.HV.Helper.psm1:6171 char:8

  •    $desktop_helper.Desktop_Update($services,$item,$updates)
    
  •    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : VimException

I tried it by the pure API apporach but it looks similar:

Script (without the Connect-HV and other basic stuff):

function Get-MapEntry {
param(
[Parameter(Mandatory = $true)]
$Key,
[Parameter(Mandatory = $true)]
$Value
)
$update = New-Object VMware.Hv.MapEntry
$update.key = $key
$update.value = $value
return $update
}

$Pools = Get-HVQueryResult -EntityType DesktopSummaryView

foreach($desktop in $Pools)
{
if($desktop.DesktopSummaryData.Source -eq "VIEW_COMPOSER" -and $desktop.DesktopSummaryData.Name -eq '1531-28')
{
$updates = Get-MapEntry -Key "desktopSettings.enabled" -Value $false
$disablePool = $viewapi.Desktop.Desktop_Update($desktop.Id, $updates)
}
}

Result:
Exception calling "Desktop_Update" with "2" argument(s): "ExceptionType : VMware.Hv.InvalidArgument
ErrorMessage : Invalid value for member
ParameterName : automatedDesktopData.vmNamingSettings.patternNamingSettings.namingPattern"
At C:\Scripte\powershell\VMware_View\View732\DisablePools.ps1:63 char:9

  •     $disablePool = $viewapi.Desktop.Desktop_Update($desktop.Id, $ ...
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : VimException

Is it possible that the namingPattern has an issue with the name of the pool '1531-28'? Do I anything wrong?

My Pool Naming Pattern is:
$test = $viewapi.Desktop.Desktop_Get($desktop.Id)
$test.AutomatedDesktopData.VmNamingSettings.PatternNamingSettings.NamingPattern

Results to (which is correct):
1531-28{n:fixed=3}

So maybe the "{}" are the problem?

Add new VI Property of KMSServer

New-VIProperty -Name KMSserver -ObjectType VirtualMachine -Value {
    Param ($VM)
    if ($VM.Encrypted) {
      $vm.EncryptionKeyId.ProviderId.Id
    }
    } -BasedOnExtensionProperty 'Config.KeyId' -Force | Out-Null 

This outputs the KMS server that’s attached to the VM and replaces the code example I was thinking of using in my blog.

Get-VM |Select Name,KMSserver

Name                                                          KMSserver                                                   
----                                                          ---------                                                   
Windows10 -1                                                  KMS01                                                       
Windows10                                                                                                                 
PyKMIPServer  

Remove a machine from a Pool, but not delete it.

Is there a function or argument to Remove-HVMachine that removes a VDI from a pool, but does not delete it? Essentially i want to remove it from a pool and add it to another.
In 6.x I would do by manipulating ADAM database, but curious if there's an API command or cmdlet that will allow it this to occur?

thanks in advance.

Missing parenthasis

Line 277. The ")" is missing after the $True statement.

[Parameter(Mandatory=$True]

should be

[Parameter(Mandatory=$True)]

get-hventitlement against a single global resource gets entitlements from all global resources

I was getting weird results when I did this:
(get-hventitlement -resourcename pod_global -ResourceType globalentitlement).globaldata.GlobalEntitlements
it showed me having multiple assigned groups whil I had only one. To test this I did

($services1.GlobalEntitlement.GlobalEntitlement_GetSummaryViews(((get-hventitlement -resour
cename pod_global -ResourceType globalentitlement).globaldata.GlobalEntitlements))).base.displayname

tldr:
doing a get-hventitlement on a single global resource you get entitlement for all global resources

Issues with the set-secureboot function

When I use the "get-vm $vm | set-secureboot -enabled" function I get a bunch of errors:


Exception calling "ReconfigVM_Task" with "1" argument(s): "
Unexpected element tag "efiSecureBootEnabled" seen
while parsing serialized DataObject of type vim.vm.BootOptions
at line 1, column 257
while parsing property "bootOptions" of static type VirtualMachineBootOptions
while parsing serialized DataObject of type vim.vm.ConfigSpec
at line 1, column 251
while parsing call information for method ReconfigVM_Task
at line 1, column 171
while parsing SOAP body
at line 1, column 64
while parsing SOAP envelope
at line 1, column 0
while parsing HTTP request for method reconfigure
on object of type vim.VirtualMachine
at line 1, column 0"
At line:62 char:5

  • $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : VimException

Get-Task : 5/2/2017 10:40:11 AM Get-Task The identifier Task- resulted in no objects.
At line:63 char:14

  • $task1 = Get-Task -Id ("Task-$($task.value)")
    
  •          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (:) [Get-Task], VimException
    • FullyQualifiedErrorId : Client20_OutputTracker_ReportNotFoundLocators_LocatorNotProduced,VMware.VimAutomation.ViCor
      e.Cmdlets.Commands.GetTask

Can someone help me? Thanks.

Charlie

Ressource Pool and accessgroup error on linked clone by .json method

Hello,
For begining, thanks to all people who have contributed to the creation of this module.

I write this message to explain two problems I've had to create linked clone with .json method and the solution I found to resolve them.

1) Resource Pool

error message :
Command : New-HVPool -Spec "C:\temp\ScriptsVMwareHV\TestpoolLinkedClone.json"

New-HVPool : Failed to create Pool with error: No hostOrCluster found with Name: [Form_Reference]
Au caractère Ligne:1 : 1
+ New-HVPool -Spec "C:\temp\ScriptsVMwareHV\TestpoolManFS6.json"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,New-HVPool

[Form_Reference] is the name of my resource pool that I put in the .json file :
Extract of .jsoon for ressource pool definition :

"VirtualCenterProvisioningData": {
"datacenter": "/Name_Of_Datacenter",
"parentVm": "Name_Of_VM",
"hostOrCluster": "/Name_Of_Datacenter/host/Name_Of_Cluster",
"resourcePool": "Form_Reference",
"snapshot": "reference",
"vmFolder": "/Name_Of_Datacenter/vm/Name_Of_Folder",
"template": null
},

The code which concerns thi part is (between line 4826-4836) in VMware.HV.Helper.psm1 :

4826: if ($resourcePool) {
4827:    $resourcePool_helper = New-Object VMware.Hv.ResourcePoolService
4828:    $resourcePoolList = $resourcePool_helper.ResourcePool_GetResourcePoolTree($services,$vmobject.HostOrCluster)
4829:    $resourcePoolObj = $resourcePoolList | Where-Object { ($_.resourcepooldata.path -eq $resourcePool) -or ($_.resourcepooldata.name -eq $resourcePool) }
4830:    if ($null -eq $resourcePoolObj) {
4831:      throw "No hostOrCluster found with Name: [$resourcePool]"
4832:    }
4833:    $vmObject.ResourcePool = $resourcePoolObj.id
4834:  }
4835:  return $vmObject
4836: 
}

The variable $resourcePool takes the value of "resourcePool": in the .json file (in my case : "Form_Reference").
$resourcePoolList takes the value of ressource pool of the cluster : path = "/Name_Of_Datacenter/host/Name_Of_Cluster/Resources" and name = "Name_Of_Cluster"
But my ressource pool is located in the path "/Name_Of_Datacenter/host/Name_Of_Cluster/Resources", it is a children.
The path of my ressource pool is : "/Name_Of_Datacenter/host/Name_Of_Cluster/Resources/Form_Reference" and name "Form_Reference".
so, the line :
$resourcePoolObj = $resourcePoolList | Where-Object { ($.resourcepooldata.path -eq $resourcePool) -or ($.resourcepooldata.name -eq $resourcePool) }

can't be true and $resourcePoolObj never have the good value.

Solution : to resolve this probleme I Replace this line by :

$resourcePoolObj = $resourcePoolList.Children | Where-Object { ($_.ResourcePoolData.path -eq $resourcePool) -or ($_.ResourcePoolData.name -eq $resourcePool) }

2) AccessGroup

Error message :

Exception lors de l'appel de « Desktop_Create » avec « 2 » argument(s) : « ExceptionType : VMware.Hv.MethodFault
ErrorMessage : Missing value for non-optional field accessGroup »
Au caractère C:\Program Files\WindowsPowerShell\Modules\VMware.Hv.Helper\VMware.HV.Helper.psm1:4730 : 7
+       $id = $desktop_helper.Desktop_create($services,$desktopSpecObj)
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException

in my .json i give a value to accessgroup (this accessgroup is present on view administrator aod user used to create pool is present in this accessgroup) :

...
"Base": {
"AccessGroup": "Windows 7",
"description": "Test linked clone VMFS6",
"name": "TestpoolManFS6-3",
"displayName": "Test pool Script VMFS6"
},
...

The code which concerns thi part is (between line 4624-4630) in VMware.HV.Helper.psm1 :

4624:  if (!$desktopBase) {
4625:      $accessGroup_client = New-Object VMware.Hv.AccessGroupService
4626:      $ag = $accessGroup_client.AccessGroup_List($services) | Where-Object { $_.base.name -eq $accessGroup }
4627:      $desktopSpecObj.base.AccessGroup = $ag.id
4628:    } else {
4629:      $desktopSpecObj.base = $desktopBase
4630:    }

The variable $accessGroup takes the value of "accessGroup": in the .json file (in my case : "Windows 7").
in this case, the value of $accessGroup_client.AccessGroup_List($services) is equal to 'Root' and the condition Where-Object { $_.base.name -eq $accessGroup } will never exist.

Solution : for this parameter work, I must change the line 4626 like this :
$ag = $accessGroup_client.AccessGroup_List($services).Children | Where-Object { $_.base.name -eq $accessGroup }

Thanks, I hope this will be usefull.

error when using new-hvpool I get an error (Domain administrator (domain.local) and container (dom.domain.nl) refer to different domains)

New-HVPool -LinkedClone -PoolName testkeespw -PoolDisplayName testkeespw -Description "pool met powercli gemaakt" -UserAssignment FLOATING -defaultDisplayProtocol BLAST -enableHTMLAccess 1 -Pa
rentVM "MCH-W7-GPU-GIP1.00" -SnapshotVM HW-upgrade -VmFolder testkees -HostOrCluster "cluster 1" -ResourcePool "cluster 1" -Datastores vsanDatastore -UseVSAN 1 -NamingMethod PATTERN -NamingPattern "W7-test-{
n:fixed=1}" -DomainAdmin sa_view-cp -CustType QUICK_PREP

Domain administrator (domain.local) and container (dom.domain.nl) refer to different domains)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.