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

понедельник, 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

пятница, 12 августа 2011 г.

Использование WMI-фильтров

Начну с цитаты из wiki:
Windows Management Instrumentation (WMI) в дословном переводе — это инструментарий управления Windows. Если говорить более развернуто, то WMI — это одна из базовых технологий для централизованного управления и слежения за работой различных частей компьютерной инфраструктуры под управлением платформы Windows.
Технология WMI — это расширенная и адаптированная под Windows реализация стандарта WBEM (на англ.), принятого многими компаниями, в основе которого лежит идея создания универсального интерфейса мониторинга и управления различными системами и компонентами распределенной информационной среды предприятия с использованием объектно-ориентированных идеологий и протоколов HTML и XML.
В основе структуры данных в WBEM лежит Common Information Model (CIM), реализующая объектно-ориентированный подход к представлению компонентов системы. CIM является расширяемой моделью, что позволяет программам, системам и драйверам добавлять в неё свои классы, объекты, методы и свойства.
WMI, основанный на CIM, также является открытой унифицированной системой интерфейсов доступа к любым параметрам операционной системы, устройствам и приложениям, которые функционируют в ней.
WMI - это классная возможность использовать фильтры, построенные на различных условиях и выборках. Возможно, потом подготовлю серию статей по использованию данного механизма. На данный момент напишу один из вариантов использования: WMI-фильтр для GPO.

Чтобы применить выбранную политику GPO только на определенную версию версию Windows достаточно использовать фильтр
select * from Win32_OperatingSystem where Version like "6.%" and ProductType = "1"
более подробно об использовании GPO

среда, 27 июля 2011 г.

KMS Key для Windows 2008 и Windows7

Иногда вновь созданный (или развернутый из "эплайнса") сервер не видит сервер KMS и требует активацию.

Решение - прописать ключ для активации через KMS.

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

Переименование подключения Windows

Намного лучше, когда подключения на всех серверах называются одинаково, например все интерфейсы, подключенные в доменную сеть называть "Domain Network".
Как же это сделать на уже созданных серверах?
С помощью команды netsh.

netsh interface set interface name="Local Area Connection" newname="NewLan"

netsh может работать удаленно, а если речь о виртуальных серверах VMware, то данную команду можно выполнить на всех VM сразу:

Get-VM | Invoke-VMScript –ScriptText “netsh interface set interface name=""Local Area Connection"" newname="NewLan"” –ScriptType Bat –guestuser DomainAdmin –GuestPassword Password
Зачем нужна команда Netsh

вторник, 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) }

среда, 2 марта 2011 г.

Создание резервной копии базы vCenter

У многих база vCentr'а располагается на локальном SQL Express. Возникает вопрос с бекапом базы. Есть Отличная утилита Data Migration Tool, но она не работает с vCenter 4.1. Выход - использование SQL Server Management Studio Express. Процитирую источник:

Creating a Backup Script

If you don’t have SQL Server Management Studio Express installed already, download and install it now.

Fire it up and log on with a user that has sufficient permissions to access the vCenter database

Find your vCenter database by expanding Databases and select VIM_VCDB

Right click on VIM_VCDB and select Tasks and then Back Up…

This opens the Back Up Database window, where you set your backup options. Set your options in a manner that fits your environment. You can set options like the backup file location, retention policy etc.

So far, this is all fine and dandy. You can create a manual backup this way, without much hassle. How can we turn that into a scheduled job?
The first bit is to turn your backup options into a SQL script that can be scheduled. You do this by finding the Script drop-down menu on the top of the Backup Database window. Select Script Action to New Query Window.

This opens the script window, where you can see the script and test it to make sure it works as intended.

The next step is to save the generated script, you do so my going to File and select Save … As. I’ve created a folder called c:\scripts\ that I use to store my SQL scripts in, so I’ll save the backup script there as FullBackupVCDB.sql.

Scheduling the Backup Script

Now that we have a working backup script, we need to be able to schedule it to run. As we can’t do that within the SQL Server Management Studio Express application, we need to find another way of scheduling it. Windows Server 2008 R2 (and other versions) include a scheduling tool, and that’s what we’ll use to create our schedule.

On my standard vCenter installation, the SQL Server is installed in the default location of C:\Program Files (x86)\Microsoft SQL Server\. This means that the actual command we need to schedule will be (be sure to replace the server-/instance-name and script name if your values differ from mine):

“C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE” -S [servername]\SQLEXP_VIM -i c:\scripts\FullBackupVCDB.sql

Go to the Control Panel and select Schedule Tasks. Click Create Basic Task, give it a name and set an appropriate schedule.

Select Start a program as the action for the task, and when it asks for Program/Script enter “C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE” -S [servername]\SQLEXP_VIM -i c:\scripts\FullBackupVCDB.sql.

Click next and check the box that says Open the Properties dialog for this task when I click Finish then click Finish. In the VCDB Backup properties, make sure the Run whether user is logged on or not option is selected, to make sure the schedule runs as planned.

Once you have verified that the schedule works as intended, make sure that you include the location for your vCenter database in your regular backup scheme, and you should we a lot safer than you were.

Источник

пятница, 25 февраля 2011 г.

Поиск и удаление строки в Word с помощью VBA

Сегодня появилась интересная задача:
В 200 страничном документе Word найти определенное слово и удалить не только его, а всю строку, в которой это слово стоит.

Очень помог гугл и сайт cyberforum.ru.

Итоговый скрипт:
' Скрипт ищет строки с определенным словом и удаляет ее.
Sub DeleteLine()
Dim DeleteLine As String
DeleteLine = InputBox("Введите слово для удаления строки", "Удаляем строки")
If DeleteLine = Empty Then Exit Sub
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
.ClearFormatting
.Text = DeleteLine
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
While .Execute
.Parent.Select
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Delete
Wend
End With
Application.ScreenUpdating = True
End Sub

среда, 19 января 2011 г.

Автоматизация действий с помощью Keepass.

Оказывается Keepass можно использовать не только для хранения паролей, но и для автоматического заполнения форм. А еще и для автоматизации выполнениейрутинных действий. Опубликую ссылку на FAQ.

вторник, 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!

Источник

вторник, 23 ноября 2010 г.

Как обновить VMware ESX4 без Update Manager

Многие пользователи используют VMware ESX в окружениях, где не установлен продукт VMware Update Manager, позволяющий централизованно обновлять хост-серверы. В этом случае может оказаться полезной процедура обновления VMware ESX из консоли (Service Console).

1. Первый способ (только VMware ESX).

Например, чтобы обновиться на VMware ESX 4 Update 1 нужно:
Скачать дистрибутив обновления в zip-архиве. 
Положить его на VMware ESX, например, используя Veeam FastSCP.
Выполнить команду в сервисной консоли VMware ESX:

esxupdate --bundle=ESX-4.0.0-update01.zip update

2. Второй способ (VMware ESX и VMware ESXi).

Есть также и второй способ (подходит как для VMware ESX, так и для VMware ESXi) с помощью скрипта vihostupdate.pl. Перед использованием данной команды необходимо перевести хост ESX в maintenance mode.

Эта команда для ESX и ESXi выполняется из RCLI. Имя пользователя и пароль указывать не обязательно (их спросят во время выполнения команды). Например, для обновления ESX 4 или ESXi 4 можно использовать следующие команды:

Получение информации об имеющихся обновлениях:

C:\Program Files\VMware\VMware vSphere CLI\bin>vihostupdate.pl --server 192.168.1.30 --username root --password XXX –query

Сканирование хоста на наличие конкретного установленного обновления:

C:\Program Files\VMware\VMware vSphere CLI\bin>vihostupdate.pl --server 192.168.1.30 --username root --password XXX --bundle c:\esx400-200906001.zip –scan

Загрузка обновления в zip-архиве на сервер и применение его к хосту ESX / ESXi:

C:\Program Files\VMware\VMware vSphere CLI\bin>vihostupdate.pl --server 192.168.1.30 --username root --password XXX --bundle c:\esx400-200906001.zip –install

Результатом успешного обновления будет следующее сообщение:

The update completed successfully, but the system needs to be rebooted for the changes to be effective.

вторник, 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.

Источник

понедельник, 12 июля 2010 г.

Обновление ESX4 с помощью vSphere CLI

1. Скачать обновления в виде zip-файлов с vmware.com

2. Запустить vSphere CLI.

3. Перевести сервер в Maintenance Mode  из vSphere Client.

4. Проверка установленных обновлений:

C:\Program Files\VMware\VMware vSphere CLI\bin>vihostupdate.pl --server 192.168.18.110 --username root --password XXXXXX –query

5. Установка обновлений с помощью команды:

C:\Program Files\VMware\VMware vSphere CLI\bin>vihostupdate.pl --server 192.168.18.110 --username root --password XXXXXX --bundle c:\esx400-200906001.zip –install

Через некоторое время должно появится сообщение об успешной установке:

The update completed successfully, but the system needs to be rebooted for the changes to be effective.

6. Перезагрузить и вывести из Maintenance Mode.