gpt4 book ai didi

arrays - 扩展哈希表中的属性

转载 作者:行者123 更新时间:2023-12-02 11:34:22 25 4
gpt4 key购买 nike

我的脚本遇到了一个简单的问题,我想在远程服务器上运行 GCI,问题是,该值与另一个哈希表属性组合在一起,因此 GCI 失败。

该脚本从两列 .csv 中读取条目,标题为“服务器”和“平台”

这是我得到的:

$ShortDate = (Get-Date).ToString('MM/dd/yyyy')
$CheckServer = @{}
$serverObjects = @() # create a list of server objects

Import-Csv $Dir\Servers.csv | ForEach {
$CheckServer.Server = $_.Server
$CheckServer.Platform = $_.Platform

if (GCI \\$_.Server\c$\log\Completed_Summary_*.html -EA 0 | where {$.LastWriteTime -ge "$ShortDate"}) {
Write-Host "FOUND"
} # end of IF GCI
} # end of For-Each

$serverObjects += New-Object -TypeName PSObject -Property $CheckServer

问题是 $_.Server 的条目应该是 SERVER1、SERVER2、SERVER3 等,即servers.csv 中的所有条目,而不是 $ 的值_.Server$_.Platform 组合在一起。如:

Write-Host "Checking" \\@{Server=SERVER1; Platform=PLATFORM_1}.Server\c$\log\Completed_Summary_*.html

它应该显示如下:

Write-Host "Checking" \\SERVER1\log\Completed_Summary_*.html

如何取消组合它们以便 GCI 命令起作用?

最佳答案

PowerShell 仅在字符串内进行简单的变量扩展。对于更复杂的表达式(例如索引操作或访问对象属性/方法),它将插入数组或对象变量的字符串化值,并保持其余操作不变。

演示:

PS C:\> $array = 23, 42PS C:\> Write-Host "some $array[1] or other"some 23 42[1] or otherPS C:\> $object = New-Object -Type PSObject -Property @{Foo=23; Bar=42}PS C:\> Write-Host "some $object.Foo or other"some @{Bar=42; Foo=23}.Foo or other

To avoid this you need to either:

  • assign the resulting value to a variable first and use that variable in the string:

    $value = $array[5]
    Write-Host "some $value or other"

    $value = $object.Foo
    Write-Host "some $value or other"
  • 使用subexpression ($(...)):

    Write-Host "some $($array[5]) or other"
    Write-Host "some $($object.Foo) or other"
  • 使用format operator (-f):

    Write-Host "some {0} or other" -f $array[5]
    Write-Host "some {0} or other" -f $object.Foo

关于arrays - 扩展哈希表中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com