如何将一组Powershell命令转换为可以在需要时运行的脚本?

时间:2019-09-05 14:22:10

标签: azure azure-powershell

我有一套可以在azure powershell中使用的命令。这些命令创建了一个资源组,应用程序服务等。我想将它们捆绑在一起,这样我就可以在终端中键入一个命令并一次性运行所有部署。

# Ask user for work item id
$workItemId = Read-Host -Prompt "Enter the Work Item ID"

# Set Variables
$appdirectory="C:\Users\Charles\Desktop\Timesheet App\Discover\Client\build"
$webappname="discoverTest$workItemId"
$location="West Europe"

# Create a resource group.
New-AzResourceGroup -Name discoverTest$workItemId -Location $location

# Create an App Service plan in `Free` tier.
New-AzAppServicePlan -Name $webappname -Location $location `
-ResourceGroupName discoverTest$workItemId -Tier Free

# Create a web app.
New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname `
-ResourceGroupName discoverTest$workItemId

# Get publishing profile for the web app
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname `
-ResourceGroupName discoverTest$workItemId `
-OutputFile null)

# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
$url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

# Upload files recursively 
Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse #Removed IsContainer condition
foreach ($file in $files)
{
    $relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')  
    $uri = New-Object System.Uri("$url/$relativepath")

    if($file.PSIsContainer)
    {
        $uri.AbsolutePath + "is Directory"
        $ftprequest = [System.Net.FtpWebRequest]::Create($uri);
        $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
        $ftprequest.UseBinary = $true

        $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

        $response = $ftprequest.GetResponse();
        $response.StatusDescription
        continue
    }

    "Uploading to " + $uri.AbsoluteUri + " from "+ $file.FullName

    $webclient.UploadFile($uri, $file.FullName)
} 
$webclient.Dispose()



$workItemId = Read-Host -Prompt "Enter the Work Item ID"
Remove-AzResourceGroup -Name "discoverTest$workItemId" -Force

# print variable
Write-Host $variable

我希望能够运行一个命令并执行完整的部署过程。

1 个答案:

答案 0 :(得分:0)

有两种方法可以满足您的需求,如下所示。

  1. 提取在这些PowerShell命令行中使用的所有参数作为PowerShell脚本<your-script-name>.ps1的参数,该脚本包括与您相同的所有命令。请参考现有的SO线程How to handle command-line arguments in PowerShell以了解操作方法。然后,您只需要在预先安装了Azure PowerShell模块的终端中使用这些参数运行<your-script-name>.ps1

  2. 跟随博客Four ways to package a non-GUI PowerShell script as an executable file使用当前命令集制作可执行文件。

通常,我认为第一种方法更好,值得推荐。