Skip to content

Commit 1241307

Browse files
SamErdeCopilot
andauthored
🐛 fix(scripts): third audit pass — string interpolation, obsolete API, and scope bugs (#17)
* 🐛 fix(scripts): correct string interpolation, obsolete API, and ErrorActionPreference scope bugs - Snippets\RemoteServerSessionLoop2.ps1: replace Enter-PSSession (interactive-only) with Invoke-Command -Session; fix string interpolation for \.ComputerName and \.State using \ subexpression syntax - DDI\DNS Reverse Lookup from CSV.ps1: replace obsolete GetHostbyAddress() with GetHostEntry() - Windows\Disable-Poshv2.ps1: fix \.Count not expanding in double-quoted string - AD Users\Set User EmailAddress from PrimaryAddress.ps1: fix \.Name not expanding in Write-Progress -Status string - DDI\Resolve-IPs.ps1: remove \Continue global assignment inside foreach loop; wrap DNS lookup in try/catch to suppress per-call errors without leaking preference scope Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * 🐛 fix(scripts): address prior PR Copilot review follow-ups - Make profile Prompt implementations null-safe when command history is empty - Add ShouldProcess support around New-gMSA Active Directory changes - Update stale remoting catch messages after replacing Enter-PSSession usage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * 🐛 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> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 4ce0d6a commit 1241307

9 files changed

Lines changed: 39 additions & 26 deletions

Active Directory/AD Users/Set User EmailAddress from PrimaryAddress.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Write-Progress -Id 1 -Activity $MainScriptActivity -Status $MainScriptStatus -Pe
3232
foreach ($user in $users)
3333
{
3434
$i++
35-
Write-Progress -Id 2 -Activity $UserLoopActivity -Status "$i of $userCount - $user.Name" -PercentComplete ($i / $userCount * 100) -ParentId 1
35+
Write-Progress -Id 2 -Activity $UserLoopActivity -Status "$i of $userCount - $($user.Name)" -PercentComplete ($i / $userCount * 100) -ParentId 1
3636

3737
$addresses = $user | Select-Object -ExpandProperty ProxyAddresses
3838
If ($addresses)

Active Directory/Domain Services/DNSZonesRemote.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ foreach ($srv in $servers) {
4848
}
4949
}
5050
} Catch {
51-
Write-Host -ForegroundColor DarkYellow "Failed to enter the PSSession for $server. Skipping."
51+
Write-Host -ForegroundColor DarkYellow "Failed to create or use the PSSession for $server. Skipping."
5252
Continue
5353
} Finally {
5454
if ($session) {

Active Directory/Set DNS Server Zone Settings via Registry.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ foreach ($srv in $servers) {
5555
}
5656
}
5757
} Catch {
58-
Write-Host "Failed to enter the PSSession for $server. Skipping." -ForegroundColor DarkYellow
58+
Write-Host "Failed to create or use the PSSession for $server. Skipping." -ForegroundColor DarkYellow
5959
Continue
6060
} Finally {
6161
if ($session) {

DDI/DNS Reverse Lookup from CSV and Add Column with Hostname.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ $file = ""
22
$csv = Import-Csv $file
33
foreach ($row in $csv) {
44
$IP = $row.SourceIP
5-
$row.SourceName = ([System.Net.DNS]::GetHostbyAddress($IP)).Hostname
5+
$row.SourceName = ([System.Net.DNS]::GetHostEntry($IP)).Hostname
66
}
77
$csv | Export-Csv "results.csv" -NoTypeInformation

DDI/Resolve-IPs.ps1

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@ $ResultList = @()
1414

1515

1616
foreach ($IP in $ListOfIPs) {
17-
$ErrorActionPreference = 'silentlycontinue'
1817
$Result = $null
1918

2019
Write-Host "Resolving $IP" -ForegroundColor Green
21-
$result = [System.Net.Dns]::gethostentry($IP)
20+
try {
21+
$Result = [System.Net.Dns]::GetHostEntry($IP)
22+
} catch {
23+
$Result = $null
24+
}
2225

2326
If ($Result) {
2427
$ResultList += "$IP," + [string]$Result.HostName

Profile and Prompt/PSProfileBase.ps1

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,10 @@ if ($IsPowerShellISE -or (-not (Get-Command -Name 'oh-my-posh' -ErrorAction Sile
170170
# Custom prompt function that shows admin status, command ID, command duration, and path.
171171
function Prompt {
172172
$LastCommand = Get-History -Count 1 -ErrorAction SilentlyContinue
173+
$CommandId = if ($LastCommand) { $LastCommand.Id + 1 } else { 1 }
174+
$DurationMilliseconds = if ($LastCommand) { [math]::Ceiling($LastCommand.Duration.TotalMilliseconds) } else { 0 }
173175
Write-Host "$AdminStatus " -ForegroundColor "$AdminStatusColor" -NoNewline
174-
Write-Host "[$($LastCommand.Id +1)] $([math]::Ceiling($LastCommand.Duration.TotalMilliseconds))ms " -NoNewline -ForegroundColor White
176+
Write-Host "[$CommandId] ${DurationMilliseconds}ms " -NoNewline -ForegroundColor White
175177
Write-Host "$FolderGlyph $($PWD.ToString() -ireplace [regex]::Escape($HOME),'~')" -ForegroundColor Yellow
176178
Write-Host '>' -NoNewline -ForegroundColor White
177179
return ' '
@@ -190,8 +192,10 @@ if ($IsPowerShellISE -or (-not (Get-Command -Name 'oh-my-posh' -ErrorAction Sile
190192

191193
function Prompt {
192194
$LastCommand = Get-History -Count 1 -ErrorAction SilentlyContinue
195+
$CommandId = if ($LastCommand) { $LastCommand.Id + 1 } else { 1 }
196+
$DurationMilliseconds = if ($LastCommand) { [math]::Ceiling($LastCommand.Duration.TotalMilliseconds) } else { 0 }
193197
Write-Host "$AdminStatus " -ForegroundColor "$AdminStatusColor" -NoNewline
194-
Write-Host "[$($LastCommand.Id +1)] $([math]::Ceiling($LastCommand.Duration.TotalMilliseconds))ms " -NoNewline -ForegroundColor White
198+
Write-Host "[$CommandId] ${DurationMilliseconds}ms " -NoNewline -ForegroundColor White
195199
Write-Host "$FolderGlyph $($PWD.ToString() -ireplace [regex]::Escape($HOME),'~')" -ForegroundColor Yellow
196200
Write-Host '>' -NoNewline -ForegroundColor White
197201
return ' '

Snippets/RemoteServerSessionLoop2.ps1

Lines changed: 16 additions & 14 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-
Enter-PSSession $session
22+
$session = New-PSSession -ComputerName $server -Name $server -Credential $Creds -ErrorAction Stop
23+
# Enter-PSSession is interactive-only; use Invoke-Command to run code in the remote session.
24+
Invoke-Command -Session $session -ErrorAction Stop -ScriptBlock {
25+
<#
26+
Code to be run on each remote server goes here.
27+
#>
28+
Write-Information 'Inner code.' -InformationAction Continue
29+
}
2330
} Catch {
24-
Write-Warning "Failed to enter the PSSession for $server. Skipping." -WarningAction Continue
31+
Write-Warning "Failed to create or use the PSSession for $server. Skipping." -WarningAction Continue
2532
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+
}
2639
}
27-
Write-Output $session.State
28-
29-
<#
30-
Code to be run on each remote server go here.
31-
#>
32-
Write-Information 'Inner code.' -InformationAction Continue
33-
34-
#Cleanup and then show the current PSSession state.
35-
Exit-PSSession
36-
Remove-PSSession $session
37-
Write-Information "$session.ComputerName $session.State `n`n" -InformationAction Continue
3840
}

Windows/Disable-Poshv2.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ $exclusions = @('', '', '')
1111
#Filtering out production servers as well as any SQL, Exchange, SharePoint (SPS), Telephony, rinf* servers, and any servers in the "Non Windows" OU.
1212
$servers = (Get-ADComputer -Filter 'OperatingSystem -like "Windows Server*" -and Enabled -eq "True" -and Name -notlike "*sps*"' `
1313
-SearchBase 'DC=DOMAIN,DC=COM' -SearchScope Subtree).Name | Where-Object { $_ -notin $Exclusions } | Sort-Object
14-
Write-Information "$servers.Count servers found."
14+
Write-Information "$($servers.Count) servers found."
1515

1616
foreach ($server in $servers) {
1717
if (Test-WSMan -ComputerName $server -ErrorAction Ignore) {

Windows/New-gMSA.ps1

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Function New-gMSA {
3737
.OUTPUTS
3838
None
3939
#>
40+
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
4041
param (
4142
[Parameter(Mandatory=$true)]
4243
[ValidateLength(1,15)]
@@ -65,7 +66,10 @@ Function New-gMSA {
6566
Import-Module ActiveDirectory
6667
$Group = "MSA " + $gMSA
6768
$DNS = "$gMSA.$DomainDnsName"
68-
New-ADGroup -Name $Group -GroupScope Global -DisplayName $Group -Description "Permission group for $gMSA" -Path $GroupPath -Credential $Credential
69-
Add-ADGroupMember -Identity $Group -Members ($Servers | ForEach-Object {Get-ADComputer -Identity $_ -Credential $Credential}) -Credential $Credential
70-
New-ADServiceAccount -Name $gMSA -DNSHostName $DNS -PrincipalsAllowedToRetrieveManagedPassword $Group -Path $ServiceAccountPath -Credential $Credential
69+
70+
if ($PSCmdlet.ShouldProcess($gMSA, 'Create gMSA, retrieval group, and group membership')) {
71+
New-ADGroup -Name $Group -GroupScope Global -DisplayName $Group -Description "Permission group for $gMSA" -Path $GroupPath -Credential $Credential
72+
Add-ADGroupMember -Identity $Group -Members ($Servers | ForEach-Object {Get-ADComputer -Identity $_ -Credential $Credential}) -Credential $Credential
73+
New-ADServiceAccount -Name $gMSA -DNSHostName $DNS -PrincipalsAllowedToRetrieveManagedPassword $Group -Path $ServiceAccountPath -Credential $Credential
74+
}
7175
}

0 commit comments

Comments
 (0)