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

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

问题描述

使用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

相关文章
|
20天前
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
|
20天前
【Azure Web Job】Azure Web Job执行Powershell脚本报错 The term 'Select-AzContext' is not recognized as the name
【Azure Web Job】Azure Web Job执行Powershell脚本报错 The term 'Select-AzContext' is not recognized as the name
|
20天前
|
存储 C# Python
【Azure Storage Account】Azure 存储服务计算Blob的数量和大小的PowerShell代码
【Azure Storage Account】Azure 存储服务计算Blob的数量和大小的PowerShell代码
|
20天前
|
Ubuntu Linux 测试技术
【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例
【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例
|
10月前
|
Shell Linux 开发工具
windows中cmd和PowerShell批处理命令
之前在 Git 批量删除本地分支,有用到 Linux 或 MacOS 下的批处理命令,这个命令中的 grep、xargs 本身是 Shell script,在 windows 中的 cmd 和 PowerShell 中是不能用的
77 0
|
JavaScript Windows
[Vue]解决 Windows PowerShell 不识别 vue 命令的问题
[Vue]解决 Windows PowerShell 不识别 vue 命令的问题
|
Windows
使用PowerShell获取Windows当前锁屏壁纸
使用PowerShell获取Windows当前锁屏壁纸 如果原始图片丢了,用这段代码就可以提取当前锁屏壁纸了!
159 0
|
应用服务中间件 nginx Windows
Windows PowerShell 中启动 Nginx 报错解决方案
Windows PowerShell 中启动 Nginx 报错解决方案
Windows PowerShell 中启动 Nginx 报错解决方案
|
XML 监控 数据格式
利用powershell进行windows日志分析
0x00 前言   Windows 中提供了 2 个分析事件日志的 PowerShell cmdlet:一个是Get-WinEvent,超级强大,但使用起来比较麻烦;另一个是Get-EventLog,使得起来相当简单,可以实时筛选,接下来,我们利用PowerShell 来自动筛选 Windows 事件日志。
2499 0