Skip to content

Commit 6c22606

Browse files
SamErdeCopilot
andcommitted
🐛 fix(scripts): address PR 17 Copilot review comments
- Move PSSession creation into try/catch with terminating errors - Ensure PSSession cleanup runs from finally when remote execution fails - Use consistent PascalCase Result variable in Resolve-IPs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 2f86ff1 commit 6c22606

2 files changed

Lines changed: 12 additions & 10 deletions

File tree

DDI/Resolve-IPs.ps1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ foreach ($IP in $ListOfIPs) {
1818

1919
Write-Host "Resolving $IP" -ForegroundColor Green
2020
try {
21-
$result = [System.Net.Dns]::gethostentry($IP)
21+
$Result = [System.Net.Dns]::GetHostEntry($IP)
2222
} catch {
23-
$result = $null
23+
$Result = $null
2424
}
2525

2626
If ($Result) {

Snippets/RemoteServerSessionLoop2.ps1

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,26 @@ if ($session) { Remove-PSSession $session }
1515

1616
#Loop through each server in the list, open a PowerShell remoting session, then show the name and status of the session. Skip (continue) to the next server if a connection fails.
1717
foreach ($server in $servers) {
18-
$session = New-PSSession -ComputerName $server -Name $server -Credential $Creds
18+
$session = $null
1919

2020
Try {
2121
Write-Information "Connecting to $server... " -InformationAction Continue
22+
$session = New-PSSession -ComputerName $server -Name $server -Credential $Creds -ErrorAction Stop
2223
# Enter-PSSession is interactive-only; use Invoke-Command to run code in the remote session.
23-
Invoke-Command -Session $session -ScriptBlock {
24+
Invoke-Command -Session $session -ErrorAction Stop -ScriptBlock {
2425
<#
2526
Code to be run on each remote server goes here.
2627
#>
2728
Write-Information 'Inner code.' -InformationAction Continue
2829
}
2930
} Catch {
30-
Write-Warning "Failed to connect to $server. Skipping." -WarningAction Continue
31+
Write-Warning "Failed to create or use the PSSession for $server. Skipping." -WarningAction Continue
3132
Continue
33+
} Finally {
34+
if ($session) {
35+
# Cleanup and then show the current PSSession state.
36+
Remove-PSSession $session -ErrorAction SilentlyContinue
37+
Write-Information "$($session.ComputerName) $($session.State) `n`n" -InformationAction Continue
38+
}
3239
}
33-
Write-Output $session.State
34-
35-
#Cleanup and then show the current PSSession state.
36-
Remove-PSSession $session
37-
Write-Information "$($session.ComputerName) $($session.State) `n`n" -InformationAction Continue
3840
}

0 commit comments

Comments
 (0)