PowerShell中Register-ObjectEvent结合ConvertTo-Json后无执行无报错问题
文件监控触发REST API无响应无报错排查
我实现了文件创建时触发操作的功能,这部分运行正常。但在调用REST API并使用
ConvertTo-Json格式化请求体后,既没有报错也没有任何反应。以下是我使用的代码:
$folder = 'C:\VMForTest_Files\IDM Process' # Enter the root path you want to monitor. $filter = '*.*' # You can enter a wildcard filter here. # Login to Rest API goes here # In the following line, you can change 'IncludeSubdirectories to $true if required. $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} $Action = { $name = $Event.SourceEventArgs.Name $changeType = $Event.SourceEventArgs.ChangeType $timeStamp = $Event.TimeGenerated Write-Host "1.The file '$name' was $changeType at $timeStamp" -fore green Out-File -FilePath C:\VMForTest_Files\log\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp" $filecontent = Get-Content -Path ($folder + "\\" + $name) $BaseDesc = $filecontent $BaseHead = "New IDM Event" $entityType = "u_EVE" $Body = @{ entityType = $entityType BaseHeader = $BaseHead BaseDescription = $BaseDesc PriorityId = 7 CategoryId = 7 BaseEntityStatusId = 55 AgentGroupId = 1 BaseEntitySource = 1 FormId = 79 } | ConvertTo-Json $result = Invoke-RestMethod -Method 'POST' -Uri $saveentity -Headers $headers -Body $Body # -StatusCodeVariable 'statusCode' Write-Host "99.The file '$name' was $changeType at $timeStamp" -fore green } Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action $action
排查与解决步骤
修复变量作用域问题:事件动作脚本块
$Action是独立作用域,默认无法访问主脚本定义的$saveentity和$headers变量。需要用$using:前缀引用外部变量,修改后的请求行应为:$result = Invoke-RestMethod -Method 'POST' -Uri $using:saveentity -Headers $using:headers -Body $Body -ContentType 'application/json'强制指定Content-Type:使用
ConvertTo-Json生成JSON请求体时,必须显式添加-ContentType 'application/json'参数,否则服务器可能无法识别请求格式,导致无响应。修正文件内容读取方式:
Get-Content默认返回字符串数组,若文件有多行内容,$BaseDesc会被转成JSON数组,可能不符合API对字符串类型参数的要求。改成用-Raw参数读取整个文件为单个字符串:$BaseDesc = Get-Content -Path ($folder + "\\" + $name) -Raw添加错误捕获与日志记录:事件动作块中的异常不会直接输出到控制台,需要加入
try/catch捕获错误并写入日志,方便排查:try { $result = Invoke-RestMethod -Method 'POST' -Uri $using:saveentity -Headers $using:headers -Body $Body -ContentType 'application/json' Out-File -FilePath C:\VMForTest_Files\log\apilog.txt -Append -InputObject "[$timeStamp] API请求成功,文件:$name,结果:$($result | ConvertTo-Json -Compress)" } catch { Out-File -FilePath C:\VMForTest_Files\log\apierrorlog.txt -Append -InputObject "[$timeStamp] API请求失败,文件:$name,错误信息:$($_.Exception.Message),状态码:$($_.Exception.Response.StatusCode.value__)" }验证请求体格式:在调用API前,把生成的JSON请求体写入日志,检查是否符合API的参数规范:
Out-File -FilePath C:\VMForTest_Files\log\requestbody.txt -Append -InputObject "[$timeStamp] 请求体(文件:$name):$Body"
内容的提问来源于stack exchange,提问作者aerobat
相关产品推荐
相关产品推荐

