Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
Start-Transcript.Tests.ps1325 linesDownload Raw Back to Microsoft.Powershell.Host
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" {4 5    BeforeAll {6 7        function ValidateTranscription {8            param (9                [string] $scriptToExecute,10                [string] $outputFilePath,11                [switch] $append,12                [switch] $noClobber,13                [string] $expectedError14            )15            if($append -or $noClobber) {16                #Add sample text to the file17                $content = "This is sample text!"18                $content | Out-File -FilePath $outputFilePath19                Test-Path $outputFilePath | Should -BeTrue20            }21 22            try {23                #execute script24                $ps = [powershell]::Create()25                $ps.addscript($scriptToExecute).Invoke()26                $ps.commands.clear()27 28                if($expectedError) {29                    $ps.hadErrors | Should -BeTrue30                    $ps.Streams.Error.FullyQualifiedErrorId | Should -Be $expectedError31                } else {32                    $ps.addscript("Get-Date").Invoke()33                    $ps.commands.clear()34                    $ps.addscript("Stop-Transcript").Invoke()35 36                    Test-Path $outputFilePath | Should -BeTrue37                    $outputFilePath | Should -FileContentMatch "Get-Date"38                    if($append) {39                        $outputFilePath | Should -FileContentMatch $content40                    }41                }42            } finally {43                if ($null -ne $ps) {44                    $ps.Dispose()45                }46            }47        }48        ## function ends here49 50        $transcriptFilePath = Join-Path $TestDrive "transcriptdata.txt"51        Remove-Item $transcriptFilePath -Force -ErrorAction SilentlyContinue52    }53 54    AfterEach {55        Remove-Item $transcriptFilePath -ErrorAction SilentlyContinue56        [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForcePromptForChoiceDefaultOption', $false)57    }58 59    It "Should create Transcript file at default path" {60        $script = "Start-Transcript"61        if ($IsWindows) {62            $defaultTranscriptFilePath = [io.path]::Combine($env:USERPROFILE, "Documents", "PowerShell_transcript*")63        } else {64            $defaultTranscriptFilePath = [io.path]::Combine($env:HOME, "PowerShell_transcript*")65        }66 67        try {68            #Make sure there is no stale data69            Remove-Item $defaultTranscriptFilePath -Force -ErrorAction SilentlyContinue70            ValidateTranscription -scriptToExecute $script -outputFilePath $defaultTranscriptFilePath71        } finally {72            #Remove test data73            Remove-Item $defaultTranscriptFilePath -ErrorAction SilentlyContinue74        }75    }76    It "Should create Transcript file with 'Path' parameter" {77        $script = "Start-Transcript -path $transcriptFilePath"78        ValidateTranscription -scriptToExecute $script -outputFilePath $transcriptFilePath79    }80    It "Should create Transcript file with 'LiteralPath' parameter" {81        $script = "Start-Transcript -LiteralPath $transcriptFilePath"82        ValidateTranscription -scriptToExecute $script -outputFilePath $transcriptFilePath83    }84    It "Should create Transcript file with 'OutputDirectory' parameter" {85        $script = "Start-Transcript -OutputDirectory $TestDrive"86        $outputFilePath = Join-Path $TestDrive "PowerShell_transcript*"87        ValidateTranscription -scriptToExecute $script -outputFilePath $outputFilePath88    }89    It "Should create Transcript file with 'Transcript' preference variable" {90        # Casting to PSObject is necessary because Set-Variable does not automatically wrap the value in a PSObject91        $script = "Set-Variable -Scope Global -Name Transcript -Value ([PSObject]'$transcriptFilePath'); Start-Transcript"92        ValidateTranscription -scriptToExecute $script -outputFilePath $transcriptFilePath93    }94    It "Should Append Transcript data in existing file if 'Append' parameter is used with Path parameter" {95        $script = "Start-Transcript -path $transcriptFilePath -Append"96        ValidateTranscription -scriptToExecute $script -outputFilePath $transcriptFilePath -append97    }98    It "Should return an error if the file exists and NoClobber is used" {99        $script = "Start-Transcript -path $transcriptFilePath -NoClobber"100        $expectedError = "NoClobber,Microsoft.PowerShell.Commands.StartTranscriptCommand"101        ValidateTranscription -scriptToExecute $script -outputFilePath $transcriptFilePath -noClobber -expectedError $expectedError102    }103    It "Should return an error if the path resolves to an existing directory" {104        $script = "Start-Transcript -path $TestDrive"105        $expectedError = "CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand"106        ValidateTranscription -scriptToExecute $script -outputFilePath $null -expectedError $expectedError107    }108    It "Should return an error if file path is invalid" {109        $fileName = (Get-Random).ToString()110        $inputPath = Join-Path $TestDrive $fileName111        $null = New-Item -Path $inputPath -ItemType File -Force -ErrorAction SilentlyContinue112        $script = "Start-Transcript -OutputDirectory $inputPath"113        $expectedError = "CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand"114        ValidateTranscription -scriptToExecute $script -outputFilePath $null -expectedError $expectedError115    }116    It "Should not delete the file if it already exist" {117        # Create an existing file118        $transcriptFilePath = Join-Path $TestDrive ([System.IO.Path]::GetRandomFileName())119        Out-File $transcriptFilePath120 121        $FileSystemWatcher = [System.IO.FileSystemWatcher]::new((Split-Path -Parent $transcriptFilePath), (Split-Path -Leaf $transcriptFilePath))122 123        $Job = Register-ObjectEvent -InputObject $FileSystemWatcher -EventName "Deleted" -SourceIdentifier "FileDeleted" -Action {124            return "FileDeleted"125        }126 127        try {128            Start-Transcript -Path $transcriptFilePath129            Stop-Transcript130        } finally {131            Unregister-Event -SourceIdentifier "FileDeleted"132        }133 134        # Nothing should have been returned by the FileSystemWatcher135        Receive-Job $job | Should -Be $null136    }137    It "Transcription should remain active if other runspace in the host get closed" {138        try {139            $ps = [powershell]::Create()140            $ps.addscript("Start-Transcript -path $transcriptFilePath").Invoke()141            $ps.addscript('$rs = [system.management.automation.runspaces.runspacefactory]::CreateRunspace()').Invoke()142            $ps.addscript('$rs.open()').Invoke()143            $ps.addscript('$rs.Dispose()').Invoke()144            $ps.addscript('Write-Host "After Dispose"').Invoke()145            $ps.addscript("Stop-Transcript").Invoke()146        } finally {147            if ($null -ne $ps) {148                $ps.Dispose()149            }150        }151 152        $transcriptFilePath | Should -Exist153        $transcriptFilePath | Should -FileContentMatch "After Dispose"154    }155 156    It "Transcription should be closed if the only runspace gets closed" {157        & "$PSHOME/pwsh" -c "start-transcript $transcriptFilePath; Write-Host ''Before Dispose'';"158 159        $transcriptFilePath | Should -Exist160        $transcriptFilePath | Should -FileContentMatch "Before Dispose"161        $transcriptFilePath | Should -FileContentMatch "PowerShell transcript end"162    }163 164    It "Transcription should record native command output" {165        $script = {166            Start-Transcript -Path $transcriptFilePath167            hostname168            Stop-Transcript169        }170 171        & $script172 173        $transcriptFilePath | Should -Exist174        $machineName = [System.Environment]::MachineName175        $transcriptFilePath | Should -FileContentMatch $machineName176    }177 178    It "Transcription should record Write-Information output when InformationAction is set to Continue" {179        [String]$message = New-Guid180        $script = {181            Start-Transcript -Path $transcriptFilePath182            Write-Information -Message $message -InformationAction Continue183            Stop-Transcript184        }185 186        & $script187 188        $transcriptFilePath | Should -Exist189        $transcriptFilePath | Should -Not -FileContentMatch "INFO: "190        $transcriptFilePath | Should -FileContentMatch $message191    }192 193    It "Transcription should not record Write-Information output when InformationAction is set to SilentlyContinue" {194        [String]$message = New-Guid195        $traceData = Join-Path $TESTDRIVE tracedata.txt196        $script = {197            Start-Transcript -Path $transcriptFilePath198            Trace-Command -File $traceData -Name param* { Write-Information -Message $message -InformationAction SilentlyContinue }199            Stop-Transcript200        }201 202        & $script203 204        $transcriptFilePath | Should -Exist205        $transcriptFilePath | Should -Not -FileContentMatch "INFO: "206        $transcriptFilePath | Should -Not -FileContentMatch $message -Because (get-content $transcriptFilePath,$traceData)207    }208 209    It "Transcription should not record Write-Information output when InformationAction is set to Ignore" {210        [String]$message = New-Guid211        $script = {212            Start-Transcript -Path $transcriptFilePath213            Write-Information -Message $message -InformationAction Ignore214            Stop-Transcript215        }216 217        & $script218 219        $transcriptFilePath | Should -Exist220        $transcriptFilePath | Should -Not -FileContentMatch "INFO: "221        $transcriptFilePath | Should -Not -FileContentMatch $message222    }223 224    It "Transcription should record Write-Information output in correct order when InformationAction is set to Inquire" {225        [String]$message = New-Guid226        $newLine = [System.Environment]::NewLine227        $expectedContent = "$message$($newLine)Confirm$($newLine)Continue with this operation?"228        $script = {229            [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForcePromptForChoiceDefaultOption', $true)230            Start-Transcript -Path $transcriptFilePath231            Write-Information -Message $message -InformationAction Inquire232            Stop-Transcript233        }234 235        & $script236 237        $transcriptFilePath | Should -Exist238        $transcriptFilePath | Should -Not -FileContentMatch "INFO: "239        $transcriptFilePath | Should -FileContentMatchMultiline $expectedContent240    }241 242    It "Transcription should record Write-Host output when InformationAction is set to Continue" {243        [String]$message = New-Guid244        $script = {245            Start-Transcript -Path $transcriptFilePath246            Write-Host -Message $message -InformationAction Continue247            Stop-Transcript248        }249 250        & $script251 252        $transcriptFilePath | Should -Exist253        $transcriptFilePath | Should -FileContentMatch $message254    }255 256    It "Transcription should record Write-Host output when InformationAction is set to SilentlyContinue" {257        [String]$message = New-Guid258        $script = {259            Start-Transcript -Path $transcriptFilePath260            Write-Host -Message $message -InformationAction SilentlyContinue261            Stop-Transcript262        }263 264        & $script265 266        $transcriptFilePath | Should -Exist267        $transcriptFilePath | Should -FileContentMatch $message268    }269 270    It "Transcription should not record Write-Host output when InformationAction is set to Ignore" {271        [String]$message = New-Guid272        $script = {273            Start-Transcript -Path $transcriptFilePath274            Write-Host -Message $message -InformationAction Ignore275            Stop-Transcript276        }277 278        & $script279 280        $transcriptFilePath | Should -Exist281        $transcriptFilePath | Should -Not -FileContentMatch $message282    }283 284    It "Transcription should record Write-Host output in correct order when InformationAction is set to Inquire" {285        [String]$message = New-Guid286        $newLine = [System.Environment]::NewLine287        $expectedContent = "$message$($newLine)Confirm$($newLine)Continue with this operation?"288        $script = {289            [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForcePromptForChoiceDefaultOption', $true)290            Start-Transcript -Path $transcriptFilePath291            Write-Host -Message $message -InformationAction Inquire292            Stop-Transcript293        }294 295        & $script296 297        $transcriptFilePath | Should -Exist298        $transcriptFilePath | Should -FileContentMatchMultiline $expectedContent299    }300 301    It "UseMinimalHeader should reduce length of transcript header" {302        $script = {303            Start-Transcript -Path $transcriptFilePath304            Stop-Transcript305        }306 307        $transcriptMinHeaderFilePath = $transcriptFilePath + "_minimal"308        $scriptMinHeader = {309            Start-Transcript -Path $transcriptMinHeaderFilePath -UseMinimalHeader310            Stop-Transcript311        }312 313        & $script314        $transcriptFilePath | Should -Exist315        $transcriptLength = (Get-Content -Path $transcriptFilePath -Raw).Length316 317        & $scriptMinHeader318        $transcriptMinHeaderFilePath | Should -Exist319        $transcriptMinHeaderLength = (Get-Content -Path $transcriptMinHeaderFilePath -Raw).Length320        Remove-Item $transcriptMinHeaderFilePath -ErrorAction SilentlyContinue321 322        $transcriptMinHeaderLength | Should -BeLessThan $transcriptLength323    }324}325