Hi Folks,
I’ve stuck on a section of a script I am creating.
Here is a simplified version of the problem I am hitting. I wish to run the command for a duration of a minute with a 10 second interval between each iteration.
$timeout = New-TimeSpan -Minutes 1 $stopwatch = [diagnostics.stopwatch]::StartNew() While ($stopwatch.elapsed -lt $timeout) {Get-ChildItem | ForEach-Object { [PSCustomObject] @{ 'Name'= $_.Name 'Timestamp'= (get-date).ToLongTimeString() 'Type'= $_.Attributes } } Start-Sleep -Seconds 10 }
The issue I have is there is a 10 second sleep anything is returned. Then I get the output from two iterations at once.
Name Timestamp Type ---- --------- ---- DNS Lookup 11:18:16 Directory iplookup.ps1 11:18:16 Archive networkcommands.txt 11:18:16 Archive pingAllDCs.ps1 11:18:16 Archive wifiChannel.ps1 11:18:16 Archive DNS Lookup 11:18:26 Directory iplookup.ps1 11:18:26 Archive networkcommands.txt 11:18:26 Archive pingAllDCs.ps1 11:18:26 Archive
I’d like the first iteration to output straightaway. I tried a Do . . While loop but that behaved the same.
I next tried changing the flow by putting the execution code in a function. This did not work.
Function TestCode{ Get-ChildItem | ForEach-Object { [PSCustomObject] @{ 'Name'= $_.Name 'Timestamp'= (get-date).ToLongTimeString() 'Type'= $_.Attributes } } } $timeout = New-TimeSpan -Minutes 1 $stopwatch = [diagnostics.stopwatch]::StartNew() testcode While ($stopwatch.elapsed -lt $timeout) { Start-Sleep -Seconds 10 testcode }
Moving Start-Sleep -Seconds 10 outside the While loops above is no use either as it’s ignored and the loop continiously cycles
Thanks,
Michael