Javascript 为什么PowerShell函数的返回类型总是数组?
我正试图编写一个PowerShell函数,在网页上执行JavaScript/jQuery并将结果返回给PowerShell。我们使用Javascript 为什么PowerShell函数的返回类型总是数组?,javascript,jquery,powershell,scripting,powershell-3.0,Javascript,Jquery,Powershell,Scripting,Powershell 3.0,我正试图编写一个PowerShell函数,在网页上执行JavaScript/jQuery并将结果返回给PowerShell。我们使用setAttribute将JavaScript返回值存储在DOM中,然后使用getAttribute在PowerShell中检索它。然而,以下问题困扰了我几天。请参阅以下评论: Function ExecJavaScript($ie, $jsCommand, [switch]$global) { if (!$global) { $jsComm
setAttribute
将JavaScript返回值存储在DOM中,然后使用getAttribute
在PowerShell中检索它。然而,以下问题困扰了我几天。请参阅以下评论:
Function ExecJavaScript($ie, $jsCommand, [switch]$global)
{
if (!$global) {
$jsCommand = "document.body.setAttribute('PSResult', (function(){$jsCommand})());"
}
$document = $ie.document
$window = $document.parentWindow
$window.execScript($jsCommand, 'javascript')
if (!$global) {
$psresult = $document.body.getAttribute('PSResult')
# Why no matter what I do, this always returns an array instead of a String?
return $psresult.ToString()
#return @($psresult)
#return @($psresult).ToString()
#return ($psresult | select -First 1)
#return ($psresult -join '')
}
}
$ie = New-Object -COM InternetExplorer.Application -Property @{
Navigate = "https://www.google.com/"
Visible = $true
}
do { Start-Sleep -m 100 } while ( $ie.busy )
$result = ExecJavaScript $ie @'
return "JavaScript code ran successfully!";
'@
# Why $result.length is always 2 ?!!
$result.length
$result
谢谢 本质上,返回null与返回null是不同的。execScript方法返回null,它实际上是一个输出到管道的对象。我希望下面的片段能够解释您正在经历的行为
Function ReturnNull () {
0..1 | % { $null }
}
Function ReturnToNull() {
0..1 | % { $null | Out-Null }
}
# This will return 2.
(ReturnNull).length
# This will return 0 as it has been spit out to Null.
(ReturnToNull).length
添加
Out Null
cmdlet时,您的函数基本上是ReturnNull
,并更改为ReturnToNull
。此命令是否有可能:$window.execScript($jsCommand,'javascript')输出污染管道的返回?如果是,则将其重定向到$null:$window.execScript($jsCommand,'javascript')>$nullDocumentation,表示它总是返回null。尽管如此,我还是通过管道将其发送到了Out Null
,解决了这个问题!:)。。。尽管如此,我还是不明白。如果你在答题贴上解释一下,我会接受你的答案。谢谢。我真的没有什么解释。我刚刚意识到了这些症状,而这个命令是我看到的唯一一个可能的外来输出源。无论如何,谢谢。在你的帮助下,我的问题解决了。