Quantcast
Channel: VMware Communities : All Content - VMware PowerCLI
Viewing all 16717 articles
Browse latest View live

vm information script powershell

$
0
0

I am trying to write a script to get all of the information for my vm infrastructure. Using powercli and powershell I have all of my information and variables figured out thanks to this forum. I just figure out how to format and export them to csv in order to put into excel. These currently are my variables.

$VmInfo = Get-VM

$VMS = ($VmInfo).Name

$VMSysInfo = Get-VMGuest -VM $VmInfo

$Cluster_initial = &{foreach($vm in Get-VM){

 

Get-Datastore -RelatedObject $vm |

 

Select @{N='Cluster';E={Get-Cluster -VMHost $vm.VMhost | select -ExpandProperty Name}}}}

$cluster = $cluster_initial.cluster

 

$ESX_IHOST = ($VmInfo).VMHost.name

$VM_Name = ($VmInfo).name

$Power_Status = ($VmInfo).PowerState

$Memory_Allocated = ($VmInfo).MemoryGB

$CPU_Allocated = ($VmInfo).NumCpu

$StorageAllocated = ($VmInfo).ProvisionedSpaceGB

$DNS_Name = ($VmInfo).ExtensionData.Guest.Hostname

$Ip_Initial = Get-VM | Select Name, @{N="IP";E={@($_.guest.IPaddress[0])}}

$IP_Address = $Ip_Initial.IP

$vCenterServer = ($VmInfo).ExtensionData.Client.ServiceUrl.Split('/')[2].trimend(":443")

$cluster = $cluster_initial.cluster


What command do I use to change the IP of an ESXi host?

$
0
0

Hello,

 

I have to re-ip a bunch of ESXi hosts into a different subnet.  I've got a script that will connect to vCenter, let me select the datacenter, select the host, remove the host from vCenter (as the host is also having a fqdn change), disconnect from vCenter, connect directly to the host and then try to reconfigure the host.  I understand it can't be all done in one command, but I'm not sure why it's failing, or what the exact command is.  Is it Set-VMHostNetwork or Set-VMHostNetworkAdapter?  What I have is this:

 

$ESXIP = Read-Host "Enter new IP address"

Write-Host "Configure new management network"

Get-VMHost "$ESXhost" | Set-VMHostNetworkAdapter -VirtualSwitch "vSwitch0" -PortGroup "Management Network" -IP "$ESXIP" -SubnetMask "255.255.255.0" -ManagementTrafficEnabled:$true -Confirm:$false | out-null

Write-Host "Configure new DNS servers"

Get-VMHost "$ESXhost" | Get-VMHostNetwork | Set-VMHostNetwork -DnsAddress 8.8.8.8,8.8.8.8 -DnsFromDhcp $false

Write-Host "Change VMkernel Gateway"

$net = Get-VMHostNetwork

$net | Set-VMHostNetwork -VMKernelGateway 1.2.3.4 | out-null

 

But I always seem to get a failure on the setting of the IP, which of course stops it from doing the gateway:

 

Set-VMHostNetworkAdapter : Parameter set cannot be resolved using the

specified named parameters.

At C:\Users\emcclure\Desktop\GenScripts\GenUpdateHostIPSettings.ps1:39 char:25

+ ... $ESXhost" | Set-VMHostNetworkAdapter -VirtualSwitch "vSwitch0" -PortG ...

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

    + CategoryInfo          : InvalidArgument: (:) [Set-VMHostNetworkAdapter],

    ParameterBindingException

    + FullyQualifiedErrorId : AmbiguousParameterSet,VMware.VimAutomation.ViCor

   e.Cmdlets.Commands.Host.SetVMHostNetworkAdapter

 

I'd figure after this I'd either want to reboot the host or somehow get the network to restart and then add it back to vCenter with the new fqdn.  But how to get the above to work?  Any help appreciated.  Thanks in advance.

ILO information by Script

$
0
0

I would like to ask if someone can try this script to check ILO information's I just need to know if is valid, I got these info when I run:

 

Header 1

   

iLOFirmwareHPSmartArraySystemBIOS
Hewlett-Packard BMC Firmware (node 0) 46:10000 2.20HP Smart Array Controller HPSA1 Firmware 6.64HP System BIOS I31 2015-04-01 00:00:00.000
Hewlett-Packard BMC Firmware (node 0) 46:10000 2.40HP Smart Array Controller HPSA1 Firmware 3.56HP System BIOS I36 2015-12-28 00:00:00.000
Hewlett-Packard BMC Firmware (node 0) 46:10000 2.40HP Smart Array Controller HPSA1 Firmware 4.02HP System BIOS I36 2015-12-28 00:00:00.000
Hewlett-Packard BMC Firmware (node 0) 46:10000 2.40HP Smart Array Controller HPSA1 Firmware 3.56HP System BIOS I36 2015-12-28 00:00:00.000
Hewlett-Packard BMC Firmware (node 0) 46:10000 2.40HP Smart Array Controller HPSA1 Firmware 3.56HP System BIOS I36 2015-12-28 00:00:00.000

 

So, I suppose 2.20, 2.40 are ILO version...thanks

 

Get-View -ViewType HostSystem -Property Name, Runtime.HealthSystemRuntime.SystemHealthInfo.NumericSensorInfo -SearchRoot (Get-View -ViewType ClusterComputeResource -Property Name -Filter @{"Name" = "^$([RegEx]::escape($strHostsClusterName))$"}).MoRef | %{    $arrNumericSensorInfo = @($_.Runtime.HealthSystemRuntime.SystemHealthInfo.NumericSensorInfo)    # HostNumericSensorInfo for BIOS, iLO, array controller    $nsiBIOS = $arrNumericSensorInfo | ? {$_.Name -like "*System BIOS*"}    $nsiArrayCtrlr = $arrNumericSensorInfo | ? {$_.Name -like "HP Smart Array Controller*"}    $nsiILO = $arrNumericSensorInfo | ? {$_.Name -like "Hewlett-Packard BMC Firmware*"}    New-Object PSObject -Property @{        VMHost = $_.Name        "SystemBIOS" = $nsiBIOS.name        "HPSmartArray" = $nsiArrayCtrlr.Name        "iLOFirmware" = $nsiILO.Name        }} | Export-Csv -Path C:\Users\gemela\ILO_info.csv -NoTypeInformation -UseCulture

Display number of LUN

$
0
0

Hello,

I would like display the LunID in my script but i dont make this. My script is : 

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

$VMS = Get-VM -Name "MyVM" | get-HardDisk -DiskType "RawPhysical", "RawVirtual"

$report = @()

foreach ($vm in $VMS) {

$row = "" | select Parent, DiskType, ScsiCanonicalName, Persistence, Filename,"LunID", CapacityGB

$row.Parent = $vm.Parent

$row.Disktype = $vm.disktype

$row.scsiCanonicalName = $vm.ScsiCanonicalName

$row.Persistence = $vm.Persistence

$row.Filename = $vm.Filename

$row."LunID" = ''

$row.CapacityGB = $vm.CapacityGB

$report += $row

}

 

$report | export-csv -Path "Path" -NoTypeInformation -UseCulture

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

VM                       DiskType                    LunName             Datastore                       Lunid                                                            Size

My VM                RawPhyscial               naa.xxxxxx           DatastoreName            Number of LUN (Exemple : 5)                   XGB

 

Thank you very much for help

 

Mehdi

$VMS = Get-VM -Name XS20792* | get-HardDisk -DiskType "RawPhysical", "RawVirtual"
 
$report = @()
foreach ($vm in $VMS) {
$row = "" | select Parent, DiskType, ScsiCanonicalName, Persistence, Filename,"LunID", CapacityGB
$row.Parent = $vm.Parent
$row.Disktype = $vm.disktype
$row.scsiCanonicalName = $vm.ScsiCanonicalName
$row.Persistence = $vm.Persistence
$row.Filename = $vm.Filename
$row."LunID" = ''
$row.CapacityGB = $vm.CapacityGB
$report += $row
}
 
$report | export-csv -Path "c:\mehdi\scripts_test\DiskType.csv" -NoTypeInformation -UseCulture

geting inventory from powercli and rvtools

$
0
0

Hi Luc ,

 

Good morning ,

could you please epain the mechanism difference in fetching vsphere info using powercli and rvtools.

Unable to get MAC, Duplex, MTU, Speed, Model

$
0
0

Hi,

 

Please help, I am unable to get the MAC, Duplex, MTU, Speed, Model, there is no error but shows blank

 

function Get-NICDetails {

[CmdletBinding()]

param(

    [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)]

    [ValidateNotNullorEmpty()]

        [String] $Clustername 

        )

Begin {

    $Validate = $True

    if (($myCluster = Get-Cluster -Name $Clustername).count -lt 1) {

       $Validate = $False

       thow "No Cluster '$myCluster' found!"

    }

  }

Process {

    $MyView = @()

    if ($Validate -eq $True) {

          foreach ($myVMhost in ($myCluster | Get-VMHost)) {

            $esxcli2 = Get-ESXCLI -VMHost $myVMhost -V2

            $niclist = $esxcli2.network.nic.list.invoke()

            $nicdetails = @()

            foreach ($nic in $niclist) {

                $args = $esxcli2.network.nic.get.createargs()

                $args.nicname = $nic.name

                $nicdetail = $esxcli2.network.nic.get.Invoke($args)

                $nicdetails += $nicdetail

                }

            ForEach ($nicdetail in $nicdetails){

                $NICReport = [PSCustomObject] @{

                        Host = $myVMhost.Name

                        Version = $myVMhost.version

                        Host_Manufacturer = $myVMhost.Manufacturer

                        Host_Model = $myVMhost.Model

                        SerialNumber = $myVMhost.ExtensionData.Hardware.SystemInfo.OtherIdentifyingInfo |Where-Object {$_.IdentifierType.Key -eq "Servicetag"} |Select-Object -ExpandProperty IdentifierValue

                        vmnic = $nicdetail.Name

                        MAC = $nicdetail.MACAddress

                        LinkStatus = $nicdetail.LinkStatus

                        BusInfo = $nicdetail.driverinfo.BusInfo

                        Duplex = $nicdetail.Duplex

                        MTU = $nicdetail.MTU

                        Speed = $nicdetail.Speed

                        Model = $nicdetail.Description

                        Driver = $nicdetail.driverinfo.Driver

                        FirmwareVersion = $nicdetail.driverinfo.FirmwareVersion

                        DriverVersion = $nicdetail.driverinfo.Version

                        }

                $MyView += $NICReport

                }

        }       

       $MyView

    }

}

}

get esxi storage path details using powercli

$
0
0

ran the below script but getting an error saying "Get-ScsiLunPath        Value cannot be null" , any help would be appreciated!!

 

$results= @()
foreach ($VMHost in $VMHosts) {
[ARRAY]$HBAs = $VMHost | Get-VMHostHba -Type "FibreChannel"

    foreach ($HBA in $HBAs) {
    $scsiluns = Get-ScsiLun -Hba $HBA -LunType "disk"
    foreach ( $scsilun in $scsiluns) {
    $pathState = $scsilun | Get-ScsiLunPath | Group-Object -Property state
    $pathStateActive = $pathState | ? { $_.Name -eq "Active"}
    $pathStateDead = $pathState | ? { $_.Name -eq "Dead"}
    $pathStateStandby = $pathState | ? { $_.Name -eq "Standby"}
    $results += "{0},{1},{2},{3},{4},{5}" -f $VMHost.Name, $HBA.Device, $VMHost.Parent, [INT]$pathStateActive.Count, [INT]$pathStateDead.Count, [INT]$pathStateStandby.Count
    }
}
}

ConvertFrom-Csv -Header "VMHost","HBA","Cluster","Active","Dead","Standby" -InputObject $results | Ft -AutoSize

 

ERROR:


Get-ScsiLunPath : 12/2/2015 1:49:18 PM    Get-ScsiLunPath        Value cannot be null.
Parameter name: array   
At line:13 char:29
+     $pathState = $scsilun | Get-ScsiLunPath | Group-Object -Property state
+                             ~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ScsiLunPath], VimException
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Host.GetScsiLunPath

Copy-DatastoreItem error - 404 File Not Found

$
0
0

So I am trying to copy a file down from a datastore on my host and having this issue:

 

Copy-DatastoreItem : 1/26/2012 6:35:54 AM VimDatastore Download of file 'https://usewdesx015:443/fo

lder%2fLogs%2fdupes.report?dcPath=ha-datacenter&dsName=LOCAL-USEWDESX015' failed. Error message: The remote s

erver returned an error: (404) Not Found.

At line:1 char:19

+ Copy-DatastoreItem <<<< -Item "ds:\Logs\dupes.report" -Destination "c:\dupes\" -Force

+ CategoryInfo : NotSpecified: (:) [Copy-DatastoreItem], VimException

+ FullyQualifiedErrorId : Client20_StorageServiceImpl_DownloadFile_DownloadFailed,VMware.VimAutomation.V

iCore.Cmdlets.Commands.CopyDatastoreItem

 

I can verify that the file I am looking for is there and also that I am connected to the datastore correctly.

 

PS ds:\Logs> ls

  

Datastore path: [LOCAL-USEWDESX015] Logs

LastWriteTime Type Length Name

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

6/30/2011 5:15 PM File 13283 esxupdate.debug

1/26/2012 1:54 PM File 8197 dupes.report

 

Here is my code:

 

 

CurrentLocation :

Name : ds

Provider : VMware.VimAutomation.Core\VimDatastore

Root : \usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015

Description :

Credential : System.Management.Automation.PSCredential

Used :

Free :

  

PSPath : VMware.VimAutomation.Core\VimDatastore::\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\

Logs\esxupdate.debug

PSParentPath : VMware.VimAutomation.Core\VimDatastore::\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\

Logs

PSChildName : esxupdate.debug

PSDrive : ds

PSProvider : VMware.VimAutomation.Core\VimDatastore

PSIsContainer : False

Length : 13283

DatastoreId : Datastore-4d931f68-983f5bd4-5450-1cc1de2607b2

Datastore : LOCAL-USEWDESX015

Name : esxupdate.debug

FolderPath : [LOCAL-USEWDESX015] Logs

DatastoreFullPath : [LOCAL-USEWDESX015] Logs/esxupdate.debug

FullName : vmstores:\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\Logs\esxupdate.debug

ItemType : File

LastWriteTime : 6/30/2011 5:15:39 PM

Uid : /VIServer=blackrock\svcvmscp@usewdesx015:443/Datastore=Datastore-4d931f68-983f5bd4-5450-1

cc1de2607b2/DatastoreItem=[LOCAL-USEWDESX015] Logs&slash;esxupdate.debug/

  

PSPath : VMware.VimAutomation.Core\VimDatastore::\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\

Logs\dupes.report

PSParentPath : VMware.VimAutomation.Core\VimDatastore::\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\

Logs

PSChildName : dupes.report

PSDrive : ds

PSProvider : VMware.VimAutomation.Core\VimDatastore

PSIsContainer : False

Length : 8197

DatastoreId : Datastore-4d931f68-983f5bd4-5450-1cc1de2607b2

Datastore : LOCAL-USEWDESX015

Name : dupes.report

FolderPath : [LOCAL-USEWDESX015] Logs

DatastoreFullPath : [LOCAL-USEWDESX015] Logs/dupes.report

FullName : vmstores:\usewdesx015@443\ha-datacenter\LOCAL-USEWDESX015\Logs\dupes.report

ItemType : File

LastWriteTime : 1/26/2012 1:54:41 PM

Uid : /VIServer=blackrock\svcvmscp@usewdesx015:443/Datastore=Datastore-4d931f68-983f5bd4-5450-1

cc1de2607b2/DatastoreItem=[LOCAL-USEWDESX015] Logs&slash;dupes.report/

 

Copy-DatastoreItem : 1/26/2012 6:33:34 AM VimDatastore Download of file 'https://usewdesx015:443/fo

lder%2fLogs%2fdupes.report?dcPath=ha-datacenter&dsName=LOCAL-USEWDESX015' failed. Error message: The remote s

erver returned an error: (404) Not Found.

At C:\software\VMWareScripts\PROD\AdminScripts\Automation\CheckDupesReport.ps1:15 char:19

+ Copy-DatastoreItem <<<< -Item "ds:\Logs\dupes.report" -Destination "c:\dupes\" -Force

+ CategoryInfo : NotSpecified: (:) [Copy-DatastoreItem], VimException

+ FullyQualifiedErrorId : Client20_StorageServiceImpl_DownloadFile_DownloadFailed,VMware.VimAutomation.V

iCore.Cmdlets.Commands.CopyDatastoreItem

 

 

 

 

 

The strangest part is that it will delete the file with no errors. Any help on this would be greatly appreciated.

 

Connect-VIServer hostname -User "user" -Password "password"

$datastore = Get-Datastore "DS Name"
New-PSDrive -Location $datastore -Name ds -PSProvider VimDatastore -Root "\"

Set-Location ds:\Logs

Get-ChildItem

Copy-DatastoreItem -Item "ds:\Logs\dupes.report" -Destination "c:\dupes\" -Force

del "ds:\Logs\dupes.report"

Disconnect-VIServer * -Confirm:$false

 

 

Here is my output:

 

 


Workaround for Error in deserializing body of reply message for operation 'RetrieveProperties'

$
0
0

I am having trouble finding  the Get-VIEvent  equivalent in the vcenter   and vcenter server API.

 

Am I missing something?

 

Or is it not there, YET?

PowerCLI 10 (and Microsoft VS Code)

$
0
0

Hi All,

 

Earlier today when trying to do some basic work in PowerCLI on a vCenter 6.5 server, I started to see some strange results

PS C:\WINDOWS\system32> Get-VMHost $serverlist | Get-VM

Get-VM : 26/Jun/2018 13:26:31    Get-VM        Exception has been thrown by the target of an invocation.   

At line:1 char:26

+ Get-VMHost $serverlist | Get-VM

+                          ~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Get-VM], VimException

    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

 

I thought "new version of VC, so maybe a new version of PowerCLI is needed"

 

PowerCLI v10 is available but, the only prerequisite, PowerShell Core 6 needs to be installed.

No big deal, right ?

Wrong !

 

PowerShell Core 6 no longer uses the ISE.

Microsoft are recommending the VS Code instead.

 

I've installed the VS Code App, PowerShell extensions and, installed PowerCLI using Install-Module -Name VMware.PowerCLI -Scope AllUsers

 

VS Code, doesn't appear to have tab completion, connect-viserv + TAB doesn't return Connect-VIserver for example.

 

Am I missing something here or, do I need to use something other than VS Code to replace the ISE when using PowerCLI 10 ?

 

Thanks

Check version of ESXi and only run commands on certain versions.

$
0
0

I know this is probably simple fix but I am coming to a blank.

 

What I need to do is check the ESXi version to make sure it is above 6.x before running code and running different code on 5.x hosts.  My pseudo code is below.

 

If (host level = version 6.x)

{

     run code set 1

}

else

{

     run code set 2

}

 

Thanks in advance.

invoke-vmscript guestcredential

$
0
0

how do I use the guest credential in invoke-vmscript?

 

I have no problem using local admin password for guestuser and guiestpassword

 

but when I use a domainuser which is part of the local admin group. it fails with access denied

How to sync templates between DCs

$
0
0

Hello Community,

 

quick to our environment:

- 2 x vCenter 6.5

- each vCenter with round about 60 DataCenters around the world

- templates synced between the vCenters with Content Library

 

Now, I need to have the actual templates synced/deployed from my main site in my vCenter to all other DataCenters so that every site is using the same templates. After a maintenance where we patching our templates I need to sync again all templates with the newest one in our main site.

 

Community, how do you handle this?

- vSphere Replication

- PowerCli

- ovftool

- backup software

- ? ? ?

 

My idea is to write a script where I delete all the templates on all DCs and do a "Clone Template" to all sites - hugh traffic each maintenance weekend.

 

Would be cool if you can give me some input!

 

Thank you very much and greetings

KKvss

Release backup software's lock on VMs

$
0
0

Hello everybody

 

We are having the issue that our backup software sometimes forgets to unlock VMs after it is done with its thing.

 

The software itself only allows the unlocking by browsing the backup selection and selecting each and every VM individually and hitting "unlock".

 

This not only hampers new backup attempt sometimes, it also blocks DRS vMotions and manual ones. While troubleshooting this on PS, I noticed that PS was aware that the VM was actually locked by the backup plugin.

 

So my hope is to find all VMs with such a lock and remove the lock via PS.

 

Does anybody have experience with this issue or can anyone be of assistance in finding a way to do this?

 

Thanks in advance for your time

 

Regards,

 

Marco

powercli script with options menu

$
0
0

Hi People, im new in powercli!

 

Is possible in powercli, create a script where appears a menu with options to choose like a what vcenter to connect, choose cluster in this vCenter.... and with this data, execute a task

 

 

For example, to choose a vCenter, in this vCenter  choose a cluster, in that cluster that shows me the DRS rules..

 

 

It's possible?

 

 

How can I do it?

 

 

Thanks in advanced

 

Regards


VCD 8.2 VM & vAPP Owner Report

$
0
0

Hi All, Anyone have an updated version of this script? Appreciate the help!

 

 

$CIvApp =get-CIvApp

 

$CIvms =$CIvApp |get-CIvm 

$report =@() 

foreach($vm in$CIvms){ 

$row =""| Select "Name","CIVApp","Org","Status","Operating System","CpuCount","Memory (GB)","Owner" 

   $row."Name"=$vm.Name 

   $row."CIvapp"=$CIVapp.Name 

   $row."Org"=$CIVapp.Org.Name 

   $row."Status"=$CIVapp.Status 

   $row."Operating System"=$vm.GuestOSFullName 

   $row."CpuCount"=$vm.CpuCount 

   $row."Memory (GB)"= ($vm |Measure-Object-Property MemoryMB -Sum).Sum/1024 

   $row."Owner"=$CIvapp.Owner.Name 

   $report +=$row 

$report |export-csv C:\tmp\VcloudVMsNEW.csv

Azure Hybrid Worker Fails New-VM PowerCLI

$
0
0

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

WARNING: Parameter 'VMHost' is obsolete. This parameter no longer accepts multiple values. WARNING: Parameter 'Principal' is obsolete

$
0
0

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.

 

 

Looking for inspiration ... Passwords in Scripts

$
0
0

Hey there,

 

after i install our ESXi hosts and put them into the vcenter i use a powershell script which will do the rest of configuration needed...

 

One of the points is to create a local readonly esxi User with a password. I dont like to have passwords in my scripts and in this case the script will only run with user interaction.

 

So in the first case i try to use a simple

 

$pwd = read-host "Enter a password:"

 

the problem here is here you can read the password which is provided...

 

I read  little bit and try..

 

$pwd = read-host "Enter a password:" -asSecureString

 

This looks nice in the first step but to avoid password missmatches i fetch the password twice and compare both. In this case $pwd1 & $pwd2 are securestrings and do not match.

 

Now i try something like...

 

---Snip----

    $check = "0"

while ($check -eq "0") {

        $encpasswort1 = Read-Host "Please Enter pwd: " -AsSecureString

        $encpasswort2 = Read-Host "again" -AsSecureString

 

        $password1 = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($encpassword1))

        $password2 = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($encpassword2))

       

        if ($passwort1 -eq $passwort2) {

            write-host -ForegroundColor Green "Lege Nutzer auf " $esx_Host.Name "an `n"

            $status = Connect-VIServer $esx_Host.Name -User root -wa 0

            $status = New-VMHostAccount -Id $user -Password $passwort1 -Description $desc -UserAccount

            $status = New-VIPermission -Principal $user -Role $role -Entity (Get-Datacenter)

            $status = Disconnect-VIServer $esx_Host.Name -Confirm:$false

            $check = "1"

          }

}

---snip----

 

This works so far but maybe there is a better way...

 

Maybe to compare to Securestring objects or pass them to an esxi host...

 

Some ideas would be welcome.

 

Thanks

Create lokal user account on ESXi Host

$
0
0

HI,

 

i try to create a local readonly esxi user. In the past i had  script like this..

 

 

New-VMHostAccount -Id $user -Password $pwd -Description $desc -UserAccount

New-VIPermission -Entity $ent -Principal $user -Role $role

 

 

where -Entiity of the New-VIPermission cmdlet was "ha-folder-root". if found this solution here in the community but i was not sure why it is this entity.

 

Now with my 6.5 host it comes to an error that the entity could not be found and a litle bit research brought me to this..

 

New-VIPermission -Entity (get-datacenter) -Principal $user -Role $role

 

Since Entity is descript as viobjekt this works well in the first step... but it the end its looks not that good..

 

 

 

New-VIPermission -Entity (get-datacenter) -Principal username -Role ReadOnly

 

Role                      Principal       Propagate IsGroup

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

ReadOnly                  username         True      False

 

Get-VIPermission|select Role, Principal, Entity

Role     Principal Entity    

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

ReadOnly username   ha-datacenter

ReadOnly username  host      

Admin    vpxuser   root      

Admin    dcui      root      

Admin    root      root      

ReadOnly username   vm       

 

 

It looks like that this is not the best option. So maybe somebody can point me to some information regarding this entity thing or can exlpain it to me?

 

And at the end ... is there an easy way to mark code as code so that it will be colored in this forum?

 

Greetings...

Viewing all 16717 articles
Browse latest View live


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