【问题标题】:how to loop my powershell script?如何循环我的powershell脚本?
【发布时间】:2014-11-10 06:53:53
【问题描述】:

我有一个小脚本可以过滤掉远程 PC 在过去 7 天内的应用程序和系统的错误日志。

Write-Host "Creating Error Log of Remote PC ......."
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"
$date = get-date
$range = $date.adddays(-7)
$pcname = Read-Host -Prompt "Please Enter PC name"

Get-WinEvent -ComputerName $pcname -FilterHashtable @{LogName="system","application"; Level=1,2; starttime=$range} | 
Select-Object @{label="PC"; expression={"$pcname"}},LogName,levelDisplayName,ProviderName,ID,TimeCreated,message | 
Sort-Object logname | 
Format-Table -AutoSize | 
Out-File C:\Eventlog.txt -width 214748

C:\Eventlog.txt

运行时会提示输入PC名称,问题是脚本执行完毕后,powershell提示符会返回

PS c:\windows\system32\windowspowershell\v1.0>

如果我想检查另一台 PC 上的日志,我必须关闭当前的 PS 窗口并再次运行我的脚本。

第一次运行完成后,如何循环显示我的 [Enter PC name] 提示?

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0


    【解决方案1】:

    您可以将现有代码包含在 while 循环中:

    while($true){
       Write-Host "Creating Error Log of Remote PC ......."
       ...
       # rest of the code
       ...
       C:\Eventlog.txt
    }
    

    这将无限重复您的代码,或者直到您按下ctrl+c

    【讨论】:

      【解决方案2】:

      包含在do..while 循环中:

      $pcname = Read-Host "Enter PC Name"
      
      do {
          Write-Host "Creating Error Log of Remote PC ......."
          [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"
          $date = get-date
          $range = $date.adddays(-7)
          $pcname = Read-Host -Prompt "Please Enter PC name"
      
          Get-WinEvent -ComputerName $pcname -FilterHashtable @{LogName="system","application"; Level=1,2; starttime=$range} | 
          Select-Object @{label="PC"; expression={"$pcname"}},LogName,levelDisplayName,ProviderName,ID,TimeCreated,message | 
          Sort-Object logname | 
          Format-Table -AutoSize | 
          Out-File C:\Eventlog.txt -width 214748
      
          C:\Eventlog.txt
          $pcname = Read-Host "Enter PC Name" 
      
      } while($pcname -match '.+')
      

      while 条件检查是否输入了某些内容,因此输入一个空白字符串(只需在输入时按 Enter)将退出脚本

      【讨论】:

        【解决方案3】:

        另一种方法

        # do your stuff
        
        read-host 'press a key to continue'
        $file=$myInvocation |select -expand invocationName
        start-process -noNewWindow "powershell.exe" "-file $file"
        

        请注意,我不建议使用它,因为它会启动一个新进程并在每次迭代时消耗资源。

        IMO 更好的方法是创建一个simple menu 来询问用户是否想再次运行该功能。

        【讨论】:

        • 这是一个新想法。会试试的。
        猜你喜欢
        • 2021-11-22
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 2022-10-17
        • 1970-01-01
        相关资源
        最近更新 更多