【问题标题】:Powershell - Variables and foreach loopPowershell - 变量和 foreach 循环
【发布时间】:2016-12-15 00:37:48
【问题描述】:

This thread 让我起步很好,但现在我需要更多帮助

我正在尝试遍历我的 serverlist.txt 文件,并将 Get-EventLog 的结果传递给 Out-GridView,然后传递给 .csv 文件。我有这个工作,但我必须选择 GridView 窗口中的所有记录,然后为每个服务器单击“确定”。

所以,我想在循环外创建一个 $sys 变量,进入,将结果附加到每个服务器的该变量,然后退出循环并将 $sys 传递给 Grid-view。

我的困惑来自于代码中的变量声明、类型、附加和放置......

我现在刚学PS,所以这对你来说可能有点基础:)

此代码有效...需要在正确的位置添加变量idea:

#Drop the existing files
Remove-Item C:\system.csv

# SERVER LIST PROPERTIES
# Get computer list to check disk space. This is just a plain text file with the servers listed out.
$computers = Get-Content "C:\ServerList.txt"; 

#Declare $sys here ??

# QUERY COMPUTER SYSTEM EVENT LOG
foreach($computer in $computers)

{        
 if(Test-Connection $computer -Quiet -Count 1)
        {
   Try {
        # $sys = 
        Get-EventLog -ComputerName $computer -LogName System -EntryType "Error","Warning" -After (Get-Date).Adddays(-7) `
        | Select-Object -Property machineName, EntryType, EventID, Source, TimeGenerated, Message `
        | Out-GridView -PassThru | Export-Csv C:\System.csv -NoTypeInformation -Append;
       } 
   Catch 
       {
       Write-Verbose "Error $($error[0]) encountered when attempting to get events from  $computer"
       }
       } 
   else {
         Write-Verbose "Failed to connect to $computer"
        }


}
# $sys | Out-GridView....etc.

谢谢!

凯文3NF

【问题讨论】:

  • 在循环外添加$sys = @()(就像你想要的那样)
  • 并使用$sys += Get-EventLog向其中添加数据
  • 是否需要网格视图,还是只想将内容放入 csv 文件中?
  • 根本不使用任何格式化 cmdlet 并将数据输出到 CSV 文件。
  • @MikeGaruccio,您的回答给了我想要的最终结果。这个问题是关于变量的语法和位置的......我该如何正确地关闭它?你们都帮助了:)

标签: windows powershell variables out-gridview


【解决方案1】:

为了解决这个问题,我使用了多个 cmets 的建议:

$sys = @()(循环外)

$sys += Get-EventLog(在循环内)

$sys | Export-Csv(循环后发送到.csv)

我什至在博客上写了整件事,包括我经历的所有各种学习迭代: http://dallasdbas.com/getting-to-know-powershell-from-an-old-dba/

感谢所有帮助。这给了我一个框架,我将在需要时继续在这些服务器上使用。

凯文3NF

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 2011-12-09
    • 2022-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多