Hi. I’m wondering how I should write my scripts. What I want is a file/script that behaves like a cmdlet. I am wondering if i should wrap my code in a function or not.
E.g.
function Write-Stuff { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [string] $Stuff1, [Parameter(Mandatory=$false)] [string] $Stuff2 = $null ) Process { if ($Stuff2) { Write-Host "You gave me $Stuff1 and $Stuff2" } else { Write-Host "You gave me $Stuff1" } } }
VS
[CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [string] $Stuff1, [Parameter(Mandatory=$false)] [string] $Stuff2 = $null ) Process { if ($Stuff2) { Write-Host "You gave me $Stuff1 and $Stuff2" } else { Write-Host "You gave me $Stuff1" } }
I believe that the first one actually is a module and should have the .psm1 extension and the second one is a .ps1 script. The first block would not behave like I want since it can’t be run like a script.
I’ve written a lot of Python earlier and in Python you could write files that behave both like modules and like scripts. Is this possible in PowerShell?
Is any of the code blocks above considered wrong/bad practice?