OpsaC - Operating as PowerShell code
published: May 31, 2019 author: Tinu tags: PowerShell categories: PowerShell-Remoting
Running Pester Tests in an interactive session.
If you have the Pester-tests on the local comuter, you can start it from the ISE / VSCode:
$RemoteHost = Read-Host 'Enter the computer to connect'
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
Enter-PSSession -ComputerName $RemoteHost -Credential $creds
Import-Module Pester -MinimumVersion 4.4.1
Describe "Compliance Tests Windows Updates" -Tag 'All','PMGT' {
$LastBootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$LastHotfix = Get-HotFix | Select-Object -Last 1
it "[PMGT] Test is LastBootUpTime is within to 60 days" {
(New-TimeSpan -Start $LastBootTime -End $ActualTime).Days | should beLessThan 60
}
it "[PMGT] Test is LastInstalled Hotfix within to 45 days" {
$LastInstalled = Get-Date($LastHotfix.InstalledOn)
(New-TimeSpan -Start $LastInstalled -End $ActualTime).Days | should beLessThan 45
}
}
Exit-PSSession
If you have all the Pester-tests on the remote comuter, you can start Pester with Invoke-Pester:
$RemoteHost = Read-Host 'Enter the computer to connect'
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
Enter-PSSession -ComputerName $RemoteHost -Credential $creds
Import-Module Pester -MinimumVersion 4.4.1
Invoke-Pester "C:\Admin\Tests"
Exit-PSSession
Running Pester Tests in a persistend session.
$RemoteHost = Read-Host 'Enter the computer to connect'
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
$rsession = New-PSSession -ComputerName $RemoteHost -Credential $creds
if($rsession.State -eq 'Opened'){
# Remove items on the remote computer
Invoke-Command -Session $rsession -ScriptBlock {
if(Test-Path 'C:\Admin\Tests'){remove-item 'C:\Admin\Tests' -Recurse -Force}
}
# Copy some scripts to the remote computer
Copy-Item -ToSession $rsession -Path "$($PSScriptRoot)\Tests\" -Destination 'C:\Admin' -Force -Recurse
Write-Host "Copy $($PSScriptRoot)\Tests to $($rsession.ComputerName) C:\Admin"
# Run a Pester tests on the remote computer
$destination = "C:\Admin\Tests"
$pestertag = 'All'
$ScriptBlockContent = {
Param($destination,$pestertag)
Import-Module -Name Pester -MinimumVersion 4.4.1
Invoke-Pester $destination -Tag $pestertag -PassThru -Show None
}
$result = Invoke-Command -Session $rsession -ScriptBlock $ScriptBlockContent -ArgumentList $destination, $pestertag
# Remove items on the remote computer
Invoke-Command -Session $rsession -ScriptBlock {
if(Test-Path 'C:\Admin\Tests'){remove-item 'C:\Admin\Tests' -Recurse -Force}
}
Remove-PSSession -Session $rsession
}
The test framework for Powershell on github.com