Context 'PS Versioning' { It 'is current version' { $host.Version.Major -ge5-and$host.Version.Minor -ge1 | Should Be $true } } Context 'PS Settings' { It 'can execute scripts' { (Get-ExecutionPolicy) | Should Not Be 'Restricted' } It 'does not use AllSigned' { (Get-ExecutionPolicy) | Should Not Be 'AllSigned' } It 'does not have GPO restrictions' { (Get-ExecutionPolicy-Scope MachinePolicy) | Should Be 'Undefined' (Get-ExecutionPolicy-Scope UserPolicy) | Should Be 'Undefined' } } }
当您运行它时(当然,前提是已经安装了 Pester 模块),这是得到的输出结果:
1 2 3 4 5 6 7 8 9 10 11
Describing PowerShell Basic Check
Context PS Versioning [+] is current version 76ms
Context PS Settings [+] can execute scripts 47ms [+] does not use AllSigned 18ms [+] does not have GPO restrictions 21ms
然而,现在有越来越多的宿主。Visual Studio 可以作为 PowerShell 的宿主,Visual Studio Code 也可以。而且还有许多商业编辑器。所以您需要确定一个脚本是否在一个特定的环境中运行,请使用宿主标识符来代替:
1 2 3 4
$name = $host.Name $inISE = $name-eq'Windows PowerShell ISE Host'
"Running in ISE: $inISE"
Each host emits its own host name, so this approach can be adjusted to any host. When you run a script inside Visual Studio Code, for example, the host name is “Visual Studio Code Host”. 每个宿主会提供它的宿主名称,所以这种方法可以适用于任何宿主。例如当您在 Visual Studio Code 中运行一个脚本,宿主名会变为 “Visual Studio Code Host”。
# if you entered a valid user credentials, this line # will start Notepad using the credentials retrieved from # the JSON file to prove that the credentials are # working. Start-Process notepad -Credential$cred
# if you entered a valid user credentials, this line # will start Notepad using the credentials retrieved from # the JSON file to prove that the credentials are # working. Start-Process notepad -Credential$cred
#requires -Version 5.0 classTextToSpeech { # store the initialized synthesizer here hiddenstatic$synthesizer
# static constructor, gets called whenever the type is initialized static TextToSpeech() { Add-Type-AssemblyName System.Speech [TextToSpeech]::Synthesizer = New-Object System.Speech.Synthesis.SpeechSynthesizer }
#requires -Version 5.0 classTextToSpeech { # store the initialized synthesizer here hidden$synthesizer
# static constructor, gets called whenever the type is initialized TextToSpeech() { Add-Type-AssemblyName System.Speech $this.Synthesizer = New-Object System.Speech.Synthesis.SpeechSynthesizer }