您的位置:首页 > 运维架构 > Shell

【Azure 应用服务】在Azure Funciton中使用Powershell脚本函数,需要存储一些变量值如何解决?

2020-12-29 17:57 1306 查看

问题描述

使用Azure Function创建Powershell脚本来执行函数,在使用中需要存储一些不重要的参数。一般情况,存储的问题都是交给DB,Storage等来解决。但是有没有一种简单的办法呢?就用Powershell命令把参数的内容输出到txt文件中,然后每次需要使用的时候就直接使用get-content呢? 

由于Azure Funciton是被触发运行或者是定时运行,这表示代码在执行完一次后将释放资源,所以不能通过变量的方式来存储数据。

解决办法

在不使用数据库的情况下,就通过在Azure Funciton的Home目录中生成文件并在文件中保存参数值。 这里Home目录的路径和Azure App Service一样,即可以是D:\Home\,也可以是%home%\

在Powershell funciton中的代码为:

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

$date = Get-Date -Format yyyy-mm-dd-hh-mm-ss

Write-Host "the new data is: $date "

$date | out-file -filepath d:\home\namelist.txt -Encoding utf8 -append -width 200
$sdata = Get-Content -Path d:\home\namelist.txt
#$sdata = (Get-Content -Path d:\home\namelist.txt)[-1]

Write-Host "File content is: $sdata "

 

首先通过Powershell的 out-file方法把 $data中的内容保存到文件d:\home\namelist.txt中。注意需要使用utf8编码。以避免乱码的情况。

然后通过Get-Connect从文件中读取内容赋值到新参数中。这样即实现了通过文件内容读取历史保留的任何参数。

测试结果如下图:

 

 

参考资料

在 Azure 中使用 Visual Studio Code 创建 PowerShell 函数: https://docs.azure.cn/zh-cn/azure-functions/create-first-function-vs-code-powershell
Out-File: https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Out-File?view=powershell-7.1
Get-Content: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-7.1

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐