PowerShell – How to name Functions

Hi All,

In development world, we normally re-use code. More experienced developers, re-use more code than developers that are starting.

It is not just PowerShell, this is also used when coding on any language but with PowerShell, you have the option to create a function within your script or inside modules, but the problem is always the same, how to name these functions.

Before writing a function, you need to know what the function will do and what is the expected return of the function.

So lets look at an example: I discovered in a code, that I use, lots of time, writing text to a file. if the file does not exist, it will be created and if it does exist, i’ll append text.

as you can imagine, the function could be called SaveToFile, AppendToFile, WriteToFile, etc. instead of something like MyFunction. You may be thinking, who would write a function like that!?!??!?! There are lots of people and i probably did this when starting writing code long ago…

But we’re using powershell, so we need to know what verbs are normally used and when, and for this, we can use the get-verb cmdlet. The Get-Verb function gets verbs that are approved for use in Windows PowerShell commands.

But if I want to use something that is not “approved”, can I?!?! yes, it is not a best practice, but you can.

So know that we know what verbs we can use, and we’re using powershell, lets try to name our function again:
1) SaveToFile. Can we use save?!?! use get-verb save. you will see that the save verb can be used and it is common used when dealing with Data, maybe not a good name for us
2) AppendToFile. Can we use append?!?! use get-verb append. Append does not exist, so probably good to avoid
3) WriteToFile. can we use? use get-verb write. Write does exist and is common used with communications. in this case, we’re trying to “communicate” (at least I think), somehow, so the write would be the best option.

And with poewrshell, we normally don’t use the ToFile, etc. we would use the , so in this case Write-File is the best option for this function


Recent Posts

Comments are closed.
%d bloggers like this: