【问题标题】:Powershell strongly typed environment variablePowershell 强类型环境变量
【发布时间】: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 问题难倒我。

【问题讨论】:

  • 我怀疑我误解了你……但环境变量是严格的字符串。您不能对此类强制任何类型的类型,因为它被存储为一个简单的字符集合。

标签: powershell strong-typing


【解决方案1】:

环境变量只能是字符串。如果需要存储多个值,可以使用多个环境变量,但数据类型始终为字符串。环境变量来自 MS-DOS,这意味着它们来自 1980 年代,旨在与批处理文件和 DOS 命令一起使用。它们是一个非常古老的遗留组件。

此外,通过$env: 命名空间设置环境变量不会为其他进程永久设置环境变量。您可以通过调用[System.Environment]::SetEnvironmentVariable() 来做到这一点,但即便如此,设置环境变量也只会为设置值后创建的进程设置值。它不会刷新其他已经运行的线程。

你不能将一个对象从一个进程完整地传递到另一个进程。您需要以某种方式对其进行序列化,然后在另一侧对其进行反序列化。通常这是通过将您的设置存储在数据文件、数据库或注册表中来完成的。您可以尝试 Export-ClixmlImport-Clixml,它们为 PowerShell 提供了基本的数据类型感知对象序列化,但我真的不知道您要做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多