Управление виртуальными машинами hyper v powershell
управление виртуальными машинами Windows с помощью PowerShell Direct
применимо к: Windows server 2022, Windows 10, Windows Server 2016, Windows Server 2019
PowerShell Direct можно использовать для удаленного управления Windows 10, Windows Server 2016 или виртуальной машиной Windows server 2019 с Windows 10, Windows Server 2016 или Windows сервера 2019 Hyper-V. PowerShell Direct позволяет управлять Windows PowerShell в виртуальной машине независимо от конфигурации сети или параметров удаленного управления на узле Hyper-V или виртуальной машине. Это позволяет администраторам Hyper-V автоматизировать управление и настройку виртуальных машин с помощью сценариев.
Запустить PowerShell Direct можно двумя способами:
Создание и выход из прямого сеанса PowerShell с помощью командлетов PSSession
Запуск скрипта или команды с помощью командлета Invoke-Command
Если вы управляете виртуальными машинами более ранних версий, используйте средство «Подключение к виртуальной машине» (VMConnect) или настройте для этой машины виртуальную сеть.
Создание и выход из прямого сеанса PowerShell с помощью командлетов PSSession
На узле Hyper-V откройте Windows PowerShell от имени администратора.
Используйте командлет Enter-PSSession для подключения к виртуальной машине. Чтобы создать сеанс с помощью имени или GUID виртуальной машины, выполните одну из следующих команд:
Введите свои учетные данные для виртуальной машины.
Выполните все необходимые команды. Эти команды выполняются на виртуальной машине, в которой был создан сеанс.
Запуск скрипта или команды с помощью командлета Invoke-Command
Выполнить предварительно определенный набор команд на виртуальной машине можно с помощью командлета Invoke-Command. Ниже приведен пример использования командлета Invoke-Command, где PSTest — это имя виртуальной машины, а сценарий, который требуется запустить,(foo.ps1) находится в папке сценария (script) на диске C:
Чтобы выполнить одну команду, используйте параметр -ScriptBlock:
Что необходимо для использования PowerShell Direct?
Чтобы создать сеанс PowerShell Direct на виртуальной машине:
Виртуальная машина должна работать на узле локально и быть загружена.
Необходимо войти в учетную запись администратора Hyper-V на хост-компьютере.
Необходимо указать действительные учетные данные пользователя для виртуальной машины.
операционная система узла должна работать как минимум Windows 10 или Windows Server 2016.
виртуальная машина должна работать как минимум Windows 10 или Windows Server 2016.
С помощью командлета Get-VM можно проверить, что используемые учетные данные имеют роль администратора Hyper-V, и получить список виртуальных машин, запущенных локально на узле и загруженных.
Virtual Machine automation and management using PowerShell
You can use PowerShell Direct to run arbitrary PowerShell in a Windows 10 or Windows Server 2016 virtual machine from your Hyper-V host regardless of network configuration or remote management settings.
Here are some ways you can run PowerShell Direct:
Requirements
Operating system requirements:
If you’re managing older virtual machines, use Virtual Machine Connection (VMConnect) or configure a virtual network for the virtual machine.
Configuration requirements:
Create and exit an interactive PowerShell session
The easiest way to run PowerShell commands in a virtual machine is to start an interactive session.
When the session starts, the commands that you type run on the virtual machine, just as though you typed them directly into a PowerShell session on the virtual machine itself.
To start an interactive session:
On the Hyper-V host, open PowerShell as Administrator.
Run one of the following commands to create an interactive session using the virtual machine name or GUID:
Provide credentials for the virtual machine when prompted.
You should see the VMName as the prefix for your PowerShell prompt as shown:
Any command run will be running on your virtual machine. To test, you can run ipconfig or hostname to make sure that these commands are running in the virtual machine.
When you’re done, run the following command to close the session:
Note: If your session won’t connect, see the troubleshooting for potential causes.
To learn more about these cmdlets, see Enter-PSSession and Exit-PSSession.
Run a script or command with Invoke-Command
PowerShell Direct with Invoke-Command is perfect for situations where you need to run one command or one script on a virtual machine but do not need to continue interacting with the virtual machine beyond that point.
To run a single command:
On the Hyper-V host, open PowerShell as Administrator.
Run one of the following commands to create a session using the virtual machine name or GUID:
Provide credentials for the virtual machine when prompted.
The command will execute on the virtual machine, if there is output to the console, it’ll be printed to your console. The connection will be closed automatically as soon as the command runs.
To run a script:
On the Hyper-V host, open PowerShell as Administrator.
Run one of the following commands to create a session using the virtual machine name or GUID:
Provide credentials for the virtual machine when prompted.
The script will execute on the virtual machine. The connection will be closed automatically as soon as the command runs.
To learn more about this cmdlet, see Invoke-Command.
Copy files with New-PSSession and Copy-Item
Note: PowerShell Direct only supports persistent sessions in Windows builds 14280 and later
Persistent PowerShell sessions are incredibly useful when writing scripts that coordinate actions across one or more remote machines. Once created, persistent sessions exist in the background until you decide to delete them. This means you can reference the same session over and over again with Invoke-Command or Enter-PSSession without passing credentials.
By the same token, sessions hold state. Since persistent sessions persist, any variables created in a session or passed to a session will be preserved across multiple calls. There are a number of tools available for working with persistent sessions. For this example, we will use New-PSSession and Copy-Item to move data from the host to a virtual machine and from a virtual machine to the host.
To create a session then copy files:
On the Hyper-V host, open PowerShell as Administrator.
Provide credentials for the virtual machine when prompted.
To copy C:\host_path\data.txt to the virtual machine from the host machine, run:
To copy C:\guest_path\data.txt to the host from the virtual machine, run:
Troubleshooting
There are a small set of common error messages surfaced through PowerShell Direct. Here are the most common, some causes, and tools for diagnosing issues.
Potential causes:
The most likely issue is that PowerShell Direct isn’t supported by your host operating system.
You can check your Windows build by running the following command:
If you are running a supported build, it is also possible your version of PowerShell does not run PowerShell Direct. For PowerShell Direct and JEA, the major version must be 5 or later.
You can check your PowerShell version build by running the following command:
Error: A remote session might have ended
Note:
For Enter-PSSession between host builds 10240 and 12400, all errors below reported as «A remote session might have ended».
Error message:
Potential causes:
You can use the Get-VM cmdlet to check to see which VMs are running on the host.
Error message:
Potential causes:
To work around the credential issue, log into the virtual machine using VMConnect, open PowerShell, and restart the vmicvmsession service using the following PowerShell:
Error: Parameter set cannot be resolved
Error message:
Potential causes:
-RunAsAdministrator is not supported when connecting to virtual machines.
Error: The credential is invalid.
Error message:
Potential causes:
Error: The input VMName parameter does not resolve to any virtual machine.
Error message:
Potential causes:
You can use the Get-VM cmdlet to check that the credentials you’re using have the Hyper-V administrator role and to see which VMs are running locally on the host and booted.
Samples and User Guides
PowerShell Direct supports JEA (Just Enough Administration). Check out this user guide to try it.
Управление виртуальными машинами в Azure Stack HCI с помощью Windows PowerShell
Применимо к: Azure Stack ХЦИ, Versions 21H2 и 20H2; Windows server 2022, Windows server 2019
Для создания виртуальных машин в Azure Stack HCI и управления ими можно использовать Windows PowerShell.
Как правило, виртуальные машины управляются с удаленного компьютера, а не с сервера узла в кластере. Этот удаленный компьютер называется компьютером управления.
Полную справочную документацию по управлению виртуальными машинами с помощью PowerShell см. в справочнике по Hyper-V.
Создание виртуальной машины
Ниже приведены параметры, которые можно указать при создании новой виртуальной машины с имеющимся виртуальным жестким диском.
-Name — имя, которое вы задаете для создаваемой виртуальной машины.
-Мемористартупбитес — объем памяти, доступной виртуальной машине при запуске.
-BootDevice — устройство, на которое загружается виртуальная машина при запуске. Обычно это виртуальный жесткий диск (VHD), ISO-файл для загрузки с DVD или сетевой адаптер для сетевой загрузки.
-VHDPath — путь к диску виртуальной машины, который вы хотите использовать.
-Path — путь для хранения файлов конфигурации виртуальной машины.
-Generation поколение виртуальной машины. Используйте поколение 1 для VHD и поколение 2 для VHDX.
-Switch — имя виртуального коммутатора, который виртуальная машина должна использовать для подключения к другим виртуальным машинам или сети. Для получения имени виртуального коммутатора воспользуйтесь командлетом Get-VMSwitch. Пример:
Полная команда для создания виртуальной машины с именем VM1 выглядит следующим образом:
В следующем примере создается виртуальная машина поколения 2 с 4 ГБ памяти. Она загружается из папки VMs\Win10.vhdx в текущий каталог и использует виртуальный коммутатор с именем ExternalSwitch. Файлы конфигурации виртуальной машины хранятся в папке VMData.
Виртуальные жесткие диски можно задать с помощью следующих параметров.
Сведения о том, как создать виртуальную машину с новым виртуальным диском, с которого будет загружаться образ операционной системы, см. в примере PowerShell в статье Создание виртуальной машины с помощью Hyper-V в Windows 10.
Получение списка виртуальных машин
В следующем примере возвращается список всех виртуальных машин на сервере Server1.
В следующем примере возвращается список всех выключенных виртуальных машин на сервере.
Запуск виртуальной машины и завершение ее работы
Воспользуйтесь командами Start-VM и Stop-VM для запуска виртуальной машины и завершения ее работы. Подробные сведения см. в справочной документации по командам Start-VM и Stop-VM.
В приведенном ниже примере показано, как запустить виртуальную машину с именем VM1.
В следующем примере показано, как завершить работу виртуальной машины с именем TestVM.
Перемещение виртуальной машины
Командлет Move-VM перемещает виртуальную машину на другой сервер. Дополнительные сведения см. в справочной документации по командлету Move-VM.
В следующем примере показано, как переместить виртуальную машину на сервер Server2, если она хранится в общем ресурсе SMB на сервере Server1.
В следующем примере показано, как переместить виртуальную машину с сервера Server1 на сервер Server2, а все связанные с ней файлы — в каталог D:\VM_name на удаленном компьютере.
Импорт и экспорт виртуальной машины
В следующем примере показано, как импортировать виртуальную машину из файла конфигурации. Виртуальная машина зарегистрирована на месте, поэтому ее файлы не копируются.
В следующем примере виртуальная машина экспортируется в корневую папку диска D.
Переименование виртуальной машины
В следующем примере VM1 переименовывается в VM2 и отображается переименованная виртуальная машина.
Создание контрольной точки виртуальной машины
В следующем примере для виртуальной машины с именем Test создается контрольная точка с именем BeforeInstallingUpdates.
Создание виртуального жесткого диска для виртуальной машины
В следующем примере создается динамический виртуальный жесткий диск в формате VHDX емкостью 10 ГБ. Расширение имени файла определяет формат, и поскольку тип не указан, используется динамический тип по умолчанию.
Добавление сетевого адаптера в виртуальную машину
В следующем примере в виртуальную машину с именем VM1 добавляется виртуальный сетевой адаптер с именем Redmond NIC1.
В этом примере виртуальный сетевой адаптер добавляется в виртуальную машину с именем VM1 и подключает ее к виртуальному коммутатору с именем Network:
Создание виртуального коммутатора для виртуальной машины
В следующем примере создается новый коммутатор с именем QoS switch, который привязывается к сетевому адаптеру с именем Wired Ethernet Connection 3 и поддерживает использование взвешенной минимальной пропускной способности.
Настройка памяти для виртуальной машины
В следующем примере на виртуальной машине с именем VM1 включается динамическая память, устанавливается ее минимальный и максимальный объем и объем при запуске. Кроме того, задается приоритет памяти и ее буфер.
Настройка виртуальных процессоров для виртуальной машины
В следующем примере настраивается виртуальная машина с именем VM1, двумя виртуальными процессорами, резервом в 10 %, ограничением в 75 % и относительным весом 200.
Удаление виртуальной машины
Чтобы удалить или удалить виртуальную машину и ее ресурсы, сначала найдите их с помощью следующего командлета:
Затем выполните следующий командлет для каждой виртуальной машины, которую вы хотите удалить из кластера:
Дальнейшие действия
Вы также можете создавать виртуальные машины и управлять ими с помощью Windows Admin Center. Дополнительные сведения см. в статье о Windows Admin Center.
Hyper-V
This reference provides cmdlet descriptions and syntax for all Hyper-V-specific cmdlets. It lists the cmdlets in alphabetical order based on the verb at the beginning of the cmdlet.
Hyper-V
Adds a DVD drive to a virtual machine.
Adds a virtual Fibre Channel host bus adapter to a virtual machine.
Adds group members to a virtual machine group.
Adds a hard disk drive to a virtual machine.
Adds a network for virtual machine migration on one or more virtual machine hosts.
Adds a virtual network adapter to a virtual machine.
Creates an ACL to apply to the traffic through a virtual machine network adapter.
Creates an extended ACL for a virtual network adapter.
Adds a routing domain and virtual subnets to a virtual network adapter.
Adds a RemoteFX video adapter in a virtual machine.
Adds a SCSI controller in a virtual machine.
Adds a path to a storage resource pool.
Adds a virtual switch to an Ethernet resource pool.
Adds a feature to a virtual network adapter.
Adds a feature to a virtual switch.
Adds members to a virtual switch team.
Creates a checkpoint of a virtual machine.
Compares a virtual machine and a virtual machine host for compatibility, returning a compatibility report.
Completes a virtual machine’s failover process on the Replica server. Removes all recovery points on a failed over virtual machine.
Connects a virtual network adapter to a virtual switch.
Associates a host bus adapter with a virtual storage area network (SAN).
Converts the format, version type, and block size of a virtual hard disk file.
Copies a file to a virtual machine.
Debugs a virtual machine.
Disables keyboard, video, and mouse for a generation 2 virtual machine.
Disables virtual machine eventing.
Disables an integration service on a virtual machine.
Disables migration on one or more virtual machine hosts.
Disables one or more RemoteFX physical video adapters from use with RemoteFX-enabled virtual machines.
Disables collection of resource utilization data for a virtual machine or resource pool.
Disables one or more extensions on one or more virtual switches.
Disables TPM functionality on a virtual machine.
Disconnects a virtual network adapter from a virtual switch or Ethernet resource pool.
Removes a host bus adapter from a virtual storage area network (SAN).
Dismounts a virtual hard disk.
Enables keyboard, video, and mouse for virtual machines.
Enables virtual machine eventing.
Enables an integration service on a virtual machine.
Enables migration on one or more virtual machine hosts.
Enables one or more RemoteFX physical video adapters for use with RemoteFX-enabled virtual machines.
Enables replication of a virtual machine.
Collects resource utilization data for a virtual machine or resource pool.
Enables one or more extensions on one or more switches.
Enables TPM functionality on a virtual machine.
Exports a virtual machine to disk.
Exports a virtual machine checkpoint to disk.
Gets the virtual hard disk object associated with a virtual hard disk.
Gets information about a VHD set.
Gets information about a checkpoint in a VHD set.
Gets the virtual machines from one or more Hyper-V hosts.
Gets the BIOS of a virtual machine or snapshot.
Gets the COM ports of a virtual machine or snapshot.
Gets entries showing users and the virtual machines to which they can connect on one or more Hyper-V hosts.
Gets the DVD drives attached to a virtual machine or snapshot.
Gets the Fibre Channel host bus adapters associated with one or more virtual machines.
Gets the firmware configuration of a virtual machine.
Gets the floppy disk drives of a virtual machine or snapshot.
Gets virtual machine groups.
Gets the virtual hard disk drives attached to one or more virtual machines.
Gets a Hyper-V host.
Gets virtual machine host clusters.
Gets the NUMA topology of a virtual machine host.
Gets the status of the virtual machines on the non-uniform memory access (NUMA) nodes of a virtual machine host or hosts.
Returns a list of virtual machine configuration versions that are supported on a host.
Gets the IDE controllers of a virtual machine or snapshot.
Gets the integration services of a virtual machine or snapshot.
Retrieves a key protector for a virtual machine.
Gets the memory of a virtual machine or snapshot.
Gets the networks added for migration to one or more virtual machine hosts.
Gets the virtual network adapters of a virtual machine, snapshot, management operating system, or of a virtual machine and management operating system.
Gets the ACLs configured for a virtual machine network adapter.
Gets extended ACLs configured for a virtual network adapter.
Gets the IP address of a virtual network adapter configured to be used when a virtual machine fails over.
Gets isolation settings for a virtual network adapter.
Gets members of a routing domain.
Gets the virtual LAN settings configured on a virtual network adapter.
Gets the processor of a virtual machine or snapshot.
Gets the RemoteFX video adapter of a virtual machine or snapshot.
Gets the RemoteFX physical graphics adapters on one or more Hyper-V hosts.
Gets the replication settings for a virtual machine.
Gets the authorization entries of a Replica server.
Gets the replication and authentication settings of a Replica server.
Gets the resource pools on one or more virtual machine hosts.
Gets the available virtual machine storage area networks on a Hyper-V host or hosts.
Gets the SCSI controllers of a virtual machine or snapshot.
Gets security information about a virtual machine.
Gets the checkpoints associated with a virtual machine or checkpoint.
Gets the storage paths in a storage resource pool.
Gets virtual switches from one or more virtual Hyper-V hosts.
Gets the extensions on one or more virtual switches.
Retrieves the status of a virtual switch extension feature applied to a virtual network adapter.
Gets the features configured on a virtual network adapter.
Gets the status of a virtual switch extension feature applied on a virtual switch.
Gets the features configured on a virtual switch.
Gets virtual switch teams from Hyper-V hosts.
Gets the switch extensions installed on a virtual machine host.
Gets the port-level features supported by virtual switch extensions on one or more Hyper-V hosts.
Gets the switch-level features on one or more Hyper-V hosts.
Gets video settings for virtual machines.
Grants a user or users access to connect to a virtual machine or machines.
Imports a virtual machine from a file.
Imports initial replication files for a Replica virtual machine to complete the initial replication when using external media as the source.
Reports resource utilization data for one or more virtual machines.
Gets replication statistics and information associated with a virtual machine.
Reports resource utilization data for one or more resource pools.
Merges virtual hard disks.
Mounts one or more virtual hard disks.
Moves a virtual machine to a new Hyper-V host.
Moves the storage of a virtual machine.
Creates a virtual floppy disk.
Creates one or more new virtual hard disks.
Creates a new virtual machine.
Creates a virtual machine group.
With Hyper-V, there are two types of VMGroups: a VMCollectionType and a ManagementCollectionType. A VMCollectionType VMGroup contains VMs while the ManagementCollectionType VMGroup contains VMCollectionType VMGroups. For example, you could have two VMCollectionType VMGroups VMG1 (containing VMs VM1 and VM2) and a second VMG2 (containing VMs VM3 and VM4). You could then create a ManagementCollectionType VMGroup VM-All containing the two VMCollectionType VMGroups. You use the Add-VMGroupMember cmdlet to add VMs to VMCollectionType VMGroups and to add VMCollectionType groups to ManagementCollectionType VMGroups.
Creates a new authorization entry that allows one or more primary servers to replicate data to a specified Replica server.
Creates a resource pool.
Creates a new virtual storage area network (SAN) on a Hyper-V host.
Creates a new virtual switch on one or more virtual machine hosts.
Optimizes the allocation of space used by virtual hard disk files, except for fixed virtual hard disks.
Optimizes VHD set files.
Removes a checkpoint from a VHD set file.
Deletes a virtual machine.
Deletes a DVD drive from a virtual machine.
Removes a Fibre Channel host bus adapter from a virtual machine.
Removes a virtual machine group.
Removes members from a virtual machine group.
Deletes a hard disk drive from a virtual machine.
Removes a network from use with migration.
Removes one or more virtual network adapters from a virtual machine.
Removes an ACL applied to the traffic through a virtual network adapter.
Removes an extended ACL for a virtual network adapter.
Removes a routing domain from a virtual network adapter.
Removes a RemoteFX 3D video adapter from a virtual machine.
Removes the replication relationship of a virtual machine.
Removes an authorization entry from a Replica server.
Deletes a resource pool from one or more virtual machine hosts.
Removes a virtual storage area network (SAN) from a Hyper-V host.
Deletes the saved state of a saved virtual machine.
Removes a SCSI controller from a virtual machine.
Deletes a virtual machine checkpoint.
Removes a path from a storage resource pool.
Deletes a virtual switch.
Removes a feature from a virtual network adapter.
Removes a feature from a virtual switch.
Removes a member from a virtual machine switch team.
Renames a virtual machine.
Renames virtual machine groups.
Renames a virtual network adapter on a virtual machine or on the management operating system.
Renames a resource pool on one or more Hyper-V hosts.
Renames a virtual storage area network (SAN).
Renames a virtual machine checkpoint.
Renames a virtual switch.
Repairs one or more virtual machines.
Resets the replication statistics of a virtual machine.
Resets the resource utilization data collected by Hyper-V resource metering.
Resizes a virtual hard disk.
Restarts a virtual machine.
Restores a virtual machine checkpoint.
Resumes a suspended (paused) virtual machine.
Resumes a virtual machine replication that is in a state of Paused, Error, Resynchronization Required, or Suspended.
Revokes access for one or more users to connect to a one or more virtual machines.
Saves a virtual machine.
Sets properties associated with a virtual hard disk.
Configures a virtual machine.
Configures the BIOS of a Generation 1 virtual machine.
Configures the COM port of a virtual machine.
Configures a virtual DVD drive.
Configures a Fibre Channel host bus adapter on a virtual machine.
Sets the firmware configuration of a virtual machine.
Configures a virtual floppy disk drive.
Configures a virtual hard disk.
Configures a Hyper-V host.
Configures a virtual machine host cluster.
Configures a key protector for a virtual machine.
Configures the memory of a virtual machine.
Sets the subnet, subnet mask, and/or priority of a migration network.
Configures features of the virtual network adapter in a virtual machine or the management operating system.
Configures the IP address of a virtual network adapter to be used when a virtual machine fails over.
Modifies isolation settings for a virtual network adapter.
Sets virtual subnets on a routing domain.
Configures the virtual LAN settings for the traffic through a virtual network adapter.
Configures settings for the virtual processors of a virtual machine. Settings are applied uniformly to all virtual processors belonging to the virtual machine.
Configures the RemoteFX 3D video adapter of a virtual machine.
Modifies the replication settings of a virtual machine.
Modifies an authorization entry on a Replica server.
Configures a host as a Replica server.
Sets the parent resource pool for a selected resource pool.
Configures a virtual storage area network (SAN) on one or more Hyper-V hosts.
Configures security settings for a virtual machine.
Configures the security policy for a virtual machine.
Configures a virtual switch.
Configures a feature on a virtual network adapter.
Configures a feature on a virtual switch.
Configures a virtual switch team.
Configures video settings for virtual machines.
Starts a virtual machine.
Starts failover on a virtual machine.
Starts replication of a virtual machine.
Starts tracing to a file.
Shuts down, turns off, or saves a virtual machine.
Stops failover of a virtual machine.
Stops an ongoing initial replication.
Cancels an ongoing virtual machine resynchronization.
Stops tracing to file.
Suspends, or pauses, a virtual machine.
Suspends replication of a virtual machine.
Tests a virtual hard disk for any problems that would make it unusable.
Tests connectivity between virtual machines.
Tests the connection between a primary server and a Replica server.