FTP を使用して Web アプリにファイルをアップロードする

このサンプル スクリプトは、App Service で Web アプリを関連リソースと合わせて作成し、そこに FTP を使用してファイルをデプロイします (System.Net.FtpWebRequest を使用)。

必要に応じて、Azure PowerShell ガイドの手順に従って Azure PowerShell をインストールし、Connect-AzAccount を実行して、Azure との接続を作成します。

サンプル スクリプト

注意

Azure を操作するには、Azure Az PowerShell モジュールを使用することをお勧めします。 作業を開始するには、Azure PowerShell のインストールに関する記事を参照してください。 Az PowerShell モジュールに移行する方法については、「AzureRM から Az への Azure PowerShell の移行」を参照してください。

$filePath="<Replace with full file path>"
$webappname="mywebapp$(Get-Random)"
$location="West Europe"

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

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

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

# Get publishing profile for the web app
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname `
-ResourceGroupName myResourceGroup `
-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 file 
$file = Get-Item -Path $filePath
$uri = New-Object System.Uri("$url/$($file.Name)")

$request = [System.Net.FtpWebRequest]([System.net.WebRequest]::Create($uri))
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$request.Credentials = New-Object System.Net.NetworkCredential($username,$password)

# Enable SSL for FTPS. Should be $false if FTP.
$request.EnableSsl = $true;

# Write the file to the request object.
$fileBytes = [System.IO.File]::ReadAllBytes($filePath)
$request.ContentLength = $fileBytes.Length;
$requestStream = $request.GetRequestStream()

try {
    $requestStream.Write($fileBytes, 0, $fileBytes.Length)
}
finally {
    $requestStream.Dispose()
}

Write-Host "Uploading to $($uri.AbsoluteUri)"

try {
    $response = [System.Net.FtpWebResponse]($request.GetResponse())
    Write-Host "Status: $($response.StatusDescription)"
}
finally {
    if ($null -ne $response) {
        $response.Close()
    }
}

デプロイのクリーンアップ

サンプル スクリプトの実行後、次のコマンドを使用すると、リソース グループ、Web アプリ、およびすべての関連リソースを削除できます。

Remove-AzResourceGroup -Name myResourceGroup -Force

スクリプトの説明

このスクリプトでは、次のコマンドを使用します。 表内の各コマンドは、それぞれのドキュメントにリンクされています。

コマンド メモ
New-AzResourceGroup すべてのリソースを格納するリソース グループを作成します。
New-AzAppServicePlan App Service プランを作成します。
New-AzWebApp Web アプリを作成します。
Get-AzWebAppPublishingProfile Web アプリの発行プロファイルを取得します。

次のステップ

Azure PowerShell モジュールの詳細については、Azure PowerShell のドキュメントを参照してください。

その他の Azure App Service Web Apps 用 Azure PowerShell サンプルは、Azure PowerShell サンプルのページにあります。