Forum Discussion
ThomasLehmann
Feb 05, 2024Copper Contributor
Import-Module for advanced functions doesn't work as expected
Using [CmdletBinding(SupportShouldProcess)] on functions using them inside the main script does work as expected: When passing -WhatIf or -Confirm:$true to the script then those parameters are passed...
ThomasLehmann
Feb 05, 2024Copper Contributor
My Module function (test) looks like following:
function Test-WriteMessage {
[CmdletBinding(SupportsShouldProcess=$true)]
param ([String] $Message)
Write-Message "-WhatIf:$WhatIfPreference -Confirm:$ConfirmPreference"
if ($PSCmdlet.ShouldProcess($Message, 'Writing a message')) {
Write-Message $Message
} else {
Write-Message "$Message (simulated)"
}
}And my main.ps1 looks like following:
[CmdletBinding(SupportsShouldProcess)]
param()
Import-Module $PSScriptRoot\Tools -Force
Write-Debug "is just a test"
Write-Message "hello world!"
Test-WriteMessage "hello world!"When calling .\Main.ps1 -WhatIf then I get
hello world!
-WhatIf:False -Confirm:High
hello world!
However when moving the Test-WriteMessage into "Main.ps1":
hello world!
-WhatIf:True -Confirm:High
What if: Performing the operation "Writing a message" on target "hello world!".
hello world! (simulated)
LainRobertson
Feb 05, 2024Silver Contributor
I missed a third test, where you're passing -WhatIf into the script, however, I had no issues with this, either.
Adjusted script (.\forum.ps1)
[cmdletbinding(SupportsShouldProcess=$true)]
param();
Import-Module -Name .\Forum.psm1;
Test-WriteMessage -Message "Foo" -WhatIf:$WhatIfPreference;
Remove-Module -Name "Forum" -WhatIf:$false;
Output
Cheers,
Lain
- ThomasLehmannFeb 05, 2024Copper Contributorok ... always passing -WhatIf:$WhatIfPreference (and same for confirm) does work (of course). However it is weird since it mean that SupportsShouldProcess is less intuitive to use since there is not much left to simply define those parameters myself. The automatically passing through all functions that do support the ShouldProcess was the real benefit which has gone moving those functions into a module.
Anyway, thanks for your help