我遇到一个简单的脚本问题,我想对远程服务器运行GCI,问题是,该值与另一个哈希表属性结合,因此GCI失败。
该脚本从两列.csv中读取条目,标题为“server”和“platform”
这就是我所拥有的:
$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
和{{1}的值结合起来。如:
$_.Platform
它应显示如下:
Write-Host "Checking" \\@{Server=SERVER1; Platform=PLATFORM_1}.Server\c$\log\Completed_Summary_*.html
如何取消组合它们以便GCI命令有效?
答案 0 :(得分:5)
PowerShell只在字符串中进行简单的变量扩展。对于更复杂的表达式,如索引操作或访问对象属性/方法,它将插入数组或对象变量的字符串化值,并保持操作的其余部分不受影响。
演示:
PS C:\> $array = 23, 42 PS C:\> Write-Host "some $array[1] or other" some 23 42[1] or other PS 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
要避免这种情况,您需要:
首先将结果值分配给变量,然后在字符串中使用该变量:
$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
答案 1 :(得分:0)
像它一样修改
$ShortDate = Get-Date -Hour 0 -Minute 0 -Second 0
$CheckServer = @{}
$serverObjects = @() # create a list of server objects
$Dir="C:\temp"
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"
}
}