Root Loop
Root Loop

Reputation: 3162

how to loop my powershell script?

I have a little script to filter out error log for application and system for remote PC in past 7 days.

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

When it runs,I will get a prompt to enter PC name, The thing is that when the script finished, powershell prompt will return to

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

If i want to check the logs on another PC i have to close the current PS window and run my script again.

How can I do a loop that it will show my [Enter PC name] prompt again after the first run finished?

Upvotes: 0

Views: 28795

Answers (3)

Loïc MICHEL
Loïc MICHEL

Reputation: 26130

an altenative way

# do your stuff

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

Note that I would not recommand to use this as it will lauch a new process ans consume resource on each iteration.

IMO a better way would be to create a simple menu to ask the user if it wants to run the function another time.

Upvotes: 0

arco444
arco444

Reputation: 22821

Enclose in a do..while loop:

$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 '.+')

The while condition checks something was entered, therefore entering a blank string (just pressing Enter at input) will exit the script

Upvotes: 1

Raf
Raf

Reputation: 10097

You could enclose existing code in a while loop:

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

This will repeat your code ad infinitum or until you press ctrl+c.

Upvotes: 5

Related Questions