1

I am trying to dump a lot of data into a file but if it takes too long I want to come out of the dump. Is there a way to do this in PowerShell? I tried the below but noticed that the logic is incorrect and will not do what I need.

$time = get-date
do
{
    dir c:\ -Recurse | Set-Content .\outtext.txt
}
while ((Get-Date).AddSeconds(5) -le $time)
trungduc
  • 11,926
  • 4
  • 31
  • 55

1 Answers1

2

Using this example, it'll stop the job after a minute if it hasn't completed:

$Now = Get-Date

Start-Job -Name 'C' -ScriptBlock {
  Get-ChildItem -Path 'C:\' -Recurse | Set-Content -Path '.\outtext.txt' } 

Try
{
    Do
    {
        If ((Get-Date).AddMinutes(-1) -gt $Now)
        {
            Stop-Job -Name 'C'
            Throw 'an error'
        }
    } While ((Get-Job -Name 'C').State -eq 'Running')

    $Output = Receive-Job -Name 'C'
}
Catch
{
    $_
}
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63