dbatools icon indicating copy to clipboard operation
dbatools copied to clipboard

cleanup.ps1 execution error using strict mode

Open RandyInMarin opened this issue 3 years ago • 1 comments

Verified issue does not already exist?

Yes

What error did you receive?

cleanup.ps1: The variable '$olderVersions' cannot be retrieved because it has not been set.

Steps to Reproduce

Set-StrictMode -Version 3 & "$((Get-InstalledModule dbatools).InstalledLocation)\cleanup.ps1"

Are you running the latest release?

No response

Other details or mentions

Adding the following to scripts that can be run independently will insure they work when the user uses strict mode.

Set-StrictMode -Version 3

In this case, $olderVersions is not being set but used in conditionals. Always set it and let it be empty? Is the objective to keep at least the latest one installed even if it's not the latest available? If only one is installed, leave it. If 2 or more are installed, remove them all if none are current?

If all old versions are to be removed, replace

if ($installedVersion.Count -gt 1) { $olderVersions = @($installedVersion | Where-Object { [version]$_.Version -lt [version]$newestVersion.Version }) }

with

$olderVersions = @($installedVersion | Where-Object { [version]$_.Version -lt [version]$newestVersion.Version })

Counts need to be fixed as well when the object can be $null

if ($processes.Count -gt 0) {... has error
if ($processes -and $processes.Count -gt 0) {...

What PowerShell host was used when producing this error

VS Code (integrated terminal)

PowerShell Host Version

[32;1mName Value[0m [32;1m---- -----[0m PSVersion 7.2.4 PSEdition Core GitCommitId 7.2.4 OS Microsoft Windows 10.0.19043 Platform Win32NT PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…} PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 WSManStackVersion 3.0

SQL Server Edition and Build number

NA

.NET Framework Version

.NET 6.0.5

RandyInMarin avatar Jun 02 '22 19:06 RandyInMarin

I suppose Set-StrictMode -off would work as well. In that case, set oldversions if any version is installed?

if ($installedVersion.Count -gt 0) { $olderVersions = @($installedVersion | Where-Object { [version]$_.Version -lt [version]$newestVersion.Version }) }

RandyInMarin avatar Jun 02 '22 20:06 RandyInMarin

Thanks for reporting this, I opened a pull request to fix it.

andreasjordan avatar Oct 24 '22 15:10 andreasjordan

Thank you, this will be a part of dbatools 2.0

potatoqualitee avatar Oct 26 '22 06:10 potatoqualitee