Powershell

execute powercli script or command:

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile “C:\Program Files\VMware\Infrastructure\VSphere PowerCLI\vim.psc1” -NoExit –Command "la commande"

C:\MyFirstPSscript.ps1

# Modules Fonctions diverves

function Set-VMVlanNetwork {
Param(
[Parameter(Mandatory = $true)][String]$VMName,
[Parameter(Mandatory = $true)][String]$VLANName
)
# recuperation du Port Group
Write-verbose "Récupération du PortGroup pour le VLAN $VLANName"
# Get-VirtualPortGroup retourne un objet de type VMware.VimAutomation.ViCore.Impl.V1.Host.Networking.VirtualPortGroupImpl
# qui sert au paramètre PortGroup de la command Set-NetWorkAdapter
$PGName = Get-VirtualPortGroup | ? Name -Like "*$VLANName"
#$PGName = Get-VirtualPortGroup -VMHost (get-vm -Name $VMName).vmhost | ? {$_.Name -like "*$VLANName" }
Write-verbose "PortGroup : $($PGName.Name)"
 
# recuperation du status de la VM
$status = (get-vm -Name "$VMName").PowerState
Write-verbose "Etat de la VM : $status"
 
if ($status.Tostring() -eq "PoweredOff") {
Write-verbose "Attribution du PortGroup $PGName.Name sur la VM $VMName"
get-vm -Name "$VMName" | Get-NetworkAdapter |set-NetworkAdapter -Portgroup $PGName -confirm:$false -verbose
get-vm -Name "$VMName" | Get-NetworkAdapter |set-NetworkAdapter -startConnected:$true -confirm:$false -verbose
Write-verbose "Démarrage de la VM VMName"
#Get-vm -Name "$VMName" |Start-VM | Out-Null
}
else {
Write-verbose "VM déjà allumée, attribution du PortGroup $($PGName.Name) et Connexion au réseau"
get-vm -Name "$VMName" | Get-NetworkAdapter |set-NetworkAdapter -Portgroup $PGName -confirm:$false -verbose
get-vm -Name "$VMName" | Get-NetworkAdapter |set-NetworkAdapter -startConnected:$true -confirm:$false -verbose
}
}
function Get-OSversion {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)]
        [String[]]$Computer='.'
    )
    $OSversion = gwmi -Class win32_operatingSystem -ComputerName $Computer | select version
    switch -wildcard ($OSversion.version) 
        {
            "5.0*" {$OS = "2000"}
            "5.2*" {$OS = "2003"} 
            "6.0*" {$OS = "2008"}
            "6.1*" {$OS = "2008 R2"}
            "6.2*" {$OS = "2012"}
            "6.3*" {$OS = "2012 R2"}
        }
    return $OS
}
function Get-OSLanguage {
[CmdletBinding()]param (
        [Parameter(Mandatory=$false)][String[]]$Computer='.'
    )
    foreach ($srv in $Computer) { 
        $lang = $null
        write-verbose "Traitement de $srv"
        $code = gwmi -Class win32_operatingsystem -ComputerName $srv |select OSLanguage
        write-verbose "Valeur du code de langue pour $srv : $code"
        switch ($code.OSLanguage) {
            "1033" { $lang = "EN" }
            "1036" { $lang = "FR" }
        }
        $lang
    }
}
function Get-VMType {
[CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][String[]]$Computer
    )
    $Manufacturer = Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $Computer | % { $_.Manufacturer.tostring() }
    switch -Regex ($Manufacturer) {
         "^[vV][mM][ware]" { $Type = "Virtual VMware"} 
         "^[Mm][icrosoft]" { $Type = "Virtual Hyper-V"}
         default { $Type = "Physical" }
    }
    return $Type
}
function Search-DNSAlias {
[CmdletBinding()] 
Param (
	[parameter(Mandatory=$true)][string[]]$hostname,
	[string]$zone="zonename",
	[string]$fqdn="domain.tld",
	[string]$dnssrv="defaultsrv",
	[switch]$AllDnsZone
)
    $zonename="$zone.$fqdn"
    write-verbose "Host : $hostname"
    write-verbose "Dns Server : $dnssrv"
    write-verbose "ZoneName : $zonename"
    $allzone = "zone1.domain.tld","zone1.domain.tld", "zone1.domain.tld"
    foreach ($cpt in $hostname) {
	    write-verbose "valeur de cpt: $cpt"
	    if ($AllDnsZone) {
        Write-Verbose "Recherche dans toutes les zones DNS"
		$allzone | % { 
                        Write-Verbose "Zone $PSItem "
                        Get-DnsServerResourceRecord -ZoneName $PSItem -ComputerName $PSItem -RRType cname | ? { $PSItem.RecordData.HostNameAlias -like "*$cpt*" } | FT -AutoSize 
                        }
		} else {
			Get-DnsServerResourceRecord -ZoneName $zonename -ComputerName $dnssrv -RRType cname | ? { $PSItem.RecordData.HostNameAlias -like "*$cpt*" } | FT -AutoSize 
		}
    }
}
function Get-LocalUser {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)][String[]]$Computer='.',
        [Parameter(Mandatory=$false)][String]$Name='*'
        )
    foreach($comp in $Computer) {
        $connexion = [ADSI]"WinNT://$Comp"
        $connexion.PSBase.Children | Where {$_.PSBase.SchemaClassName -eq 'user' -and $_.PSBase.Name -like $Name} | Select-Object -ExpandProperty name 
    }
}
function Get-LocalGroup {
    # Get-LocalGroup.ps1
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)][String]$Computer='.'
        )
    $connexion = [ADSI]"WinNT://$Computer"
    $connexion.PSBase.Children | Where {$_.PSBase.SchemaClassName -eq 'group'} | Select-Object -ExpandProperty Name
}
function Get-LocalGroupMember {
    # Get-LocalGroupMemberv2.ps1
    [CmdletBinding()]
    param (
           [Parameter(Mandatory=$false)][String]$Computer='.',
           [Parameter(Mandatory=$true)][String]$Group)
    $connexion = [ADSI]"WinNT://$Computer/$Group,group"
    $connexion.PSBase.Invoke('Members') | % {$_.GetType().InvokeMember('AdsPath', 'GetProperty', $null, $_, $null) }
}
function Get-LocalAdminGroupName {
    #Get-LocalAdminGroupName
    param (
        [Parameter(Mandatory=$false)]
        [String[]]$Computer='.'
    )
    $lang = Get-OSlanguage $Computer
    switch ($lang) {
        "FR" { $AdminsLocalGroup = "Administrateurs" }
        "EN" { $AdminsLocalGroup = "Administrators" }
    }
    return $AdminsLocalGroup
}
function Add-LocalGroupMember {
    # Add-LocalGroupMember.ps1
    [CmdletBinding()]
    param (
           [Parameter(Mandatory=$false)][String]$Computer='.',
           [Parameter(Mandatory=$true)][String]$Group,
           [Parameter(Mandatory=$true)][String]$User
       )
        write-verbose "Connexion à $Computer"
        try {
	        $connexion = [ADSI]"WinNT://$Computer/$Group,group"
        }catch {
	        write-host "impossible de se connecter à $Connexion"
	        write-host $_.Exception.Message.ToString()
	        exit 1 }
        write-verbose "Ajout de $User au groupe $Group"
        try { 
              $connexion.Add("WinNT://$User")
        }catch { write-host $_.Exception.Message.ToString() }
}
function Set-LocalUserPassword {
    [CmdletBinding()]
    param (
           [Parameter(Mandatory=$false)][String]$Computer='.',
           [Parameter(Mandatory=$true)][String]$Name,
           [Parameter(Mandatory=$true)][String]$Password
       )
        write-verbose "Vérification de l'existence du user $Name sur $Computer"
        if (Get-LocalUser -Computer $Computer -Name $Name) {
	        write-verbose "Connexion au serveur $Computer"
	        $cnx = [ADSI]"WinNT://$computer/$user,user"
	        write-verbose "Modification du mot de passe de $Name"
	        $cnx.setpassword($Password)
	        try { $cnx.setinfo()} catch { $_.Exception.Message.ToString() }
        }else { write-host "$Name inexistant sur $Computer" }
}
function New-LocalUser {
# New-LocalUser.ps1
[CmdletBinding()]
param (
       [Parameter(Mandatory=$false)][String]$Computer='.',
       [Parameter(Mandatory=$true)][String]$Name,
       [Parameter(Mandatory=$true)][String]$Password,
       [Parameter(Mandatory=$false)][String]$Description
       )
        $objMachine = [ADSI]"WinNT://$Computer"
        $objUser = $objMachine.Create('user', $Name)
        $objUser.SetPassword($Password)
        $objUser.PSBase.InvokeSet('Description', $Description)
        try { $objUser.SetInfo() } catch { $_.Exception.Message.ToString() }
}

# Lister les clés de registre à distance pour tous les DCs

Get-ADDomainController -Filter * |select name | % { iex "reg query \\$($_.Name)\HKLM\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters" }

# PowerCLI – RelocateVM()

[CmdLetBinding()]
param(
[Parameter(Mandatory=$true)]$VMCluster,
[Parameter(Mandatory=$False)][string[]]$VMlist,
[Parameter(Mandatory=$False)]$HostFilter="filter",
[Parameter(Mandatory=$False)]$DataStoreFilter="filter",
[Parameter(Mandatory=$true)][String]$VLANName
)
Import-Module MyTools
Add-PSSnapin VMware.VimAutomation.Core -PassThru
 
# Connexion au vCenter (fonctione prédéfinie dans le module Mytools
$vCenter = connectvcenter
 
# choix d'un HOST parmis les Host Connected et avec mémoire utilisé < 85%
$tgtHost = Get-Cluster -Name $VMCluster |Get-VMHost | ? { $PSItem.Name -like "*$HostFilter*" -and $PSItem.ConnectionState -eq "Connected" -and ($PSItem.MemoryUsageGB/$PSItem.MemoryTotalGB)*100 -lt 85 } | Get-Random
write-verbose "esx destination: $tgtHost"
$tgtDS = $tgtHost | Get-Datastore | ? { $PSItem.Name -Like "*$DataStoreFiler*" -and ($PSItem.FreeSpaceGB/$PSItem.CapacityGB)*100 -gt 25} | Get-Random
write-verbose "datastore destination: $tgtDS"
$target_pg = Get-VirtualPortGroup | ? Name -Like "*$VLANName*"
write-verbose "Port Group: $target_pg"
 
foreach ($vm_name in $VMlist) {
$vm = get-vm -name $vm_name -server $vCenter
write-verbose "Traitement de la VM: $vm"
if ($vm.PowerState -eq "Running") {
write-verbose "VM $vm Running"
write-verbose "disconnect vnic"
get-networkadapter -vm $vm |set-networkadapter -connected:$false -confirm:$false -Verbose| Out-Null
write-verbose "shutdown VM"
Shutdown-VMGuest -VM $vm -Verbose
} else {
write-verbose "Définition des spec pour la relocalisation"
$vm = Get-VM $vm_name | Get-View
$esx = Get-VMHost $tgtHost | Get-View
$parent = $esx.Parent
while($parent.Type -ne "Datacenter"){
$parent = (Get-View $parent).Parent
}
$dc = Get-View $parent
$spec = New-Object VMware.Vim.VirtualMachineRelocateSpec
write-verbose "Création de l'objet VMware.Vim.VirtualMachineRelocateSpec"
$spec.datastore = (Get-Datastore $tgtDS | Get-View).MoRef
$spec.host = $esx.MoRef
#$spec.Pool = (Get-Datacenter $dc.Name | Get-ResourcePool -Name "Resources" | Get-View).MoRef
$spec.Pool = ((Get-Datacenter $dc.Name |Get-ResourcePool).parent |? Name -EQ $VMCluster |Get-View).resourcepool
write-verbose "****** Lancement de la relocalisation *****"
$vm.RelocateVM($spec,"defaultPriority")
# a faire
#Get-Task |? {$PSItem.Name -EQ "RelocateVM_Task" -and $PSItem.objectid -like "*$($vm.moref.value)" }
write-verbose "****** Fin de la relocalisation *****"
write-verbose "Modification du network"
Set-VMVlanNetwork -VMName $vm_name -VLANName $VLANName -Verbose
}
}

 

#Remote Desktop

Activer le RD

Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections -Value 0

# Firewall

desactiver le firewall windows

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

# Hyper-V

Recherche VM dans SCVMM – script Search-VM.ps1

param(
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[ValidateLength(6,12)]
[string] $Name
)
Clear-Host
$snapin="Microsoft.SystemCenter.VirtualMachineManager"
if (get-pssnapin $snapin -ea "silentlycontinue") {
write-host "PSsnapin $snapin is loaded"
}
elseif (get-pssnapin $snapin -registered -ea "silentlycontinue") {
write-host "PSsnapin $snapin is registered but not loaded"
write-host "Loading PSSnapin, please wait...."
Add-PSSnapin $snapin
}
else {
write-host "PSSnapin $snapin not found" -foregroundcolor Red
exit
}
#Cnx to SCVMM Server
#Get-VMMServer -ComputerName -Credential (Get-Credential)
#
$VMMServers = @("scvmm_server1", "scvmm_server2")
write-host "Serveur SCVMM utilisé: "$VMMServers
write-host "Enregistrement des credentiels"
if (!$cred) {$GLOBAL:cred=(Get-Credential)}
$VMMServers | % {
Write-Host "Connexion au Serveur SCVMM:" $_
$vmmsrv = Get-VMMServer $_ -cred $cred
Write-Host "=========================================================================================="
Get-VM -name $Name |%{ "{0} is managed by {1} on cluster {2} `n" -f $_.Name, $_.HostName, (($_.VMHost).HostCluster).ClusterName ; break }
"Nothing in $_ `n"
}

 Recherche HOST dans SCVMM – Script Search-HOST.ps1

param(
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[ValidateLength(6,12)]
[string] $Name
)
Clear-Host
$snapin="Microsoft.SystemCenter.VirtualMachineManager"
if (get-pssnapin $snapin -ea "silentlycontinue") {
write-host "PSsnapin $snapin is loaded"
}
elseif (get-pssnapin $snapin -registered -ea "silentlycontinue") {
write-host "PSsnapin $snapin is registered but not loaded"
write-host "Loading PSSnapin, please wait...."
Add-PSSnapin $snapin
}
else {
write-host "PSSnapin $snapin not found" -foregroundcolor Red
exit
}
#Cnx to SCVMM Server
#Get-VMMServer -ComputerName  -Credential (Get-Credential)
#
$VMMServers = @("scvmm_server1", "scvmm_server2")
write-host "Serveur SCVMM utilisé: "$VMMServers
 
write-host "Enregistrement des credentiels"
if (!$cred) {$GLOBAL:cred=(Get-Credential)}
 
$VMMServers | % {
	Write-Host "Connexion au Serveur SCVMM:" $_
	$vmmsrv = Get-VMMServer $_ -cred $cred
	Write-Host "================================================================================"
	Get-VMHost -VMMServer $vmmsrv | %{if ($_.ComputerName -like $Name ) { "host {0} is managed by Cluster: {1} `n" -f $Name, $_.HostCluster.Name; break } }
	"Nothing in $_ `n"
}

Modifier le BootOrder d’une seule VM

$bootorder = "IdeHardDrive","CD","Floppy","PxeBoot"
Set-VM -VM vm_name -BootOrder $bootorder –Verbose

Modifier le BootOrder de plusieurs VM

$bootorder="IdeHardDrive","CD","Floppy","PxeBoot"
$list = gc list-vm.txt
$list | %{ Stop-VM –VM $_ ; Set-VM -VM $_ -BootOrder $bootorder –Verbose ;Start-VM –VM $_ }

Visualiser le paramètre BootOrder

Pour toutes les VMs du fichier list-vm.txt :

$scvmmserver=Read-Host -Prompt "Nom du serveur SCVMM"
$cred=get-credential
$bootorder="IdeHardDrive","CD","Floppy","PxeBoot"
$list = gc list-vm.txt
Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
Get-VMMServer –ComputerName $scvmmserver -credential $cred
$list | %{ (Get-VM -Name $_).BootOrder } | out-file -append vm_bootorder.txt

Retrouver la version des IC « Integration Components »

sigcheck -q -n c:\Windows\System32\drivers\vmbus.sys

icversnio_sigcheck

Sur une VM avec OS 2008R2 seulement

reg query "HKLM\SOFTWARE\Microsoft\Virtual Machine\auto" /v integrationservicesversion

icversion

Script Check-ICVersion

param(
[string]$vmName = $(throw "Must specify virtual machine name")
)
$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName'"
 
# Get the associated KVP Exchange component
$kvp = gwmi -namespace root\virtualization `
-query "Associators of {$vm} where ResultClass=Msvm_KvpExchangeComponent"
 
# Pull the Guest Intrinsic Exchange Items from XML into a hash
$kvpHash = @{}
if($kvp.GuestIntrinsicExchangeItems){
$xmlContents = ([xml]("<xml>"+$kvp.GuestIntrinsicExchangeItems+"</xml>"))
foreach($instance in $xmlContents.xml.INSTANCE)
{
$name = $instance.PROPERTY | where {$_.NAME -eq "Name"}
$data = $instance.PROPERTY | where {$_.NAME -eq "Data"}
$kvphash.add($name.Value,$data.Value)
}
}
# Save the guest's version
$icVersionGuest = $kvpHash.IntegrationServicesVersion
# Save the host's version
$icVersionHost = (ls 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestInstaller').`
GetValue("Microsoft-Hyper-V-Guest-Installer-Win60-Package")
return -not ([version]$icVersionGuest -lt [version]$icVersionHost)

source du script: ??

# Modules

Lister les modules disponibles

Get-Module –ListAvailable

 # Fichier

Lister la version d’un fichier

(Get-Item C:\Windows\system32\vmicsvc.exe).versioninfo | Select FileVersion

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>