Показаны сообщения с ярлыком PowerShell. Показать все сообщения
Показаны сообщения с ярлыком PowerShell. Показать все сообщения

вторник, 28 августа 2012 г.

Could not connect using the requested protocol

Неожиданно команда PowerCLI Connect-VIServer VI.SERVER.NAME стала выдавать ошибку:
PowerCLI D:\VMware\Infrastructure\vSphere PowerCLI> Connect-VIServer VI.SERVER.NAME
Connect-VIServer : 11/22/2011 7:35:37 AM Connect-VIServer Could not connect using the requested protocol.
At line:1 char:17
+ Connect-VIServer <<<<  VI.SERVER.NAME
+ CategoryInfo : ObjectNotFound: (:) [Connect-VIServer], ViServerConnectionException
+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_ProtocolError,VMware.VimAutomation.ViCore.Cmd

Оказалось что проблема в том, что используется прокси сервер. В моем случае достаточно было просто отключить прокси в настройках IE, т.к. на сервере Inet не требуется. Более правильный случай описан в KB:


1. Посмотреть вывод команды
Get-PowerCLIConfiguation

2. Убеждаемся что используем системные настройки прокси:
C:\PS>Get-PowerCLIConfiguration
Proxy Policy Default Server
                               Mode
-------------------------       ---------------
UseSystemProxy      Single
Note: This output indicates that the PowerCLI is using the System Proxy.
3. Для отключение использования прокси в PowerShell выполняем команду:
Set-PowerCLIConfiguration -ProxyPolicy NoProxy -Confirm
4. И смотрим вывод команды:
C:\PS>Set-PowerCLIConfiguration -ProxyPolicy NoProxy -Confirm
Perform operation?
Performing operation 'Update vSphere PowerCLI configuration.'?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): y
Proxy Policy Default Server
                     Mode
------------         ---------------
NoProxy              Single 

Источник

понедельник, 26 декабря 2011 г.

Работа с DNS с помощью PowerShell.

На полноценный пост конечно не тянет, но может быть кому-нибудь будет полезно.

Недавно я с удивлением обнаружил что работа с DNS с помощью PowerShell почти никак не реализовано. Точнее единственный приличный вариант, найденный мной, это работа через WMI.

Итак, для создания DNS записи A-типа можно выполнить нижеследующий скрипт :
#Создание записи в DNS
$OwnerName = "Server.domainname";
$IPAddress = "10.10.10.1";

$DnsServerName = "DNSserver.domainname";
$ContainerName = " domainname ";
$RecordClass = "1";
$TTL = "3600";


$dnsAType = [wmiclass]"\\ DNSserver.domainname\root\MicrosoftDNS:MicrosoftDNS_AType"
$dnsAType.CreateInstanceFromPropertyData($DnsServerName, $ContainerName, $OwnerName, $RecordClass, $TTL, $IPAddress)
А так же скрипт для удаления DNS записи:

$ServerName = Read-Host "Введите имя сервера";
#$ServerFullName = "$ServerName" + ".domainname";
$FilterValue = "OwnerName='" + "$ServerName" + ".domainname'";
Get-WmiObject -namespace ".domainname\MicrosoftDNS" -class MicrosoftDNS_AType -ComputerName rccf.ru -Filter "$FilterValue" | Remove-WmiObject
Ссылки по теме: 1 и 2 и 3

вторник, 5 апреля 2011 г.

Массовое переключение ВМ в другую портгруппу

Предположим, у вас меняется сетевая политика для виртуальных машин и вы создаете новые портгруппы. Или вы решили мигрировать на Distributed vSwitch. Соотв. есть много (поэтому вручную не вариант, или просто лень) ВМ, подключенных в одну портгруппу, и их надо переключить в другую.

Решение - PowerShell! :)

Как это сделал я для своего тестового кластера. Сначала создал Distributed vSwitch с одним аплинком (с каждого хоста) и на нем новую портгруппу для ВМ. Затем переключил пару включенных машин вручную, проверив, что они остались доступны. И оставшиеся N-цать выключенных переключил уже скриптом:

Get-Cluster "Cluster" | Get-VM | Where-Object {$_.PowerState -eq "PoweredOff"} | Get-NetworkAdapter | where { $_.Name -eq "Network Adapter 1" } | Set-NetworkAdapter -NetworkName "dv VM Network" -Confirm:$false
Скопипастил отсюда

вторник, 29 марта 2011 г.

Настройка Round Robin Multipathing с помощью Powershell

Ниже процитирован скрипт для смены режима Multipathing на Round Robin.

Connect-VIServer vcenter.nh.novant.net
$h = get-vmhost testvsphere.nh.novant.net
$hostView = get-view $h.id
$policy = new-object VMware.Vim.HostMultipathInfoLogicalUnitPolicy
$policy.policy = "rr"
$storageSystem = get-view $hostView.ConfigManager.StorageSystem
$storageSystem.StorageDeviceInfo.MultipathInfo.lun |
where { $_.Path.length -gt 1 } |
foreach { $storageSystem.SetMultipathLunPolicy($_.ID, $policy) }

вторник, 18 января 2011 г.

Изменение Notes для нескольких VM


Задача: Необходимо у списка VM поменять notes.

1. Создаем csv файл следующего содержания:
VMName,Note
VM1,Domain Controller
VM2,Database Server
2. Запускаем:
Import-Csv "D:\*.csv" | % { Set-VM $_.VMName -Description $_.Note -Confirm:$false}

И получаем:

Onyx - создание скриптов от VMware

У Майкрософт есть хорошая штука - PowerShell.
У VMware есть хороший аддон к ней - PowerCLI.
Вооружившись этой парой, можно удобно управлять инфраструктурой - командная строка, скрипты и т.п.

1) По ссылке скачали архив, распаковали, запустили исполняемый файл.
Нажали звездочку, и указали адрес vCenter.


2) Клиентом vSphere подключаемся на ту машину и порт, где запущен Onyx.

3) В окне Onyx нажать пиктограмму начала записи, и в клиенте vSphere выполнить действия, которые мы хотели бы заскриптовать. В окне Onyx появится готовый скрипт для этого!
Левая из обведенных пиктограмм сохранит содержимое окна в файл скрипта PowerShell.
Те скрипты, на которых экспериментировал я, выполнялись и делали нужную работу без дополнительных усилий с моей стороны.
В Onyx я сохранил скрипт под именем ps_start_SQL_VM.ps1.
В PowerCLI я запустил файл с таким именем.

вторник, 11 января 2011 г.

Управление VM с помощью PowerCLI

Наткнулся на статью в KB по управлению VM. Хотя там и написаны основы, но 2 очень важных момента там есть:
  • конфигурация сети виртуальной машины
  • выгрузка свойств виртуальной машины, в том числе VMID
Get-VM vmname | Format-List - информация, о VM

дальше цитата:
Collecting information about the virtual machine
This section discusses the commands that can be used to collect detailed information about the virtual machine. This article provides an overview of the commands they can be customized according to the needs.
Collecting information about virtual machine hardware
To get a list of all the virtual machines in the inventory and their name, power state, number of CPUs, and configured memory, run the cmdlet:

[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM

Name PowerState Num CPUs Memory (MB)
---- ---------- -------- -----------
NW PoweredOff 1 512
PowerCLI PoweredOn 1 1024

Note: This command provides information about the version, virtual hardware attached(virtual disk, network, CD-ROM), datastore, host, HA restart and isolation properties:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM windows-dc | Format-List *
Collecting information about the virtual machine guest operating system
vSphere PowerCLI provides cmdlets to retrieve the details about the virtual machine guest operating system. These cmdlets are independent of the guest operating system installed in the virtual machine.
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VMGuest -VM windows-dc | Format-List *

OSFullName : Microsoft Windows Server 2003, Enterprise Edition (64-bit)
IPAddress : {10.112.102.7}
State : Running
HostName : windows-dc.vcd.com
Nics : {}
ScreenDimensions : {Width=1024, Height=768}
Note: When retrieving the details about the guest operating system, you are prompted for the user name and password for the ESX/ESXi host and guest operating system. You can provide the authentication details in the command by using the -HostUser root -HostPassword pass1 -GuestUser administrator -GuestPassword vmware123 parameters.
Using PowerCLI you can also query, start, or stop a service within the guest operating system. You can use Start-Service, Stop-Service, and Restart-Service cmdlets to modify the status of the service. If no virtual machine is specified in the command the change is be made on all the Windows virtual machines in the inventory.
Note: To use this command ensure that the latest version of VMware Tools are installed on the Virtual Machine and this cmdlet is applicable only for Windows Guest.
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM windows-dc | Invoke-VMScript "Get-Service app*"
Status Name DisplayName
------ --- -----------
Stopped AppMgmt Application Management
vSphere PowerCLI also provides cmdlets to provide the Network Configuration information from within the guest operating system:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VMGuestNetworkInterface -VM windows-dc -HostUser root -HostPassword vmware123 -GuestUser administrator -GuestPassword vmware123

VMId : VirtualMachine-vm-33
VM : windows-dc
NetworkAdapter : Network adapter 1
SubnetMask : 255.255.252.0
NicId : VirtualMachine-vm-33/4000
Name : Local Area Connection
IPPolicy : Static
Ip : 10.112.102.7
Dns : {127.0.0.1}
DefaultGateway : 10.112.103.254
Description : Intel(R) PRO/1000 MT Network Connection
Mac : 00-0C-29-30-F3-11
RouteInterfaceId : 0x10003
Uid :
/VIServer=@10.112.101.9:443/VMGuestNetworkInterface=00-0C-29
-30-F3-11/
DnsPolicy : Static
WinsPolicy : Static
Wins :
To retrieve the routing configuration of the specified virtual machine, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VMGuestroute -VM windows-dc -HostUser root -HostPassword vmware123 -GuestUser administrator -GuestPassword vmware123

Destination : 0.0.0.0
Gateway : 10.112.103.254
Interface : 10.112.102.7
Netmask : 0.0.0.0
VMId : VirtualMachine-vm-33
VM : windows-dc
Configuring a virtual machine using PowerCLI
This section discusses the cmdlets that you can use to configure/reconfigure the virtual machines.
To create new virtual machines, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> New-VM -VMHost 10.112.96.17 -Name TestCli -MemoryMB 1024 -DiskMB 8024
Name PowerState Num CPUs Memory (MB)
---- ---------- -------- - ----------
TestCli PoweredOff 1 1024
To migrate a virtual machine using vMotion, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VMHost 10.112.96.18 | Get-VM "windows-cli" | Move-VM -Destination 10.112.96.17
Name PowerState Num CPUs Memory (MB)
---- ---------- -------- -----------
windows-cli PoweredOn 1 1024
To migrate a virtual machine using Storage vMotion, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM windows-rhel5 | Move-VM -Datastore vCloud-1
Name PowerState Num CPUs Memory (MB)
---- ---------- -------- -----------
windows-rhel5 PoweredOn 1 3072
All of the virtual machines in the in the inventory can be configured with or without the CD-ROM drive using this command:
Note: To disable CD-ROM, use the $false option. To enable CD-ROM, use the $true option.
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM | Get-CDDrive | Set-CDDrive -Connected:$false
Confirm
Are you sure you want to perform this action?
Performing operation "Setting Connected: False, NoMedia: False." on Target "CD/DVD Drive 1".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):Y
Working with virtual machine snapshots
vSphere PowerCLI provides cmdlets to create/remove snapshots for all of the virtual machines in the inventory. However, you may further customize the command to specify virtual machines from a specific ESX/ESXi Host, Cluster, or Datacenter.
To take a new snapshot for all virtual machines in a Cluster, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-Cluster "vCloud" | Get-VM | New-Snapshot -Name Automate
Name Description PowerState
---- ----------- ----------
Automate PoweredOff
Automate PoweredOff
To remove a snapshot from all of the virtual machine in the inventory, run the cmdlet:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-VM | Get-Snapshot | Remove-Snapshot
Confirm
Are you sure you want to perform this action?
Performing operation "Removing snapshot." on Target
"VirtualMachineSnapshot-snapshot-174".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):A
Note: Use the preceding commands with caution as the changes made are applicable for all virtual machines.
Updating VMware Tools
Update-Tools cmdlets can be used to update the VMware Tools on a single or multiple virtual machines. This command reboots the virtual machine after updating the VMware Tools. You can use the -NoReboot option to update the VMware Tools without rebooting the virtual machine.
In this example, the VMware Tools for all of the virtual machines in Resource Pool vCloud will be updated without rebooting the virtual machine:
[vSphere PowerCLI] C:\Program Files\VMware\Infrastructure\vSphere PowerCLI> Get-ResourcePool vcloud | Get-VM | Update-Tools -NoReboot
WARNING: Automatic update of VMware tools is not fully supported for
non-Windows OSs. Manual intervention might be required.
Note: Before running the cmdlet, ensure that the VMware Tools service is running. This command is used only to upgrade VMware Tools. To do an unattended install, use msiexec.exe. For more information, see The Microsoft article Use Windows Installer from the command line.

понедельник, 13 декабря 2010 г.

Ввод компьютера в домен с помощью PowerShell

Не каждый знает что в домен ввести компьютер можно из cmdlets - это быстрее чем лазать по менюшкам :)

C:\PS>add-computer -domainname Domain01 -cred Domain01\Admin01
C:\PS>restart-computer

Установка Remote Server Administration Tools for Windows 7

1. On a computer that is running Windows 7, download the Remote Server Administration Tools for Windows 7 package from the Microsoft Download Center.

2. Open the folder into which the package downloaded, and double-click the package to unpack it, and then start the Remote Server Administration Tools for Windows 7 Setup Wizard.

Important: You must accept the License Terms and Limited Warranty to start to install the Administration Tools pack.

3. Complete all the steps that you must follow by the wizard, and then click Finish to exit the wizard when installation is completed.

4. Click Start, click Control Panel, and then click Programs.

5. In the Programs and Features area, click Turn Windows features on or off.

6. If you are prompted by User Account Control to enable the Windows Features dialog box to open, click Continue.

7. In the Windows Features dialog box, expand Remote Server Administration Tools.

8. Select the remote management tools that you want to install.

9. Click OK.

10. Configure the Start menu to display the Administration Tools shortcut, if it is not already there.

• Right-click Start, and then click Properties.

• On the Start Menu tab, click Customize.

• In the Customize Start Menu dialog box, scroll down to System Administrative Tools, and then select Display on the All Programs menu and the Start menu. Click OK. Shortcuts for snap-ins installed by Remote Server Administration Tools for Windows 7 are added to the Administrative Tools list on the Start menu.

Источник

Использование PowerShell Cmdlets для администрирования Active Directory

Using Microsoft's New AD PowerShell Cmdlets

In the past two weeks I have really started playing with the new AD PowerShell cmdlets from Microsoft.  I am really glad these cmdlets are finally here.  I will admit though, to get the working in my lab, it was not easy.  I cant blame this though on the cmdlets themselves, as my problems stemmed from the fact that I don't have 64-bit virtualization capability yet in my own lab.

First I want to briefly explain what has to be in order to use the cmdlets:

  1. You must have the cmdlets themselves, they are part of the ActiveDirectory module for PowerShell v2.  This module is a Windows Feature that can be installed on Windows 7, 2008, and 2008 R2.  Life is super simple if you have a 2008 R2 Domain Controller, as you are good to go to import and use the module on that machine.  When you promote an R2 server to a DC, I believe that the AD PowerShell Module Windows feature is installed automatically.  For Windows 7 and 2008 (non R2), you need to install the latest RSAT (Remote Server Admin Tools) and then add the Windows Feature for the PowerShell AD Module.
  2. Once you have the module physically installed, you must import the module in your PowerShell v2 session.  This is as simple as typing PS C:\> Import-Module ActiveDirectory
  3. You must have an Active Directory Web Service (ADWS) Implemented on at least one of your Domain Controllers.  Any new 2008 R2 DC will have this new service.  If you haven't yet deployed a 2008 R2 DC, then you can install the ADWS on a down-level DC by installing the Active Directory Management Gateway Service.

Once these three steps are in place you can then use the cmdlets.  You can see the cmdlets a few ways, but perhaps the easiest is to do this: PS C:\> Get-Command -Module ActiveDirectory

By running the above cmdlet I found the following cmdlets:

Add-ADComputerServiceAccount
Add-ADDomainControllerPasswordReplicationPolicy
Add-ADFineGrainedPasswordPolicySubject
Add-ADGroupMember
Add-ADPrincipalGroupMembership
Clear-ADAccountExpiration
Disable-ADAccount
Disable-ADOptionalFeature
Enable-ADAccount
Enable-ADOptionalFeature
Get-ADAccountAuthorizationGroup
Get-ADAccountResultantPasswordReplicationPolicy
Get-ADComputer
Get-ADComputerServiceAccount
Get-ADDefaultDomainPasswordPolicy
Get-ADDomain
Get-ADDomainController
Get-ADDomainControllerPasswordReplicationPolicy
Get-ADDomainControllerPasswordReplicationPolicyUsage
Get-ADFineGrainedPasswordPolicy
Get-ADFineGrainedPasswordPolicySubject
Get-ADForest
Get-ADGroup
Get-ADGroupMember
Get-ADObject
Get-ADOptionalFeature
Get-ADOrganizationalUnit
Get-ADPrincipalGroupMembership
Get-ADRootDSE
Get-ADServiceAccount
Get-ADUser
Get-ADUserResultantPasswordPolicy
Install-ADServiceAccount
Move-ADDirectoryServer
Move-ADDirectoryServerOperationMasterRole
Move-ADObject
New-ADComputer
New-ADFineGrainedPasswordPolicy
New-ADGroup
New-ADObject
New-ADOrganizationalUnit
New-ADServiceAccount
New-ADUser
Remove-ADComputer
Remove-ADComputerServiceAccount
Remove-ADDomainControllerPasswordReplicationPolicy
Remove-ADFineGrainedPasswordPolicy
Remove-ADFineGrainedPasswordPolicySubject
Remove-ADGroup
Remove-ADGroupMember
Remove-ADObject
Remove-ADOrganizationalUnit
Remove-ADPrincipalGroupMembership
Remove-ADServiceAccount
Remove-ADUser
Rename-ADObject
Reset-ADServiceAccountPassword
Restore-ADObject
Search-ADAccount
Set-ADAccountControl
Set-ADAccountExpiration
Set-ADAccountPassword
Set-ADComputer
Set-ADDefaultDomainPasswordPolicy
Set-ADDomain
Set-ADDomainMode
Set-ADFineGrainedPasswordPolicy
Set-ADForest
Set-ADForestMode
Set-ADGroup
Set-ADObject
Set-ADOrganizationalUnit
Set-ADServiceAccount
Set-ADUser
Uninstall-ADServiceAccount

 

On the PowerShell Team Blog they posted a great write-up and a really nice graphic showing the cmdlets organized logically

I hope this is a short and sweet guide to help get the cmdlets working for you!

Источник

вторник, 3 августа 2010 г.

Запуск скриптов PowerShell по расписанию

Создаем новый текстовый документ, куда добавляем следующую строчку (без переводов строки):

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -NoExit -Command C:\first.ps1

Затем сохраняем его как .bat-файл и добавляем в планировщик Windows.

Источник

четверг, 20 мая 2010 г.

vCheck - скрипт PowerCLI для получения отчетов о vSphere

Бесплатный скрипт PowerCLI для получения отчетов о VMware vSphere 4 / ESX - vCheck

На сайте Virtu-Al.net коллега Alan Renouf выложил бесплатный скрипт vCheck, предназначенный для сбора информации о виртуальной инфраструктуре VMware vSphere 4, хостах ESX и vCenter. Для запуска скрипта потребуется использовать интерфейс VMware vSphere PowerCLI. Результатом работы скрипта будет следующая информация:

  • Основное
    Число хостов ESX
    Число виртуальных машин
    Число шаблонов
    Число кластеров
    Число виртуальных хранилищ (Datastores)
    Число запущенных (активных) виртуальных машин
    Число остановленных виртуальных машин
    Количество миграций DRS за последние несколько дней
  • Снапшоты, которые старше, чем заданное количество дней
  • Виртуальные хранилища (Datastores) с менее, чем заданным процентом свободного пространства
  • Виртуальные машины, созданные за последние X дней
  • Виртуальные машины, удаленные за последние X дней
  • Виртуальные машины без VMware Tools
  • Виртуальные машины с подключенным CD-ROM
  • Виртуальные машины с подключенным Floppy Drive
  • Виртуальные машины на локальных хранилищах
  • Виртуальные машины, где счетчик CPU ready превышает X%
  • Виртуальные машины, у которых число vCPU превышает заданное количество
  • Список миграций DRS
  • Хосты ESX в Maintenance Mode
  • Хосты ESX в состоянии disconnected
  • Проверка NTP-сервера по заданному имени
  • Сообщения лога vmkernel warning за последние X дней
  • Сообщения лога vCenter за последний X дней
  • Сообщения лога vCenter (Windows Event Log Errors) за последние X дней
  • Детали сервиса VMware vCenter Service
  • В начале скрипта можно выключить не требующиеся секции отчета
  • Активные тревоги, привязанные к ВМ
  • Активные тревоги, привязанные к кластеру
  • Активные тревоги, привязанные к хосту ESX
  • Недоступные iSCSI LUN
  • Проверка vSphere: размеры слотов для VMware HA
  • Проверка vSphere: устаревшая версия виртуального Hardware (меньше версии 7)

Сам скрипт vCheck v3 можно скачать по данной ссылке: http://virtu-al.net/Downloads/vCheck/vCheckV3.txt

Источник

Local Plugin Creator - Плагины на основе веб-интерфейсов.


Local Plugin Creator - прикручиваем свои окна как плагины к VMware vSphere Client.

Интересную штучку сделал Alan Renouf с помощью PowerCLI / PowerShell для VMware vSphere Client. Бесплатная утилита для VMware vSphere называется Local Plugin Creator и позволяет создавать свои собственные плагины для VMware vSphere на базе веб-интерфейсов от продуктов для управления виртуальной инфраструктурой VMware. Это позволит не переключаться постоянно между множеством окон, а просто выбирать вкладку в vSphere Client для нужного средства.

Итак, запустив Local Plugin Creator в виде скрипта PowerCLI, мы видим окно.

Здесь просто вбиваем URL нужной страницы, которую нам необходимо подцепить в качестве плагина к VMware vSphere Client, а также вкладку, где этот плагин будет показан, и нажимаем Create Plugin.

Источник

PowerShell - выполнение скриптов запрещено.

По умолчанию в windows запрещено запускать скрипты PowerShell.

Решение простое - в консоле PowerShell Выполнить:

"Set-ExecutionPolicy remotesigned " - Подразумевает, что вы будете запускать только подписанные скрипты.

"Set-ExecutionPolicy Unrestricted " - Запуск любых скриптов.