我有一个PowerShell脚本,该脚本连接到localhost API,该API返回“会话”的字典,以及它们是否处于活动状态
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$response = Invoke-RestMethod 'https://localhost:44356/api/RDM/getSessions' -Method 'GET' -Headers $headers
$numOfUsers = Invoke-RestMethod 'https://localhost:44356/api/RDM/countSessions' -Method 'GET' -Headers $headers
for($x = 0; $x -lt $numOfUsers; $x++)
{
$user = $response.userId[$x]
$name = $response.sessionName[$x]
"`nSession Name: $name"
"User Logged In: $user`n"
}
pause
当多个会话处于活动状态时,它将正确返回:
Session Name: ExampleSession
User Logged In: ExampleUser
但是,当只有1处于活动状态时,它仅返回第一个字母:
Session Name: E
User Logged In: E
我确实知道此错误是由脚本而不是API引起的,但是到目前为止,我无法找到问题的根源。
含义是,如果仅返回一个会话,$response.userId
而$response.sessionName
不是单元素数组,而只是字符串-索引到字符串将返回字符(例如,'foo'[0]
return 'f'
)。[1]
您可以使用@()
,该阵列子表达式运算符,以确保你总是处理数组:
$user = @($response.userId)[$x]
$name = @($response.sessionName)[$x]
如果会话数可能很大,则以下操作会更好(因为@(...)
创建数组的浅副本[2],而[array]
强制转换按原样使用现有的数组):
$user = ([array] $response.userId)[$x]
$name = ([array] $response.sessionName)[$x]
[1]请注意,与C#不同,返回的字符在技术上也是字符串([string]
,System.String
),而不是[char]
(System.Char
)实例,因为PowerShell本身不使用该[char]
类型。
[2]在较旧的PowerShell版本(v5.0之前的版本)中,这也适用于具有明确枚举元素的数组;例如,@('foo', 'bar')
但是此案例已经过优化,以适应使用此类表达式定义数组文字的广泛实践-即使@(...)
并不需要严格要求('foo', 'bar'
单独也可以)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句