繁体   English   中英

Powershell通过ForEach循环(或嵌套的Foreach)中的数组前进

[英]Powershell advance through an array in a ForEach loop (or nested Foreach)

伙计们,

我找到了一些答案,但它们似乎是用于手动数组,或者当你知道确定的数字时。 我将有一个阵列,我不知道会有多少人在那里。 想知道我是否能得到帮助。

基本上 - 我希望它通过每个服务器,获取OCX和DLL名称,版本和日期,并将其放在电子表格中。

它似乎工作得很好......只有一次。 它不会继续我的数组中的下一个文件。

我是如此接近,有人可以帮我告诉它(好吧,在你完成所有文件之前不要前进到下一个服务器)

到目前为止,这是我的代码。 效果很好 - 但每台服务器只能使用一个文件。

提前谢谢了。

$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"

$sheet.Cells.item(1,1)=("Server")
$sheet.Cells.item(1,2)=("File Name")
$sheet.Cells.Item(1,3)=("File Version")
$sheet.Cells.Item(1,4)=("Date")
$sheet.Range("A1:D1").interior.colorindex = 43  
$x=2


$i = 0

foreach ($Server in $Servers) {


    $infos = Invoke-Command -computername $Server {Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    $info = $infos[$i]



$sheet.Cells.item($x, 1)=($Server)
$sheet.Cells.item($x, 2)=($info.name)
$sheet.Cells.item($x, 3)=($info.FileVersion)
$sheet.Cells.item($x, 4)=($info.Date)
$x++
$i++
}

#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()

它似乎永远不会通过$ info [$ i]数组前进。

只是嵌套另一个foreach:

$x = 2
foreach ($Server in $Servers) {
    $infos = Invoke-Command -computername $Server { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object  name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    foreach ($info in $infos) {
        $sheet.Cells.item($x, 1)=($Server)
        $sheet.Cells.item($x, 2)=($info.name)
        $sheet.Cells.item($x, 3)=($info.FileVersion)
        $sheet.Cells.item($x, 4)=($info.Date)
        $x++
    }
}

我还建议将$x重命名$x更具描述性的内容,例如$Row

我建议的是立即获取所有信息,按服务器排序,选择所需内容,将其转换为制表符分隔的csv,将其复制到剪贴板,然后将其粘贴到电子表格中。

$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"
$infos = Invoke-Command -ComputerName $Servers -ScriptBlock { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx }
$infos | 
    Sort PSComputerName | 
    Select-Object  @{l='Name';e={$_.PSComputerName}},@{l='File Name';e={$_.Name}},@{label="File Version";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}} |
    ConvertTo-CSV -Del "`t" |
    | Clip
$sheet.cells.item(1,1).PasteSpecial() | Out-Null

$sheet.Range("A1:D1").interior.colorindex = 43 
#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM