Script is not working after vcenter upgraded
Restart-GuestVM not exiting
Hello Everyone,
I have a situation where we are calling a PS1 (PostDeployScript) scripts from within another PS1 script (VMPoll), and in the PostDeployScript we have the cmd
....
"Log to syslog server - Rebooting "
$vm | Restart-GuestVM -Confrim:$Fasle
"Log to syslog server - Rebooted "
....
Now this use to work fine with PowerCLI 6.5 and PowerShell v4, Ever since we upgraded to PowerCLI 11.0.x and PowerShell v5 the PostdeployScript get's held up at the Restart-GuestVM and never continues further, the powershell thread is still running and the Postdeploy never completes, almost as if it's waiting from some feedback or response. The VM does actually reboot as this can be seen the VC tasks.
If we change the line
$vm | Restart-VM -Confirm:$Fasle -RunAsync
Then the script continues as expected, but this now means the first login post the reboot we see the error "unexpected reboot"
Any help wold be appreciated
Azure Hybrid Worker Fails New-VM PowerCLI
So I have installed a Azure Hybrid worker on my script server.
I can launch a script with Local System / Local Service or Network Service as a scheduled task or interactively.
But running it through Test Pane in fails on the Azure Runbook if fails with a rather non-informed error
New-VM : 6/27/2018 4:05:30 PM New-VM Could not find item C:\ProgramData.
At line:56 char:1
+ New-VM -Name $VMname -template $myTemplate -location $env -ResourcePo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-VM], VimException
+ FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM
Paired it down my script , to make it simple
Param (
[String]$VMNamesuffix = 'MyTestServerLocal',
[string]$Env = "Test01",
[String]$VCServiceAccount ="Domain\svc_UserAccount",
[String]$VCServicePassword = "SomePassword"
)
## Varaibles ##
$VMname = ($Env+"-"+$VMNameSuffix).ToUpper()
$sourcevc = "vcenter01.domain.test"
$TargetDataStore = "TFC_XIO_"+$env
$sourceDS = 'TFC_XIO_UTILITY'
$ResourcePool = 'GoldRP'
# List of modules to be loaded
$moduleList = @(
"VMware.VimAutomation.Core",
"VMware.VimAutomation.Vds",
"VMware.VimAutomation.Cloud",
"VMware.VimAutomation.PCloud",
"VMware.VimAutomation.Cis.Core",
"VMware.VimAutomation.Storage",
"VMware.VimAutomation.HorizonView",
"VMware.VimAutomation.HA",
"VMware.VimAutomation.vROps",
"VMware.VumAutomation",
"VMware.DeployAutomation",
"VMware.ImageBuilder",
"VMware.VimAutomation.License"
)
# Load modules
function LoadModules(){
$loaded = Get-Module -Name $moduleList -ErrorAction Ignore | % {$_.Name}
$registered = Get-Module -Name $moduleList -ListAvailable -ErrorAction Ignore | % {$_.Name}
$notLoaded = $registered | ? {$loaded -notcontains $_}
foreach ($module in $registered) {
if ($loaded -notcontains $module) {
Import-Module $module
}
}
}
#Run LoadModules function
LoadModules
$VCSecurePassword = Convertto-SecureString -String $VCServicePassword -AsPlainText -force
$VCCreds = New-object System.Management.Automation.PSCredential $VCServiceAccount ,$VCSecurePassword
Connect-VIServer -Server $sourcevc -Credential $VCCreds
$SourceDataStoreOB = Get-Datastore $SourceDataStore
$TargetDataStoreOB= Get-Datastore $TargetDataStore
$myTemplate = Get-Template -Name "WinTemplate" -Location Templates
New-VM -Name $VMname -template $myTemplate -location $env -ResourcePool $ResourcePool -Datastore $TargetDataStoreOB -Verbose
Set/Enable SecureBoot - PowerCLI
Hi there
Does anyone know how to set/enable SecureBoot on PowerCLI?
I can see the below on one of the Forums but this only sets to EFI firmware and doesn't enable Secure Boot
$vm = Get-VM TestVM
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
$spec.Firmware = [VMware.Vim.GuestOsDescriptorFirmwareType]::efi
$vm.ExtensionData.ReconfigVM($spec)
Thanks
esxcli output driver version with host name
I seem to be stumped on this for some reason. I need to check a driver version (if installed) on all of our hosts. I have a small script with a foreach. However I need to see what host the driver version is on when I output to CSV. I made a variable called $VMHostName that gets the host. I tried to combine that with assigned a $output to the $esxcli line below then added $Vmhostname + $output but that didnt work either (I removed that section ) . Any assistance would be appreciated.
$EsxHosts = Get-VMHost
foreach($EsxHost in $EsxHosts){
$esxcli = Get-VMHost $EsxHost | Get-EsxCli
$VMHostName = $esxhost.Name
$esxcli.software.vib.list() | where "Name" -eq "scsi-aacraid" | export-csv driver.csv
}
Stop Task via powercli
i have a task that is hung in vcenter 6.5 and i cannot cancel it via the web.
powercli Get-Task state is "running" at 0% for the last hour. do i need to retrieve the task id in order to run a "stop-task"?
the task is "cancel remediating entity"
VCenter Server is unable to decrypt passwords stored in the customization database
Hi,
I am using the following in a script to build a new vm. I am copying the original customization spec, then modifying it.
Get-OSCustomizationSpec -name $custom | New-OSCustomizationSpec -name $servernametemp -type NonPersistent -ErrorAction stop
Get-OSCustomizationNicMapping -OSCustomizationSpec $servernametemp | Set-OSCustomizationNicMapping -ipmode UseStaticIP -IpAddress $ipaddr -subnetmask $NETMASK -DefaultGateway $gateway -dns $dns1 -ErrorAction stop
Set-OSCustomizationSpec $servernametemp -Domain domainname -DomainUsername $username -DomainPassword $userPassword -ErrorAction stop
When I try to create a new vm using the new spec, I get the following message:
Thanks for any help!
VM Migration from vcenter 5.5 to 6.5
Hello Everyone,
I'm planning to migrate more than 2000 vms from vcenter 5.5 to 6.5 and I would to get some help here if it's possible to have a script
which.
Like first
Source :shutdown the vms, unregister and remove from inventory and not delete...
Destination : Register vm, add to inventory connect to network and schedule VM compatibility upgrade
Targeting the source/destination cluster or folder that contains vms, keep same vlan, determine the port group type (standard or distributed).
Destination part, before starting vms, connect network and if possible update
- Active Connection to both Source and Destination vCenters
- Source vCenter
- VM
- VM’s Network Adapter/s
- Destination vCenter
- Destination ESXi Host
- Destination Datastore
- Destination PortGroup/s
Many thanks
Patrick
VMs did not fetch new VM settings on first run
Hello Experts,
I have the below script to add/modify some VMSettings in our cluster. We first powered off the VMs then ran the script which showed that it is setting the values for both new advanced settings the "followcorespersocket and the numa.autosize.vcpu.maxPerVirtualNode. After the script finished, we ran verification and it showed that the values for both VM settings is correct on all VMs. We started powering on the VMs but the VMs were not stable so we powered them down and then re-ran a verification script to find that the VMs only copied the first VM setting only but not the second one even though the verification right after the script fifnished showed both correctly!
We powered down the VMs again, ran the script again, seems like the script got the second VM setting the second time right. Powered on the VMs, they were stable, then ran the verification and everything seems correct. Does any body know why did the VMs did not copy both VM settings correctly on the first run? Do we need to introduce a pause in between the two commands for a few seconds to give the VM a chance to copy the new VM settings correctly? Your inputs is highly appreciated. Thanks
$vms = get-vm | where {$_.Name -like "*MCM*"} | where {$_.PowerState -eq "PoweredOff"}
foreach ($vm in $vms) {
Write-Host "Processing VM $vm" -ForegroundColor green
$followcorespersocketvalue = (Get-AdvancedSetting -Entity $vm -Name numa.vcpu.followcorespersocket).value
if ($followcorespersocketvalue -eq 1)
{
Write-Host "numa.vcpu.followcorespersocket key already exists and set correctly" -ForegroundColor green
}
else{
Write-Host "numa.vcpu.followcorespersocket key might already exists but not set correctly or does not exist at all - Setting the value for VM $vm" -ForegroundColor red
New-AdvancedSetting -Entity $vm -Name numa.vcpu.followcorespersocket -Value 1 -Confirm:$false -Force:$true
}
$numaautosize = (Get-AdvancedSetting -Entity $vm -Name numa.autosize.vcpu.maxPerVirtualNode).value
$AdvancedSettingDesiredValue = (Get-AdvancedSetting -Entity $vm -Name cpuid.coresPerSocket | select Value).value
if ($numaautosize -eq $AdvancedSettingDesiredValue )
{
Write-Host "numa.autosize.vcpu.maxPerVirtualNode key already exists and is set correctly equal to the cpuid.coresPerSocket value" -ForegroundColor green
}
else{
Write-Host "numa.autosize.vcpu.maxPerVirtualNode key might already exist, and might not be existing or set incorrectly" -ForegroundColor red
New-AdvancedSetting -Entity $vm -Name numa.autosize.vcpu.maxPerVirtualNode -Value $AdvancedSettingDesiredValue -Confirm:$false -Force:$true
}
Write-Host ""
}
Thanks @
Setting the network name on a nic before the customization spec
Hi,
I am building a virtual machine using a customization spec in which I want to join the domain. If the command below requires the vm to be powered on, how can I get this done before the customization spec tries to join the domain? I need it to be on a particular network of course.
get-networkadapter $servername | set-networkadapter -networkname $netw -Confirm:$false -StartConnected:$true -Connected:$true
Thanks!
WARNING: Parameter 'VMHost' is obsolete. This parameter no longer accepts multiple values. WARNING: Parameter 'Principal' is obsolete
After an upgrade from powercli 6.3. to 6.5.1 some parts of my script to configure an ESXi host have been showing warnings that I haven't seen before.
The iscsi-binding of 2 vmk ports completely broke but I will ask about this in a different subject if I can't fix it that myself.
question: What do I need to change in the syntax to get rid of the warnings?
The first snippit:
Set-PowerCLIConfiguration-InvalidCertificateActionIgnore-DisplayDeprecationWarnings$false-Confirm:$false|out-null
Write-Host"add local user to readonly role"-foregroundcolorgreen
New-VIPermission-Principaltestuser-Role" readonly "-Propagate:$true-Entity$vmhostname|Out-Null
Write-Host"Done"
Write-Host""
The snippit still works but gives this warning:
WARNING: Parameter 'Principal' is obsolete. This parameter no longer accepts multiple values.
WARNING: Parameter 'Entity' is obsolete. This parameter no longer accepts multiple values
Another snippit:
Write-Host"Connect NFS Datastores"-foregroundcolorgreen
foreach ($datastorein (Get-cluster$cluster|Get-Datastore|where {$_.Type -eq"nfs"-and$_.Accessible -eq"true"})){
New-Datastore-vmhost$vmhostname-Nfs-Name$datastore.Name -Path$datastore.RemotePath -NfsHost$datastore.RemoteHost |Out-Null
}
Write-Host"Done"
Write-Host""
The snippit still works but gives this warning:
WARNING: Parameter 'VMHost' is obsolete. This parameter no longer accepts multiple values.
PowerCLI Version
----------------
VMware PowerCLI 6.5 Release 1 build 4624819
---------------
Component Versions
---------------
VMware Cis Core PowerCLI Component 6.5 build 4624453
VMware VimAutomation Core PowerCLI Component 6.5 build 4624450
VMWare ImageBuilder PowerCLI Component 6.5 build 4561891
VMWare AutoDeploy PowerCLI Component 6.5 build 4561891
VMware Vds PowerCLI Component 6.5 build 4624695
VMware Cloud PowerCLI Component 6.5 build 4624821
VMware HA PowerCLI Component 6.0 build 4525225
VMware HorizonView PowerCLI Component 7.0.2 build 4596620
VMware Licensing PowerCLI Component 6.5 build 4624822
VMware PCloud PowerCLI Component 6.5 build 4624825
VMware Storage PowerCLI Component 6.5 build 4624820
VMware vROps PowerCLI Component 6.5 build 4624824
VMware vSphere Update Manager PowerCLI 6.5 build 4540462
Powercli config:
Powercli helptext:
NAME
New-Datastore
SYNOPSIS
This cmdlet creates a new datastore.
-------------- Example 1 --------------
C:\PS>New-Datastore -VMHost $vmhost -Name Datastore -Path $scsiLun.CanonicalName -Vmfs -FileSystemVersion 3
Creates a VMFS datastore by specifying the file system type.
-------------- Example 2 --------------
C:\PS>New-Datastore -Nfs -VMHost 10.23.112.60 -Name NFSDatastore -Path /mynfs -NfsHost 10.23.84.73
NAME
New-VIPermission
SYNOPSIS
This cmdlet creates new permissions on the specified inventory objects for the provided users and groups in the role.
-------------- Example 1 --------------
C:\PS>New-VIRole -Name Role -Server $server -Privilege (Get-VIPrivilege -PrivilegeGroup)
$permission = New-VIPermission -Role Role -Principal Administrator -Entity (Get-Datacenter)
Creates a permission on the provided server for a role with the specified privileges.
GuestOS Full and Family randomly empty
I'm attempting to gather details on VM guest OS and provide an easy way to sort Windows and Linux guests, so I want to gather the OS Full and OS Family into separate columns on a spreadsheet. I think I've run into an interesting bug here...
Starting with just a basic PowerCLI command to get the data on a folder of VMs I use for VMmark3. All happen to be CentOS VMs cloned from the same template file - configured (and verified) OS Class: Linux and OS Type CentOS 4/5/6/7 (64-bit) in the web client.
Get-VM -location Tile0 | Select Name,@{N="OS Full";E={$_.ExtensionData.Guest.guestFullName}},@{N="OS Family";E={$_.ExtensionData.Guest.guestFamily}}
Here's the output I get:
Name OS Full OS Family
---- ------- ---------
DS3DB0 CentOS 4/5/6/7 (64-bit) linuxGuest
AuctionMSQ0
AuctionAppA0
ElasticLB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
AuctionNoSQL0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
DS3WebA0 CentOS 4/5/6/7 (64-bit) linuxGuest
AuctionAppB0
DS3WebB0 CentOS 4/5/6/7 (64-bit) linuxGuest
ElasticWebA0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
AuctionWebB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
ElasticAppA0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
AuctionDB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
DS3WebC0
ElasticWebB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
Standby0 CentOS 4/5/6/7 (64-bit) linuxGuest
AuctionLB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
AuctionWebA0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
ElasticDB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
ElasticAppB0 Red Hat Enterprise Linux 7 (64-bit) linuxGuest
This is leaving me with large gaps of cells I need to fill in by hand and it doesn't really make sense as to why they would be empty. Let's pick on AuctionMSQ0 as it happens to be the top of the list of offenders.
get-vmguest AuctionMSQ0 | FL
results in:
OSFullName :
IPAddress : {}
State : Running
Disks :
HostName :
Nics :
ScreenDimensions : {Width=800, Height=600}
VmId : VirtualMachine-vm-265
VM : AuctionMSQ0
VmUid : /VIServer=vsphere.local\administrator@[redacted]:443/VirtualMachine=VirtualMachine-vm-265/
VmName : AuctionMSQ0
Uid : /VIServer=vsphere.local\administrator@[redacted]:443/VirtualMachine=VirtualMachine-vm-265/VMGuest=/
GuestId :
ConfiguredGuestId : centos64Guest
RuntimeGuestId :
ToolsVersion :
ExtensionData : VMware.Vim.GuestInfo
GuestFamily :
I've attached a snap of the VM settings to prove it's set correctly as far as I can see.
Any ideas?
powercli script to get last boottime of guest OS
hi
can I get some help with a script to get last boottime of guest OS (Win7 and 10) for multiple VMs.
thanks
datastore_info_function_with_foreach-object_powercli
hi Luc,
could you suggest what is wring in folowing .i want to use foreach-object .
function get-datastoreinfo
{
[cmdletbinding()]
param (
[parameter(mandatory = $true,
valuefrompipeline = $true,
valuefrompipelinebypropertyname = $true)]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost]$esxiname
)
$vm_host = Get-VMHost $esxiname
$datastores=Get-VMHost $vm_host|Get-Datastore|% -Process
{$per_freespace=$_.freespaceGB/$_.capacityGB*100
$_|select name,@{N='freespacepercent';E={$per_freespace}}}
}
Moving VM to another folder with full folder path using script
Hi All,
I'm trying to move virtual machines from one folder to another folder using scripts, however there were some errors that I encountered that I couldn't get around.
The script I used was written by LucD, please refer below:
$newDatacenter = "newDC"
$newFolder = "Temp"
$startFolder = New-Folder -Name $newFolder -Location (Get-Folder -Name vm -Location (Get-Datacenter -Name $newDatacenter))
Import-Csv "c:\temp\VM-with-FolderPath.csv" -UseCulture | %{
$location = $startFolder
$_.BlueFolderPath.TrimStart('/').Split('/') | %{
$tgtFolder = Get-Folder -Name $_ -Location $location -ErrorAction SilentlyContinue
if(!$tgtFolder){
$location = New-Folder -Name $_ -Location $location
}
else{
$location = $tgtFolder
}
}
$vm = Get-VM -Name $_.Name -ErrorAction SilentlyContinue
if($vm){
Move-VM -VM $vm -Destination $location -Confirm:$false
}
}
I've already exported the CSV file with another script, importing the CSV has no errors.
The error I got from the above script can be summarized as shown below:
PS C:\> move-vm -vm vra-iaas -destination Temp
WARNING: Specifying Folder in the Destination parameter is deprecated and the parameter will stop accepting Folder
objects at a future release. Please use the InventoryLocation parameter instead.
move-vm : 10/29/2018 4:08:22 PM Move-VM The operation for the entity "vra-iaas" failed with the following message:
"The request refers to an unexpected or unknown type."
At line:1 char:1
+ move-vm -vm vra-iaas -destination Temp
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Move-VM], InvalidType
+ FullyQualifiedErrorId : Client20_TaskServiceImpl_CheckServerSideTaskUpdates_OperationFailed,VMware.VimAutomation
.ViCore.Cmdlets.Commands.MoveVM
Temp is actually a folder I want to move the virtual machines in to. Did I specify the destination wrongly?
Are there any other commands/scripts that can be used?
Thanks in advance for your help.
Best regards,
Marcus
Issue with Date Format
Hi,
I am having issue with getting the date with timezone details.
I tried the below
$MTZ = [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')
$post = "<BR><i>Report generated on $((Get-Date).ToString())+ " " +$MTZ"
When executed, I am getting the below error
+ $post = "<BR><i>Report generated on $((Get-Date).ToString())+ " " +$MTZ"
+ ~~~~~~~~
Unexpected token '" +$MTZ"' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
But When I execute the direct command, it is working and I am getting the output
Command : $((Get-Date).ToString())+ " " +$MTZ
Output : 10/31/2018 6:24:22 AM CST
Please help!!!!
Get-VM result is fault at second time
My script as below
1. Getting list of vms as input file and it is running on two center server.
2. Connecting to vcenter server one by one to get-vm for each vm
3. Collect Snapshot status for that vm
4.disconnect vcenter and report out as below
Vmname,vcentername,snapshot,createdtime.
Then second phase as continuity after giving input to proceed yes.
Connecting to all the vcenter servers.
Get-vm for the vm which has snapshot (from the previous report).
But I'm not getting output here.
When I check overall get-vm also not showing any result.
Why it's not working?
PowerCli - Find VM in Multiple vCenter
How to find a VM in multiple vCenter using powercli.
I tried :
$vCenters = @("xx""xx")
ForEach-Object ($vCenter -in $vCenters)
{
$Connect = Connect-VIServer $vCenter -User xxxxx -Password xxxxx
}
running under "system account"
Hi Guys,
We have a powercli script which we run scheduled using the windows system account, this worked fine until we uninstalled the PowerCLI exe 6.5 and install 11.0 via PSGallery ?
Anyone experienced this ?
Thanks
Rolf
Trouble finding PowerCLI in new install of vscode
Hi all,
I'm new to vscode (heard about it yesterday in fact) and am having a configuration issue. I have successfully installed vs code, and I was able to add the powershell extenison to it. I als added LucD's Microsoft.VSCode_Profile.ps1 to the install which I found on his blog here: http://www.lucd.info/2016/04/23/visual-studio-code-powercli/
When I ran and install-module command to connect powercli It looked successful but when I open a ps1 file I see this error:
PowerShell Integrated Console
Can not find a PowerCLI installation!
At \\fs-55-ah\vmgr$\home05\dscotti\Documents\WindowsPowerShell\Microsoft.VSCode_profile.ps1:78 char:13
+ Throw 'Can not find a PowerCLI installation!'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Can not find a PowerCLI installation!:String) [], RuntimeException
+ FullyQualifiedErrorId : Can not find a PowerCLI installation!
Also Seeing this error:
cd : Cannot find path 'Microsoft.PowerShell.Core\FileSystem::' because it does not exist.
At C:\Program Files (x86)\VMware\Infrastructure\PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1:134 char:1
+ cd \
+ ~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.PowerShell.Core\FileSystem:::String) [Set-Location], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
I am running this version of powershell:
$psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
5 1 17134 228
This is my version of powercli:
PowerCLI Version
----------------
VMware PowerCLI 11.0.0 build 10380590
---------------
Component Versions
---------------
VMware Cis Core PowerCLI Component PowerCLI Component 11.0 build 10335701
VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 11.0 build 10336080
An interesting side note is that the commands I run (like connect-viserver) can tab complete. so that tellse me something is finding powercli.
Has anyone seen this before? And how do I clear the error?
Thanks
Dan