- Visual Studio Developer Command Prompt and Developer PowerShell
- Start in Visual Studio
- Start from Windows menu
- Windows 10
- Windows 8.1
- Windows 7
- Start from file browser
- Developer Command Prompt
- Developer PowerShell
- Использование скриптов Windows PowerShell для публикации в средах разработки и тестирования Using Windows PowerShell scripts to publish to dev and test environments
- Предварительные требования Prerequisites
- Дополнительные средства Additional tools
- Создание сценариев публикации Generating the publish scripts
- Сценарии, создаваемые в Visual Studio Scripts that Visual Studio generates
- Сценарий публикации Windows PowerShell Windows PowerShell publish script
- Модуль Windows PowerShell Windows PowerShell module
- Файл конфигурации в формате JSON JSON configuration file
- Запуск скриптов публикации How to run the publish scripts
- Выполнение скрипта Run the script
- Настройка и расширение сценариев публикации Customizing and extending the publish scripts
- Автоматизация сборки проекта To automate building your project
- Запуск команды сборки Start execution of the build command
- Обзор функций публикации Publishing function summary
- Дальнейшие действия Next steps
Visual Studio Developer Command Prompt and Developer PowerShell
Visual Studio 2019 includes two command-line shells for developers:
Visual Studio Developer Command Prompt — A standard command prompt with certain environment variables set to make using command-line developer tools easier. Available since Visual Studio 2015.
Visual Studio Developer PowerShell — More powerful than a command prompt. For example, you can pass the output of one command (known as a cmdlet) to another cmdlet. This shell has the same environment variables set as Developer Command Prompt. Available since Visual Studio 2019.
Starting in Visual Studio 2019 version 16.5, Visual Studio includes an integrated terminal that can host either of these shells (Developer Command Prompt and Developer PowerShell). You can also open multiple tabs of each shell. The Visual Studio terminal is built on top of Windows Terminal. To open the terminal in Visual Studio, choose View > Terminal.
When you open one of the developer shells from Visual Studio, either as a separate app or in the Terminal window, it opens to the directory of your current solution (if you have a solution loaded). This behavior makes it convenient to run commands against the solution or its projects.
Both shells have specific environment variables set that enable you to use command-line developer tools more easily. After opening one of these shells, you can enter the commands for different utilities without having to know where they’re located.
Popular commands | Description |
---|---|
MSBuild | Build a project or solution |
clrver | A .NET Framework tools for clr. |
ildasm | A .NET Framework tool for disassembler. |
dotnet | A .NET CLI command |
dotnet run | A .NET CLI command |
CL | C/C++ compile tool |
NMAKE | C/C++ compile tool |
LIB | C/C++ build tool |
DUMPBIN | C/C++ build tool |
Start in Visual Studio
Follow these steps to open Developer Command Prompt or Developer PowerShell from within Visual Studio:
Open Visual Studio.
On the menu bar, choose Tools > Command Line > Developer Command Prompt or Developer PowerShell.
Start from Windows menu
Another way to start the shells is from the Start menu. You may have multiple command prompts, depending on the version of Visual Studio and any additional SDKs and workloads you’ve installed.
Windows 10
Select Start and scroll to the letter V.
Expand the Visual Studio 2019 folder.
Choose Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.
Alternatively, you can start typing the name of the shell in the search box on the taskbar, and choose the result you want as the result list starts to display the search matches.
Windows 8.1
Go to the Start screen, by pressing the Windows logo key on your keyboard for example.
On the Start screen, press Ctrl+Tab to open the Apps list, and then press V. This brings up a list that includes all installed Visual Studio command prompts.
Choose Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.
Windows 7
Choose Start and then expand All Programs.
Choose Visual Studio 2019 > Visual Studio Tools > Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.
If you have other SDKs installed, such as the Windows 10 SDK or previous versions, you may see additional command prompts. Check the documentation for the individual tools to determine which version of the command prompt you should use.
Start from file browser
Usually, the shortcuts for the shells you have installed are placed in the Start Menu folder for Visual Studio, such as in %ProgramData%\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools. But if searching for the command prompt doesn’t produce the expected results, you can try to manually locate the files on your machine.
Developer Command Prompt
Search for the name of the command prompt file, which is VsDevCmd.bat, or go to the Tools folder for Visual Studio, such as %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools (path changes according to your Visual Studio version, edition, and installation location).
Once you’ve located the command prompt file, open it by entering the following command in a regular command prompt window:
Or enter the following command in the Windows Run dialog box:
You’ll need to edit the path to match your Visual Studio installation.
Developer PowerShell
Search for a PowerShell script file named Launch-VsDevShell.ps1, or go to the Tools folder for Visual Studio, such as %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools. (The path changes according to your Visual Studio version, edition, and installation location.) Once you’ve located the PowerShell file, run it by entering the following command at a Windows PowerShell or PowerShell 6 prompt:
By default, the Developer PowerShell that launches is configured for the Visual Studio installation whose install path the Launch-VsDevShell.ps1 file is located in.
The execution policy must be set in order for the cmdlet to run.
Использование скриптов Windows PowerShell для публикации в средах разработки и тестирования Using Windows PowerShell scripts to publish to dev and test environments
При создании веб-приложения в Visual Studio вы можете создать сценарий Windows PowerShell, который позволит автоматизировать публикацию решения на виртуальной машине или веб-сайте (как веб-приложения в службе приложений Azure). When you create a web application in Visual Studio, you can generate a Windows PowerShell script that you can use later to automate the publishing of your website to Azure as a Web App in Azure App Service or a virtual machine. В редакторе Visual Studio этот сценарий можно изменить и расширить в соответствии со своими потребностями или интегрировать его в существующие сценарии сборки, тестирования и публикации. You can edit and extend the Windows PowerShell script in the Visual Studio editor to suit your requirements, or integrate the script with existing build, test, and publishing scripts.
С помощью этих сценариев вы можете подготавливать временные пользовательские версии сайта. Эти версии также называют средами разработки и тестирования. Using these scripts, you can provision customized versions (also known as dev and test environments) of your site for temporary use. Например, на виртуальной машине Azure или в промежуточном слоте веб-сайта можно настроить определенную версию веб-сайта и использовать ее для проведения различных тестов, воспроизведения ошибки, проверки исправления ошибки или исследования предлагаемого изменения. Вы также можете создать специальную среду для демонстраций или презентаций. For example, you might set up a particular version of your website on an Azure virtual machine or on the staging slot on a website to run a test suite, reproduce a bug, test a bug fix, trial a proposed change, or set up a custom environment for a demo or presentation. Создав сценарий публикации проекта, вы можете с его помощью воссоздавать идентичные среды или использовать его в своей сборке веб-приложения для создания отдельной среды тестирования. After you’ve created a script that publishes your project, you can recreate identical environments by rerunning the script as needed, or run the script with your own build of your web application to create a custom environment for testing.
Предварительные требования Prerequisites
- Visual Studio 2015 или последующей версии с установленной рабочей нагрузкой Azure или Visual Studio 2013 с пакетом Azure SDK, начиная с версии 2.3. Visual Studio 2015 or later with the Azure workload installed, or Visual Studio 2013 and Azure SDK 2.3 or later. Ознакомьтесь со страницей скачиваемых компонентов Visual Studio. See Visual Studio Downloads. (Пакет Azure SDK не нужен для создания сценариев для веб-проектов. (You don’t need the Azure SDK to generate the scripts for web projects. Он предназначен для веб-проектов, а не веб-ролей облачных служб.) This feature is for web projects, not web roles in cloud services.)
- Azure PowerShell, начиная с версии 0.7.4. Azure PowerShell 0.7.4 or later. Ознакомьтесь со статьей Установка и настройка Azure PowerShell. See How to install and configure Azure PowerShell.
- Windows PowerShell , начиная с версии 3.0. Windows PowerShell 3.0 or later.
Дополнительные средства Additional tools
Если вы занимаетесь разработкой решений для Azure, для работы с PowerShell в Visual Studio доступны дополнительные средства и ресурсы. Additional tools and resources for working with PowerShell in Visual Studio for Azure development are available. Ознакомьтесь с разделом Средства PowerShell для Visual Studio. See PowerShell Tools for Visual Studio.
Создание сценариев публикации Generating the publish scripts
Чтобы создать сценарии публикации для виртуальной машины, на которой будет размещен веб-сайт, при создании проекта воспользуйтесь этими инструкциями. You can generate the publish scripts for a virtual machine that hosts your website when you create a new project by following these instructions. Можно также создать сценарии публикации для веб-приложений в службе приложений Azure. You can also generate publish scripts for web apps in Azure App Service.
Сценарии, создаваемые в Visual Studio Scripts that Visual Studio generates
Visual Studio создает папку на уровне решения с именем PublishScripts, содержащую два файла Windows PowerShell, скрипт публикации для виртуальной машины или веб-сайта, а также модуль с функциями, которые можно использовать в скриптах. Visual Studio generates a solution-level folder called PublishScripts that contains two Windows PowerShell files, a publish script for your virtual machine or website, and a module that contains functions that you can use in the scripts. Visual Studio также создает файл в формате JSON, в котором хранятся сведения о развертываемом проекте. Visual Studio also generates a file in the JSON format that specifies the details of the project you are deploying.
Сценарий публикации Windows PowerShell Windows PowerShell publish script
Сценарий публикации содержит действия по развертыванию решения на веб-сайте или виртуальной машине. The publish script contains specific publish steps for deploying to a website or virtual machine. В Visual Studio работает цветовая подсветка синтаксиса Windows PowerShell и доступна справка по функциям. Visual Studio provides syntax coloring for Windows PowerShell development. Кроме того, вы можете свободно изменять функции сценария в соответствии со своими потребностями. Help for the functions is available, and you can freely edit the functions in the script to suit your changing requirements.
Модуль Windows PowerShell Windows PowerShell module
Создаваемый в Visual Studio модуль Windows PowerShell содержит функции, которые используются в сценарии публикации. The Windows PowerShell module that Visual Studio generates contains functions that the publish script uses. Эти функции Azure PowerShell не нужно изменять. These Azure PowerShell functions are not intended to be modified. Ознакомьтесь со статьей Установка и настройка Azure PowerShell. See How to install and configure Azure PowerShell.
Файл конфигурации в формате JSON JSON configuration file
Файл JSON создается в папке Конфигурации и содержит данные конфигурации, указывающие, какие именно ресурсы следует развертывать в Azure. The JSON file is created in the Configurations folder and contains configuration data that specifies exactly which resources to deploy to Azure. Если вы создали веб-сайт, Visual Studio создает этот файл с именем имя_проекта-WAWS-dev.json. Если вы создали виртуальную машину, Visual Studio создает этот файл с именем имя_проекта-VM-dev.json. The name of the file that Visual Studio generates is project-name-WAWS-dev.json if you created a website, or project name-VM-dev.json if you created a virtual machine. Ниже приведен пример файла конфигурации JSON, который создается для веб-сайта. Here’s an example of a JSON configuration file that’s generated when you create a website. Большая часть значений не нуждается в объяснении. Most of the values are self-explanatory. Имя веб-сайта задает служба Azure, поэтому оно может не совпадать с именем вашего проекта. The website name is generated by Azure, so it might not match your project name.
В случае создания виртуальной машины файл конфигурации JSON выглядит так, как показано ниже. When you create a virtual machine, the JSON configuration file looks similar to the following. Для виртуальной машины создается контейнер в виде облачной службы. A cloud service is created as a container for the virtual machine. Виртуальная машина содержит обычные конечные точки для веб-доступа через HTTP и HTTPS, а также конечные точки для веб-развертывания, что позволяет публиковать решение на веб-сайт с локального компьютера, удаленного рабочего стола или через Windows PowerShell. The virtual machine contains the usual endpoints for web access through HTTP and HTTPS, as well as endpoints for Web Deploy, which lets you publish to the website from your local machine, Remote Desktop, and Windows PowerShell.
Редактируя файл конфигурации JSON, вы можете влиять на результат выполнения сценариев публикации. You can edit the JSON configuration to change what happens when you run the publish scripts. Разделы cloudService и virtualMachine обязательны, а вот раздел databases можно удалить, если он не нужен. The cloudService and virtualMachine sections are required, but you can delete the databases section if you don’t need it. Пустые свойства в стандартном файле конфигурации, который создается в Visual Studio, можно не использовать. Свойства, имеющие значение в стандартном файле конфигурации, — обязательные. The properties that are empty in the default configuration file that Visual Studio generates are optional; those properties that have values in the default configuration file are required.
Если у вас есть веб-сайт с несколькими средами развертывания (также известны как слоты), вместо рабочего веб-сайта в Azure в файле конфигурации JSON в имени веб-сайта можно указать имя слота. If you have a website that has multiple deployment environments (known as slots) instead of a single production site in Azure, you can include the slot name in the name of the website in the JSON configuration file. Например, если у вас есть веб-сайт с именем mysite и слот для него с именем test, то универсальный код ресурса (URI) будет mysite-test.cloudapp.net , но правильное имя для использования в файле конфигурации — mysite(test). For example, if you have a website that’s named mysite and a slot for it named test then the URI is mysite-test.cloudapp.net , but the correct name to use in the configuration file is mysite(test). Так можно сделать, только если веб-сайт и слоты уже есть в вашей подписке. You can only do this if the website and slots already exist in your subscription. Если их еще нет, создайте веб-сайт, запустив сценарий без указания слота, затем создайте слот на портале Azure. После этого запустите сценарий с измененным именем веб-сайта. If they don’t exist, create the website by running the script without specifying the slot, then create the slot in the Azure portal, and thereafter run the script with the modified website name. Дополнительные сведения о слотах развертывания для веб-приложений см. в статье Настройка промежуточных сред для веб-приложений в службе приложений Azure. For more information about deployment slots for web apps, see Set up staging environments for web apps in Azure App Service.
Запуск скриптов публикации How to run the publish scripts
Если вы раньше не запускали сценарии Windows PowerShell, вам сначала необходимо настроить политику выполнения. Это позволит сценариям выполняться. If you have never run a Windows PowerShell script before, you must first set the execution policy to enable scripts to run. Такая политика предусмотрена для того, чтобы защитить пользователей от вредоносных программ и вирусов, которые могут распространяться с помощью выполняемых сценариев, включая сценарии Windows PowerShell. The policy is a security feature to prevent users from running Windows PowerShell scripts if they’re vulnerable to malware or viruses that involve executing scripts.
Выполнение скрипта Run the script
Создайте пакет веб-развертывания для своего проекта. Create the Web Deploy package for your project. Пакет веб-развертывания — это сжатый файл (ZIP-архив), содержащий файлы, которые нужно скопировать на веб-сайт или виртуальную машину. A Web Deploy package is a compressed archive (.zip file) that contain files that you want to copy to your website or virtual machine. В Visual Studio можно создавать пакеты веб-развертывания для любых веб-приложений. You can create Web Deploy packages in Visual Studio for any web application.
Дополнительные сведения см. в статье Как создать пакет веб-развертывания в Visual Studio. For more information, see How to: Create a Web Deployment Package in Visual Studio. Создание пакета веб-развертывания можно автоматизировать, как описано в разделе Настройка и расширение сценариев публикации. You can also automate the creation of your Web Deploy package, as described in Customizing and extending the publish scripts.
В обозревателе решений откройте контекстное меню сценария и выберите Открыть с помощью PowerShell ISE. In Solution Explorer, open the context menu for the script, and then choose Open with PowerShell ISE.
Если вы запускаете сценарии Windows PowerShell на этом компьютере впервые, откройте окно командной строки с правами администратора и введите такую команду: If running Windows PowerShell scripts on this computer for the first time, open a command prompt window with Administrator privileges and type the following command:
Войдите в Azure, выполнив такую команду: Sign in to Azure by using the following command.
При появлении запроса введите свои имя пользователя и пароль. When prompted, supply your username and password.
Обратите внимание, что после автоматизации работы сценария этот способ указания учетных данных Azure не будет работать. Note that when you automate the script, this method of providing Azure credentials doesn’t work. В таком случае учетные данные нужно указать в файле .publishsettings . Instead, you should use the .publishsettings file to provide credentials. Один раз скачайте файл из Azure, выполнив команду Get-AzurePublishSettingsFile, после чего импортируйте его с помощью команды Import-AzurePublishSettingsFile. One time only, you use the command Get-AzurePublishSettingsFile to download the file from Azure, and thereafter use Import-AzurePublishSettingsFile to import the file. Подробные инструкции см. в статье Установка и настройка служб Azure PowerShell. For detailed instructions, see How to install and configure Azure PowerShell.
(Этот этап можно пропустить.) Если вы хотите создать ресурсы Azure, такие как виртуальная машина, база данных и веб-сайт, не публикуя свое веб-приложение, выполните команду Publish-WebApplication.ps1, указав в качестве значения параметра -Configuration ссылку на JSON-файл конфигурации. (Optional) If you want to create Azure resources such as the virtual machine, database, and website without publishing your web application, use the Publish-WebApplication.ps1 command with the -Configuration argument set to the JSON configuration file. Используя файл конфигурации JSON, эта командная строка определяет, какие именно ресурсы нужно создать. This command line uses the JSON configuration file to determine which resources to create. Так как для других аргументов командной строки используются параметры по умолчанию, командная строка создает ресурсы, не публикуя веб-приложение. Because it uses the default settings for other command-line arguments, it creates the resources, but doesn’t publish your web application. Параметр -Verbose позволяет получить дополнительные сведения о том, что происходит при выполнении командной строки. The –Verbose option gives you more information about what’s happening.
С помощью команды Publish-WebApplication.ps1 вызовите сценарий и опубликуйте свое веб-приложение (см. пример ниже). Use the Publish-WebApplication.ps1 command as shown in one of the following examples to invoke the script and publish your web application. Если вам нужно изменить стандартные параметры других аргументов, например имя подписки, имя публикуемого пакета, учетные данные виртуальной машины или сервера базы данных, укажите эти параметры. If you need to override the default settings for any of the other arguments, such as the subscription name, publish package name, virtual machine credentials, or database server credentials, you can specify those parameters. Параметр -Verbose позволяет получить дополнительные сведения о ходе публикации. Use the –Verbose option to see more information about the progress of the publishing process.
Если вы создаете виртуальную машину, команда должна выглядеть так, как показано в примере ниже. If you’re creating a virtual machine, the command looks like the following. В этом примере также показано, как указывать учетные данные для нескольких баз данных. This example also shows how to specify the credentials for multiple databases. SSL-сертификат виртуальных машин, создаваемых этими сценариями, происходит из ненадежного корневого центра. For the virtual machines that these scripts create, the SSL certificate is not from a trusted root authority. Поэтому вам нужно использовать параметр -AllowUntrusted . Therefore, you need to use the –AllowUntrusted option.
Этот сценарий создает базы данных. Он не может создавать серверы баз данных. The script can create databases, but it doesn’t create database servers. Если вы хотите создать сервер базы данных, используйте функцию New-AzureSqlDatabaseServer в модуле Azure. If you want to create a database server, you can use the New-AzureSqlDatabaseServer function in the Azure module.
Настройка и расширение сценариев публикации Customizing and extending the publish scripts
Вы можете настраивать сценарии публикации и изменять файл конфигурации JSON. You can customize the publish script and JSON configuration file. Функции в модуле Windows PowerShell AzureWebAppPublishModule.psm1 нельзя изменять. The functions in the Windows PowerShell module AzureWebAppPublishModule.psm1 are not intended to be modified. Чтобы выбрать другую базу данных или изменить некоторые свойства виртуальной машины, внесите необходимые изменения в файл конфигурации JSON. If you just want to specify a different database or change some of the properties of the virtual machine, edit the JSON configuration file. Если вы хотите расширить функциональность сценария и автоматизировать сборку и тестирование проекта, добавьте заготовки функций в файл Publish-WebApplication.ps1. If you want to extend the functionality of the script to automate building and testing your project, you can implement function stubs in Publish-WebApplication.ps1.
Чтобы автоматизировать сборку проекта, добавьте код, вызывающий функцию MSBuild New-WebDeployPackage (см. пример кода ниже). To automate building your project, add code that calls MSBuild to New-WebDeployPackage as shown in this code example. Путь к команде MSBuild зависит от установленной версии Visual Studio. The path to the MSBuild command is different depending on the version of Visual Studio you have installed. Получить правильный путь можно с помощью функции Get-MSBuildCmd (см. пример ниже). To get the correct path, you can use the function Get-MSBuildCmd, as shown in this example.
Автоматизация сборки проекта To automate building your project
Добавьте параметр $ProjectFile в раздел глобальных параметров. Add the $ProjectFile parameter in the global param section.
Скопируйте функцию Get-MSBuildCmd в файл сценария. Copy the function Get-MSBuildCmd into your script file.
Замените New-WebDeployPackage следующим кодом и замените заполнители в строке $msbuildCmd . Replace New-WebDeployPackage with the following code and replace the placeholders in the line constructing $msbuildCmd . Этот код предназначен для Visual Studio 2019. This code is for Visual Studio 2019. Если вы используете Visual Studio 2017, замените значение свойства VisualStudioVersion на 15.0 , если у вас Visual Studio 2015 — на 14.0, если Visual Studio 2013 — на 12.0 . If you’re using Visual Studio 2017, change the VisualStudioVersion property to 15.0 , ‘14.0’ for Visual Studio 2015, or 12.0 for Visual Studio 2013).
Для создания веб-приложения используйте файл MsBuild.exe. To build your web application, use MsBuild.exe. Справочные сведения см. в справочнике по Command-Line MSBuild For help, see MSBuild Command-Line Reference
Запуск команды сборки Start execution of the build command
Вызовите функцию New-WebDeployPackage перед строкой $Config = Read-ConfigFile $Configuration (для веб-приложений) или $Config = Read-ConfigFile $Configuration -HasWebDeployPackage:([Bool]$WebDeployPackage) (для виртуальных машин). Call the New-WebDeployPackage function before this line: $Config = Read-ConfigFile $Configuration for web apps or $Config = Read-ConfigFile $Configuration -HasWebDeployPackage:([Bool]$WebDeployPackage) for virtual machines.
Вызовите настроенный сценарий из командной строки, передав аргумент $Project , как показано в примере ниже. Invoke the customized script from command line using passing the $Project argument, as in the following example:
Чтобы автоматизировать тестирование приложения, добавьте код в Test-WebApplication . To automate testing of your application, add code to Test-WebApplication . Обязательно раскомментируйте строки в файле Publish-WebApplication.ps1 , в которых вызываются эти функции. Be sure to uncomment the lines in Publish-WebApplication.ps1 where these functions are called. Если реализация не указана, проект можно вручную собрать в Visual Studio и опубликовать его в Azure с помощью сценария публикации. If you don’t provide an implementation, you can manually build your project with Visual Studio, and then run the publish script to publish to Azure.
Обзор функций публикации Publishing function summary
Чтобы получить справку по функциям, выполните в командной строке Windows PowerShell команду Get-Help function-name . To get help for functions you can use at the Windows PowerShell command prompt, use the command Get-Help function-name . Справочная информация содержит описание параметров и примеры их использования. The help includes parameter help and examples. Этот же текст справки также находится в исходных файлах сценария азуревебапппублишмодуле. PSM1 и Publish-WebApplication.ps1. The same help text is also in the script source files AzureWebAppPublishModule.psm1 and Publish-WebApplication.ps1. Сценарий и справка переведены на язык интерфейса Visual Studio. The script and help are localized in your Visual Studio language.
AzureWebAppPublishModule AzureWebAppPublishModule
Имя функции Function name | Описание Description |
---|---|
Add-AzureSQLDatabase Add-AzureSQLDatabase | Создает новую базу данных SQL Azure. Creates a new Azure SQL database. |
Add-AzureSQLDatabases Add-AzureSQLDatabases | Создает базы данных SQL Azure на основе значений в файле конфигурации JSON, который создается в Visual Studio. Creates Azure SQL databases from the values in the JSON configuration file that Visual Studio generates. |
Add-AzureVM Add-AzureVM | Создает виртуальную машину Azure и возвращает URL-адрес развернутой виртуальной машины. Creates an Azure virtual machine and returns the URL of the deployed VM. Функция настраивает обязательные компоненты и затем вызывает функцию New-AzureVM (в модуле Azure), которая создает виртуальную машину. The function sets up the prerequisites and then calls the New-AzureVM function (Azure module) to create a new virtual machine. |
Add-AzureVMEndpoints Add-AzureVMEndpoints | Добавляет новые входные конечные точки для виртуальной машины и возвращает виртуальную машину с новой конечной точкой. Adds new input endpoints to a virtual machine and returns the virtual machine with the new endpoint. |
Add-AzureVMStorage Add-AzureVMStorage | Создает в текущей подписке новую учетную запись хранения Azure. Creates a new Azure storage account in the current subscription. Имя учетной записи начинается с devtest, после чего следует уникальная строка из букв и цифр. The name of the account begins with «devtest» followed by a unique alphanumeric string. Функция возвращает имя новой учетной записи хранения. The function returns the name of the new storage account. Для новой учетной записи хранения укажите расположение или территориальную группу. Specify either a location or an affinity group for the new storage account. |
Add-AzureWebsite Add-AzureWebsite | Создает веб-сайт с указанными именем и расположением. Creates a website with the specified name and location. Эта функция вызывает функцию New-AzureWebsite в модуле Azure. This function calls the New-AzureWebsite function in the Azure module. Если в подписке еще нет веб-сайта с указанным именем, функция создает его и возвращает объект веб-сайта. If the subscription doesn’t already include a website with the specified name, this function creates the website and returns a website object. В противном случае возвращается значение $null . Otherwise, it returns $null . |
Backup-Subscription Backup-Subscription | Сохраняет текущую подписку Azure в переменной $Script:originalSubscription в области сценария. Saves the current Azure subscription in the $Script:originalSubscription variable in script scope. Эта функция сохраняет текущую подписку Azure (полученную с помощью команды Get-AzureSubscription -Current ) и ее учетную запись хранения, а также подписку, которую изменяет этот сценарий (хранится в переменной $UserSpecifiedSubscription ), и ее учетную запись хранения в области сценария. This function saves the current Azure subscription (as obtained by Get-AzureSubscription -Current ) and its storage account, and the subscription that is changed by this script (stored in the variable $UserSpecifiedSubscription ) and its storage account, in script scope. Сохранив эти значения, вы сможете (например, с помощью функции Restore-Subscription ) восстановить исходное состояние текущей подписки и учетной записи хранения, если оно изменилось. By saving the values, you can use a function, such as Restore-Subscription , to restore the original current subscription and storage account to current status if the current status has changed. |
Find-AzureVM Find-AzureVM | Возвращает указанную виртуальную машину Azure. Gets the specified Azure virtual machine. |
Format-DevTestMessageWithTime Format-DevTestMessageWithTime | Добавляет в сообщение дату и время. Prepends the date and time to a message. Эта функция предназначена для сообщений, которые записываются в потоки Error и Verbose. This function is designed for messages written to the Error and Verbose streams. |
Get-AzureSQLDatabaseConnectionString Get-AzureSQLDatabaseConnectionString | Собирает строку подключения к базе данных SQL Azure. Assembles a connection string to connect to an Azure SQL database. |
Get-AzureVMStorage Get-AzureVMStorage | Возвращает имя первой учетной записи хранения с шаблоном имени «devtest » (без учета регистра) в указанном расположении или территориальной группе. Если учетная запись хранения «devtest» не соответствует расположению или территориальной группе, функция пропускает ее. Returns the name of the first storage account with the name pattern «devtest » (case insensitive) in the specified location or affinity group. If the «devtest» storage account doesn’t match the location or affinity group, the function ignores it. Укажите расположение или территориальную группу. Specify either a location or an affinity group. |
Get-MSDeployCmd Get-MSDeployCmd | Возвращает команду для запуска средства MsDeploy.exe. Returns a command to run the MsDeploy.exe tool. |
New-AzureVMEnvironment New-AzureVMEnvironment | Находит или создает в подписке виртуальную машину, которая соответствует значениям в файле конфигурации JSON. Finds or creates a virtual machine in the subscription that matches the values in the JSON configuration file. |
Publish-WebPackage Publish-WebPackage | Развертывает ресурсы на веб-сайт с помощью средства MsDeploy.exe и пакета веб-публикации (ZIP-файл). Uses MsDeploy.exe and a web publish package .Zip file to deploy resources to a website. Эта функция не создает никаких выходных данных. This function doesn’t generate any output. Если вызов MSDeploy.exe завершился ошибкой, функция создает исключение. If the call to MSDeploy.exe fails, the function throws an exception. Чтобы получить более подробные выходные данные, используйте параметр -Verbose . To get more detailed output, use the -Verbose option. |
Publish-WebPackageToVM Publish-WebPackageToVM | Проверяет значения параметров, а затем вызывает функцию Publish-WebPackage . Verifies the parameter values, and then calls the Publish-WebPackage function. |
Read-ConfigFile Read-ConfigFile | Проверяет файл конфигурации JSON и возвращает хэш-таблицу выбранных значений. Validates the JSON configuration file and returns a hash table of selected values. |
Restore-Subscription Restore-Subscription | Восстанавливает исходное состояние подписки. Resets the current subscription to the original subscription. |
Test-AzureModule Test-AzureModule | Возвращает $true , если установленный модуль Azure имеет версию 0.7.4 и выше. Returns $true if the installed Azure module version is 0.7.4 or later. Возвращает $false , если модуль не установлен или имеет более раннюю версию. Returns $false if the module isn’t installed or is an earlier version. У этой функции нет параметров. This function has no parameters. |
Test-AzureModuleVersion Test-AzureModuleVersion | Возвращает $true , если модуль Azure имеет версию 0.7.4 и выше. Returns $true if the version of the Azure module is 0.7.4 or later. Возвращает $false , если модуль не установлен или имеет более раннюю версию. Returns $false if the module isn’t installed or is an earlier version. У этой функции нет параметров. This function has no parameters. |
Test-HttpsUrl Test-HttpsUrl | Преобразует входной URL-адрес в объект System.Uri. Converts the input URL to a System.Uri object. Возвращает $True , если URL-адрес является абсолютным адресом и использует схему HTTPS. Returns $True if the URL is absolute and its scheme is https. Возвращает $false , если URL-адрес является относительным, не использует схему HTTPS или входную строку невозможно преобразовать в URL-адрес. Returns $false if the URL is relative, its scheme isn’t HTTPS, or the input string can’t be converted to a URL. |
Test-Member Test-Member | Возвращает $true , если свойство или метод является членом объекта. Returns $true if a property or method is a member of the object. В противном случае возвращается $false . Otherwise, returns $false . |
Write-ErrorWithTime Write-ErrorWithTime | Записывает сообщение об ошибке с текущим временем в префиксе. Writes an error message prefixed with the current time. Эта функция вызывает функцию Format-DevTestMessageWithTime , которая добавляет время перед записью сообщения в поток Error. This function calls the Format-DevTestMessageWithTime function to prepend the time before writing the message to the Error stream. |
Write-HostWithTime Write-HostWithTime | Записывает в основную программу (Write-Host) сообщение с текущим временем в префиксе. Writes a message to the host program (Write-Host) prefixed with the current time. Результат записи в основную программу варьируется. The effect of writing to the host program varies. Большинство программ, использующих Windows PowerShell, записывают эти сообщения в стандартный вывод. Most programs that host Windows PowerShell write these messages to standard output. |
Write-VerboseWithTime Write-VerboseWithTime | Записывает подробное сообщение с текущим временем в префиксе. Writes a verbose message prefixed with the current time. Так как функция вызывает функцию Write-Verbose, сообщение появляется, только если сценарий запускается с параметром -Verbose или для параметра VerbosePreference задано значение Continue. Because it calls Write-Verbose, the message displays only when the script runs with the Verbose parameter or when the VerbosePreference preference is set to Continue. |
Publish-WebApplication Publish-WebApplication
Имя функции Function name | Описание Description |
---|---|
New-AzureWebApplicationEnvironment New-AzureWebApplicationEnvironment | Создает ресурсы Azure, например веб-сайт или виртуальную машину. Creates Azure resources, such as a website or virtual machine. |
New-WebDeployPackage New-WebDeployPackage | Эта функция не реализована. This function isn’t implemented. В нее можно добавлять команды для сборки проекта. You can add commands in this function to build your project. |
Publish-AzureWebApplication Publish-AzureWebApplication | Публикует веб-приложение в Azure. Publishes a web application to Azure. |
Publish-WebApplication Publish-WebApplication | Создает и развертывает веб-приложения, виртуальные машины, базы данных SQL и учетные записи хранения для веб-проекта Visual Studio. Creates and deploys Web Apps, virtual machines, SQL databases, and storage accounts for a Visual Studio web project. |
Test-WebApplication Test-WebApplication | Эта функция не реализована. This function isn’t implemented. В нее можно добавлять команды для тестирования приложения. You can add commands in this function to test your application. |
Дальнейшие действия Next steps
Дополнительные сведения о сценариях PowerShell см. в статье Работа со сценариями в Windows PowerShell. Рекомендуем также посетить центр сценариев и ознакомиться с другими сценариями Azure PowerShell. Learn more about PowerShell scripting by reading Scripting with Windows PowerShell and see other Azure PowerShell scripts at the Script Center.