Ken*_*nny 2 csv arrays powershell hashtable
我遇到一个简单的脚本问题,我想在远程服务器上运行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
Run Code Online (Sandbox Code Playgroud)
问题是,条目$_.Server应该是SERVER1,SERVER2,SERVER3等,来自servers.csv中的所有条目,而不是两者的值$_.Server和$_.Platform组合.如:
Write-Host "Checking" \\@{Server=SERVER1; Platform=PLATFORM_1}.Server\c$\log\Completed_Summary_*.html
Run Code Online (Sandbox Code Playgroud)
它应该显示如下:
Write-Host "Checking" \\SERVER1\log\Completed_Summary_*.html
Run Code Online (Sandbox Code Playgroud)
如何取消组合它们以便GCI命令有效?
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"
Run Code Online (Sandbox Code Playgroud)使用子表达式($(...)):
Write-Host "some $($array[5]) or other"
Write-Host "some $($object.Foo) or other"
Run Code Online (Sandbox Code Playgroud)使用格式operator(-f):
Write-Host "some {0} or other" -f $array[5]
Write-Host "some {0} or other" -f $object.Foo
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |