目录
5.1 添加/上传文件 - Add-FTPItem (Send-FTPItem)
5.2 获取目录下面的文件、子目录 - Get-FTPChildItem
5.3 下载文件 - Get-FTPItem(Receive-FTPItem)
5.7 重命名文件或者目录 - Rename-FTPItem(Move-FTPItem)
5.8 检查文件或者目录是否存在 - Test-FTPItem
1. 前言
之前在【Azure - App Service】如何使用PowerShell一键部署前端代码到微软Azure云的App Service上_码农杰克的博客-优快云博客
中提到在之前尝试部署前端代码到Azure云上时,曾尝试过使用FTP来操作。但是很不幸没有成功,不过倒是对PowerShell如何操作FTP搞明白了。 所以接下来对PowerShell操作FTP作一番记录,以备后用。
2. 遇见PSFTP
其实PowerShell本身并没了内置对FTP的支持,但是.net里面内置了FTP操作的类。当时在微软官方文档上看到了下面一段示例代码,主要就是演示如何通过PowerShell上传前端代码到Azure 的APP Service 上。PowerShell: Upload files using FTP - Azure App Service | Microsoft DocsLearn how to use Azure PowerShell to automate deployment and management of App Service. This sample shows how to upload files to an app using FTP.https://docs.microsoft.com/en-us/azure/app-service/scripts/powershell-deploy-ftp
$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()
}
}
这段代码只是C#与PowerShell的混合编程,因为PowerShell本身支持内嵌C#代码,并且在PowerShell中可以直接使用C#库。其中就有一个[System.Net.FtpWebRequest],这个就是.net里内置的FTP操作类。感兴趣的同学请参考下面的连接。