【发布时间】:2020-03-28 09:55:12
【问题描述】:
我想设置一个强类型环境变量,当我使用 $env 时它似乎“丢失”了它的类型:
在原来的函数中它工作正常:
function Create-ThisCrap(){
[Microsoft.ApplicationInsights.TelemetryClient] $mytest = New-Object -TypeName Microsoft.ApplicationInsights.TelemetryClient
$mytest.InstrumentationKey = "213-123"
$mytest.TrackTrace("something")
}
但这已经不是了:
function Create-ThisCrap(){
[Microsoft.ApplicationInsights.TelemetryClient] $env:mytest = New-Object -TypeName Microsoft.ApplicationInsights.TelemetryClient
$env:mytest.InstrumentationKey = "213-123"
$env:mytest.TrackTrace("something")
}
有错误:
在此对象上找不到属性“InstrumentationKey”。
方法调用失败,因为 [System.String] 不包含名为“TrackTrace”的方法。
我试着作弊了一点:
function Create-ThisCrap(){
[Microsoft.ApplicationInsights.TelemetryClient] $mytest = New-Object -TypeName Microsoft.ApplicationInsights.TelemetryClient
$mytest.InstrumentationKey = "213-123"
$mytest.TrackTrace("something")
return $mytest
}
function FROMAnotherScript(){
[Microsoft.ApplicationInsights.TelemetryClient] $env:HopeItWorks = Create-ThisCrap
$env:HopeItWorks.TrackTrace('whatever')
}
但它产生了相同的效果。
我大致了解 Powershell 传递类的问题(显然还不够),但我认为只要它在一个函数内它应该可以工作并且 $env 问题难倒我。
【问题讨论】:
-
我怀疑我误解了你……但环境变量是严格的字符串。您不能对此类强制任何类型的类型,因为它被存储为一个简单的字符集合。