≡ Menu

Powershell: Unexpected attribute ‘cmdletbinding’(ParentContainsErrorRecordException)

I get the below error sometimes while working with powershell scripts. Every time I end up spending some efforts to recollect what I have done previously to fix this. This time I decided to document it for my quick reference and for other powershell users.

ERROR Message:

Unexpected attribute ‘cmdletbinding’.
At line:24 char:15
+ [cmdletbinding <<<< ()] + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedAttribute

When we will get this error?

This error we will generally observe when copy pasting a function from script to powershell console for quick execution. It is also quite possible that you might get this error while running some script or importing a function.

What are the causes for this error?

Mainly there are two cases where you will get this error.

Missing of param declaration:

We declare [cmdletbinding()] in a function or script but may miss to declare parameters after that. It is possible that your script/function doesn’t requires any parameters but you still need to declare it like param ( ). Otherwise you will get the above error.

So, it is general thump rule that [cmdletbinding()] should follow param() like below.

            
function foo-bar {            
[cmdletbinding()]            
param (            
)            
...            
...            
...            
}

A new line between [cmdletbinding()] and param declaration:

Just try copy pasting the below code into a powershell window and let me know what happens. You will definitely observe the above given error. This is because of the new line between [cmdletbinding()] and param declaration. Now remove the new line and try again. It should go well.

            
function foo-bar {            
[cmdletbinding()]            

param (            
)            
...            
...            
...            
}

Note that above is true while copy pasting the code into powershell window. If you have this space in a script and you are executing the script from powershell window, then you may not notice this.

Hope this helps… Happy learning…

 

Comments on this entry are closed.

  • Trevor July 19, 2020, 3:15 am

    Thanks for the tip, fixed my issue!

  • Roberto October 18, 2021, 10:50 pm

    In my case it happened to me even without having the 2 cases that you listed.
    I could fix it by adding the code into a function and later run the function instead of the command.

    Thanks for the idea 🙂