我在 Azure 文件共享上有一个文件,我想下载它、修改它,然后使用 Powershell 再次上传它。这是我到目前为止编写的代码,但它不起作用:
$context = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
$share = Get-AzStorageShare -Name $shareName -Context $context
$client = $share.CloudBlob.OpenRead($filePath)
$file = $client.DownloadText()
不幸的是它给了我一个错误。代码可能有什么问题?
我在 Azure 文件共享上有一个文件,如下所示:
使用 Azure 自动化修改脚本并上传它,您可以制作如下脚本。
$Appid = "789da472-e33e-4de6-bada-XXXXXXX"
$PWord = ConvertTo-SecureString -String "Yig8Q~_R_RPrl_Wrcn2CX5VAsngwR1tXXXXXXX" -AsPlainText -Force
$tenant = "72f988bf-86f1-41af-91ab-2dXXXXXXX"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Appid, $PWord
# Authenticate
$null = Add-AzAccount -Credential $Credential -Tenant $tenant -ServicePrincipal
$storageAccountName = "xxxxx"
$storageAccountKey = "euf04t6rJW7z7UKr1VhSlfduHAlouTZ7/rxzzMhmOE7XXXXXXXXXXXXXXX"
# File share information
$shareName = "file1"
$filePath = 'demo.txt'
try {
# Construct the storage context
$context = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
# Define a temporary directory within the Azure Automation sandbox
$tempPath = Join-Path $env:TEMP "tempfile1.txt"
Write-Output "Share Name: $shareName"
Write-Output "Temporary Path: $tempPath"
# Get the file content from the Azure File Share
Write-Output "Getting file content from Azure File Share..."
Get-AzStorageFileContent -ShareName $shareName -Path $filePath -Destination $tempPath -Context $context
Write-Output "File content retrieved and saved to temporary directory."
# Read and modify the file content
$fileContent = Get-Content $tempPath
Write-Output $fileContent
$newFileContent = $fileContent -replace 'Imran123', 'Khan123'
$newFileContent | Set-Content $tempPath
Write-Output $newFileContent
Set-AzStorageFileContent -ShareName $shareName -Source $tempPath -Path $filePath -Context $context -Force
Write-Output "Modified file content uploaded."
}
catch {
Write-Output "An error occurred: $_"
}
# Sign out to avoid potential issues with credentials
Remove-AzAccount -Scope Process
现在,当我运行上面的脚本时,文件被修改并成功上传到文件共享中,如下所示:
输出: