You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本本地运行正常,部署至Azure Function后执行失败

解决Azure Function中PowerShell脚本DateTime.Substring()报错问题

问题根源

错误提示明确指向:$item.date在Azure Function环境中是**[System.DateTime]类型**,而DateTime类本身没有.Substring()方法,因此调用失败。本地环境中$item.date是字符串类型,所以能正常执行截取操作——这是本地(PowerShell 7.3.10)与云端(PowerShell 7.2)环境中数据源类型映射的差异导致的。


解决方案

方案1:直接格式化DateTime对象(推荐)

既然云端的$item.date已经是DateTime类型,无需先转字符串再截取,直接格式化即可:

# 直接将DateTime格式化为yyyy-MM-dd格式的字符串
$creation_date = $item.date.ToString('yyyy-MM-dd')

# 注:如果$item.date本身就是DateTime,$parsedDate可直接赋值,无需重复解析
$parsedDate = $item.date
# 若必须通过字符串解析确认格式,可保留以下代码(非必要)
# $parsedDate = [DateTime]::ParseExact($creation_date, 'yyyy-MM-dd', $null)

方案2:兼容本地与云端的类型差异

如果需要脚本同时适配本地(字符串类型)和云端(DateTime类型)环境,可添加类型判断逻辑:

# 根据$item.date的类型选择对应处理方式
if ($item.date -is [string]) {
    $creation_date = $item.date.Substring(0,10)
}
else {
    $creation_date = $item.date.ToString('yyyy-MM-dd')
}

$parsedDate = [DateTime]::ParseExact($creation_date, 'yyyy-MM-dd', $null)

内容的提问来源于stack exchange,提问作者Micksta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:26:17