PowerShell-将布尔值返回到显式声明的变量时InvalidCastException
我已经编写了一个PowerShell脚本,为我部署到整个庄园的客户端计算机上的一系列修补程序执行一些预安装设置,我遇到了一个我无法理解的奇怪问题 由于powershell 2.0的“功能”,应用程序默认使用.NET Framework 2.0.0而不是4.5.2,因此安装程序修补程序会检查“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config”文件,从而阻止执行某些功能。如果该文件不存在或计算值与规范不匹配,我将添加XML文件并提供必要的值 我运行的命令如下所示:PowerShell-将布尔值返回到显式声明的变量时InvalidCastException,powershell,exception,Powershell,Exception,我已经编写了一个PowerShell脚本,为我部署到整个庄园的客户端计算机上的一系列修补程序执行一些预安装设置,我遇到了一个我无法理解的奇怪问题 由于powershell 2.0的“功能”,应用程序默认使用.NET Framework 2.0.0而不是4.5.2,因此安装程序修补程序会检查“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config”文件,从而阻止执行某些功能。如果该文件不存在或计算值与规范不匹配,我将添加XM
$psConfigDir = "C:\Windows\System32\WindowsPowerShell\v1.0"
$psConfigFileName = "powershell.exe.config"
[boolean]$psExeXml = Set-PSRuntimeConfigs -FilePath ( [String]::Format("{0}\{1}", $psConfigDir, $psConfigFileName) ) -CLRVersions @("v4.0.30319", "v2.0.50727")
…在我使用以下代码创建的PowerShell模块中可以找到Set PSRuntimeConfigs
方法:
Function Set-PSRuntimeConfigs {
[CmdletBinding()]
Param(
[String]$FilePath,
[System.Collections.ArrayList]$CLRVersions
)
Try {
$xmlWriter = New-Object System.Xml.XmlTextWriter($FilePath, $null)
$xmlWriter.Formatting = "Indented"
$xmlWriter.Indentation = 4
$xmlWriter.WriteStartDocument()
$xmlWriter.WriteStartElement("configuration")
$xmlWriter.WriteStartElement("startup")
$xmlWriter.WriteAttributeString("useLegacyV2RuntimeActivationPolicy", $true)
$CLRVersions | ForEach-Object {
$xmlWriter.WriteStartElement("supportedRuntime")
$xmlWriter.WriteAttributeString("version", $_)
$xmlWriter.WriteEndElement()
}
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndDocument()
$xmlWriter.Close()
$xmlWriter.Dispose()
return $true
} Catch {
echo "ERROR: Exception occurred during XML write process!"
echo "ERROR: Exception message: $($_.Exception.Message)"
return $false
}
}
但是,当尝试将函数结果分配给$psexexexxml
变量时,函数返回InvalidCastException。奇怪的是,PowerShell返回时出现一个错误,指出[System.Object()]无法转换为[Boolean]类型,尽管函数只返回$true
或$false
我的第一个想法是,由于代码问题,函数抛出了一个异常,但编写该函数是为了在提示符中报告错误,在这种情况下只返回
$false
。。。不管怎样,我被卡住了,不知道该从哪里开始…如果函数产生任何输出,那么结果将是一个包含输出字符串的数组,然后最后一个元素将是您的布尔值
因此,对于此代码:
echo "ERROR: Exception occurred during XML write process!"
echo "ERROR: Exception message: $($_.Exception.Message)"
return $false
该函数返回一个由两个字符串和一个布尔值组成的数组。Hi@Duncan,因此“echo”(又称写主机)只是回写到PowerShell控制台,但仍然作为对象返回?您的错误是
echo
是写输出的别名,而不是写主机的别名。您可以使用Write Host
写入控制台,但Write Output
会从函数中生成一个输出,该输出可能最终会进入控制台,也可能不会进入控制台。感谢Duncan,我将把命令改为Write Host
)