Skip to content

Instantly share code, notes, and snippets.

@shaneis
Created February 22, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaneis/0cd417a2964ca4f4582e96eab51590bf to your computer and use it in GitHub Desktop.
Save shaneis/0cd417a2964ca4f4582e96eab51590bf to your computer and use it in GitHub Desktop.
Get-Name with extra for ScriptBlock
function Get-Name {
[CmdletBinding()]
param(
[String]$Name = 'you'
)
'Hello, {0}. Script root is {1}' -f $Name, $PSScriptRoot
}
Get-Name -Name Shane
@Kagre
Copy link

Kagre commented Jan 8, 2021

wouldn't this be testable?

param([switch]$Testing)

function Get-Name-Sourcing{
   . (join-path $PSScriptRoot 'lib\MyLogging.ps1')
}
function Get-Name {
   [CmdletBinding()]
   param(
      [String]$Name = 'you'
   )

   LogIt "Said: Hello, $Name" #From MyLogging.ps1
   'Hello, {0}' -f $Name
}

if(!$Testing){
   Get-Name-Sourcing #split out so it can be mocked
   Get-Name -Name Shane
   Remove-Item Function:\Get-Name-Sourcing
}

@shaneis
Copy link
Author

shaneis commented Jan 10, 2021

Yup, looks good to me. Nice one!

I'll say that it may be difficult to get everyone in the company/community to use this style. Especially if they're starting with PowerShell and wondering "Why do I have to do this when I just want to run a script?!"

Overall, though, yup! An absolutely superb way to ensure these scripts are testable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment