Search code examples
powershellpowershell-4.0

Powershell script not working right with "pause" in the end


I have a strange problem with my script, which runs on two different servers, on one server it's working perfectly and on the other one it's behave very strange.

Here is the code:

write-host "Cheking if App open please wait"

write-host "`n"

$open = Get-SmbOpenFile | 
          Where-Object {$_.Path -eq "d:\Shares\Share1\app.exe"} |
            Select-Object @{l="Who is using App?";e="ClientUserName"}, Path

if ($open) {
 write-host "Showing open files:"
  $open

}

else {
  write-host "all closed"
}

pause

On a server 2012 r2 with powershell version 3.0 it's working perfectly, and on the second server which is 2016 it's not working.

So I've started to investigate and I came to a conclusion that if I remove the "pause" in the end of the script on the 2016 server it's working perfectly, which is very strange..

With the "pause" in the end, I'am getting this result:

Showing open files:

Press Enter to continue...: 

Thanks a lot for your help :)


Solution

  • Format-table (implied) waits indefinitely for 2 objects.

    Hmm, format-table never comes out before the pause.

    [pscustomobject]@{name='joe'}; pause
    
    Press Enter to continue...:
    name
    ----
    joe
    

    With format-list, it comes out right away:

    [pscustomobject]@{name='joe'}|format-list; pause
    
    name : joe
    
    
    Press Enter to continue...: 
    

    This should work:

    write-host "Cheking if App open please wait"
    
    write-host "`n"
    
    $open = Get-SmbOpenFile | 
              Where-Object {$_.Path -eq "d:\Shares\Share1\app.exe"} |
                Select-Object @{l="Who is using App?";e="ClientUserName"}, Path
    
    if ($open) {
     write-host "Showing open files:"
      $open | format-list
    
    }
    
    else {
      write-host "all closed"
    }
    
    pause