Powershell change/edit 变量中对象的值

Powershell change/edit value of Object in Variable

我使用从 CSV 文件收集的数据在 ForEach 循环中创建变量,如下所示:

    New-Variable -Name $FlexVPN.'IP-adress' -Value (New-Object PSObject -Property @{
    IP = $FlexVPN.'IP-adress'
    Information = $FlexVPN.'Information'
    Priority = $FlexVPN.'Priority'
    RegisteredUp = $RegisteredUp
    RegisteredDown = $RegisteredDown
    ResponseTime = $Result = try{ Test-Connection -ComputerName $FlexVPN.'IP-adress' -Count $FlexVPN.'Priority' -ErrorAction Stop | Select ResponseTime} catch [System.Net.NetworkInformation.PingException] { $_.exception | PingFailed }})

然后我要做的是根据 ping 的响应更改 RegisteredUp 和 RegisteredDown 的值。

我不明白新会员的东西,我试过但没用。 现在我尝试了 Set-Variable 但我不知道如何只更改变量中的对象?

Set-Variable -Name $FlexVPN.'IP-adress' -Value (New-Object PSObject -Property @{RegisteredDown = "TESTING"})

我没有收到任何错误,它也没有工作。

进一步说明。 如果 ping 没有响应,则在 RegisteredDown 中为该变量设置 Get-Date。 如果在该变量的 RegisteredUp 中响应 ping ser Get-Date。

然后我使用 if/else 以某种方式在下一个版本中使用结果 ;)


编辑

# Clear variables after loop
Remove-Variable * -force -erroraction silentlycontinue

 
    function PingFailed { 
        
        # Add date and time when IP-address first didn't responded
            $FlexVPN.RegisteredDown = 'AnotherTest'

        # If only error should be printed
        if($PrintError -eq 'Yes'){Write-Host -ForegroundColor Red $FlexVPN.'IP-adress' "," $FlexVPN.'Information'}

##########################################################################
####################### NO CHANGES ABOVE THIS LINE #######################
##########################################################################

# Choose between printing output or not for all rows in CSV-file [Yes/No]
$PrintOutput = 'Yes'

# Choose between printing out error or not [Yes/No]
$PrintError = 'No'

##########################################################################
####################### NO CHANGES BELOW THIS LINE #######################
##########################################################################

# Import CSV-file to Powershell to use data in code
$FlexVPNlist = Import-Csv -Path $PSScriptRoot\PingIPEmail.csv -Header 'IP-adress', 'Information', 'Priority' -Delimiter ';' -Encoding UTF7

Foreach($FlexVPN in $FlexVPNlist) {

    New-Variable -Name $FlexVPN.'IP-adress' -Value (New-Object PSObject -Property @{
    IP = $FlexVPN.'IP-adress'
    Information = $FlexVPN.'Information'
    Priority = $FlexVPN.'Priority'
    RegisteredDown = 'Test'
    ResponseTime = $Result = try{ Test-Connection -ComputerName $FlexVPN.'IP-adress' -Count $FlexVPN.'Priority' -ErrorAction Stop | Select ResponseTime} catch [System.Net.NetworkInformation.PingException] { $_.exception | PingFailed }})

    if($PrintOutput -eq 'Yes'){
    if ($host.name -eq 'Windows PowerShell ISE Host') {if ($Result.ResponseTime -eq $null) { $Host.UI.RawUI.BackgroundColor = ($bckgrnd = 'Red') } else { $psISE.Options.RestoreDefaults() }}
    [PSCustomObject]@{
        "IP address" = $FlexVPN.'IP-adress'
        "Information" = $FlexVPN.'Information'
        "Priority" = $FlexVPN.'Priority'
        "Response time" = $Result.ResponseTime
        "RegisteredDown" = 'Test'
    }}
       
    }

}

我上面的第二次尝试工作正常,直到我在 ping 期间捕获异常并转到我的函数 PingFailed。 我想 运行 在 IP 地址没有响应时运行该功能,并在这些情况下将 Get-Date 添加到 RegisteredDown。

我收到的错误是:

At C:\Temp\Powershell scripts\PingIPEmail\PingIPEmail.ps1:49 char:13
+             $FlexVPN.RegisteredDown = 'AnotherTest'
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
   + FullyQualifiedErrorId : ExceptionWhenSetting`

尝试了其他代码

# Importing a csv
$FlexVPNList = Import-Csv -Path 'C:\Temp\Powershell scripts\PingIPEmail\PingIPEmail.csv' -Header 'IP-adress', 'Information', 'Priority' -Delimiter ';' -Encoding UTF7

Foreach($FlexVPN in $FlexVPNlist) {

$FlexVPN.GetType()                                # Object[]
$FlexVPN[0].GetType()                             # PSCustomObject
($FlexVPN[0] | gm -MemberType NoteProperty).Count # 3 Noteproperties

$FlexVPN | % {
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredUp' -NotePropertyValue 1 -Force
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredDown' -NotePropertyValue 1 -Force
}

($FlexVPN[0] | gm -MemberType NoteProperty).Count # 5 Noteproperties

 $Result = try{ Test-Connection -ComputerName $FlexVPN.'IP-adress' -Count $FlexVPN.'Priority' -ErrorAction Stop | Select ResponseTime} catch [System.Net.NetworkInformation.PingException] { $_ }

    if ($Result.ResponseTime -eq $null){
    if ($host.name -eq 'Windows PowerShell ISE Host') { $Host.UI.RawUI.BackgroundColor = ($bckgrnd = 'Red') }
    $FlexVPN.RegisteredDown = Get-Date
    [PSCustomObject]@{
        "IP address" = $FlexVPN.'IP-adress'
        "Information" = $FlexVPN.'Information'
        "Priority" = $FlexVPN.'Priority'
        "Response time" = $Result.ResponseTime
        "RegisteredUp" = $FlexVPN.RegisteredUp
        "RegisteredDown" = $FlexVPN.RegisteredDown
    }

    }

    if ($Result.ResponseTime -ge '0'){
    if ($host.name -eq 'Windows PowerShell ISE Host') { $psISE.Options.RestoreDefaults() }
    $FlexVPN.RegisteredUp = Get-Date
    [PSCustomObject]@{
        "IP address" = $FlexVPN.'IP-adress'
        "Information" = $FlexVPN.'Information'
        "Priority" = $FlexVPN.'Priority'
        "Response time" = $Result.ResponseTime
        "RegisteredUp" = $FlexVPN.RegisteredUp
        "RegisteredDown" = $FlexVPN.RegisteredDown
    }
    }

如果我理解正确,此代码会为我的 CSV 文件中的每一行重复使用相同的变量。 我想为每一行创建一个变量(将它们命名为 IP 地址),这样我就可以重用存储的值,只要脚本我 运行ning.

看起来你把事情复杂化了。您可以像这样创建一个新变量(对象)

$FlexVPN = [PSCustomObject] @{
    Information='Test'
}

显示信息的价值

$FlexVPN.Information 

更改信息的值

$FlexVPN.Information = 'AnotherTest'

显示信息的变化值

$FlexVPN.Information 

使用新变量的一个有效用例是,如果您动态 create/use 变量


编辑

你的意图对我来说并不是很清楚,但在测试平台之后可能会给你一些新的想法

# Mimick importing a csv
$FlexVPN = @'
IP-Adress,Information,Priority
1.1.1.1,FlexVPN,1
2.2.2.2,FlexVPN,2
'@ | ConvertFrom-Csv

$FlexVPN.GetType()                                # Object[]
$FlexVPN[0].GetType()                             # PSCustomObject
($FlexVPN[0] | gm -MemberType NoteProperty).Count # 3 Noteproperties

$FlexVPN | % {
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredUp' -NotePropertyValue 1 -Force
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredDown' -NotePropertyValue 1 -Force
}

($FlexVPN[0] | gm -MemberType NoteProperty).Count # 5 Noteproperties

通过这样做管理我想要的东西:

# Clear variables after loop
Remove-Variable * -force -erroraction silentlycontinue

# Importing a csv
$FlexVPNList = Import-Csv -Path 'C:\Temp\Powershell scripts\PingIPEmail\PingIPEmail.csv' -Header 'IP', 'Information', 'Priority' -Delimiter ';' -Encoding UTF7

$FlexVPNList | % {
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredUp' -NotePropertyValue '' -Force
    Add-Member -InputObject $_ -NotePropertyName 'RegisteredDown' -NotePropertyValue '' -Force
    Add-Member -InputObject $_ -NotePropertyName 'ResponseTime' -NotePropertyValue '' -Force
}

Foreach($FlexVPN in $FlexVPNlist) {

$Ping = try{ Test-Connection -ComputerName $FlexVPN.IP -Count $FlexVPN.'Priority' -ErrorAction Stop | Select ResponseTime } catch [System.Net.NetworkInformation.PingException] { $_ }

 if($Ping.ResponseTime -ge '0'){ 
    $FlexVPN.RegisteredUp = Get-Date 
    $FlexVPN.ResponseTime = $Ping.ResponseTime
    }
    if($Ping.ResponseTime -eq $null){ $FlexVPN.RegisteredDown = Get-Date }

    New-Variable -Name $FlexVPN.IP -Value (New-Object PSObject -Property @{
    IP = $FlexVPN.IP
    Information = $FlexVPN.Information
    Priority = $FlexVPN.Priority
    RegisteredUp = $FlexVPN.RegisteredUp
    RegisteredDown = $FlexVPN.RegisteredDown
    ResponseTime = $Ping.ResponseTime
})

    [PSCustomObject]@{
        "IP address" = $FlexVPN.IP
        "Information" = $FlexVPN.Information
        "Priority" = $FlexVPN.Priority
        "Response time" = $FlexVPN.ResponseTime
        "RegisteredUp" = $FlexVPN.RegisteredUp
        "RegisteredDown" = $FlexVPN.RegisteredDown
    }

}

我现在可以处理计算机是否响应的问题了!