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

解决Microsoft Graph PowerShell中New-MgDriveItem创建文件夹报错问题

解决New-MgDriveItem创建OneDrive文件夹时的类型错误

问题描述

执行以下PowerShell代码创建OneDrive文件夹时:

New-MgDriveItem -DriveId $Global:driveId -BodyParameter @{
    name = "TestFolder"
    folder = @{}  # 明确指定该项目为文件夹
}

收到错误提示:

Either 'folder' or 'file' must be provided, but not both.

问题原因

PowerShell的空哈希表@{}在被Microsoft Graph PowerShell模块转换为JSON请求体时,会被序列化为null。而OneDrive API要求必须明确提供非空的folder或file字段来标识项目类型,当folder为null时,API判定未提供有效类型,因此抛出错误。

解决方案

方案1:使用PSCustomObject构造请求体

通过PSCustomObject定义请求体,确保空的folder对象被正确序列化为{}而非null:

$folderBody = [PSCustomObject]@{
    name = "TestFolder"
    folder = [PSCustomObject]@{}
}
New-MgDriveItem -DriveId $Global:driveId -BodyParameter $folderBody

方案2:直接传递JSON字符串

手动构造符合要求的JSON字符串,并指定内容类型,避免模块自动转换导致的问题:

$jsonBody = @"
{
    "name": "TestFolder",
    "folder": {}
}
"@
New-MgDriveItem -DriveId $Global:driveId -BodyParameter $jsonBody -ContentType "application/json"

内容的提问来源于stack exchange,提问作者Mr.Wosch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:32:35