Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Powershell scripts for correctness

Is their anyway to test the correctness of a powershell script without executing it. I know you could do something similar in unix, but can't find the equiv for powershell.

Essentially what I have is a script repository, where each script is tied to rule. If a rule fires, the script executes, but I need to be sure the script is valid, before its put in the repository.

Thanks.

Hi, Well, Unfortunately the -whatif command is not sufficient. Its the syntax of scripts I want to check from a C# runtime engine, which fires a script if a engine rule fires. Before the script fires, I write into it, IList values from the rule, and then I fire it. But I need to ensure it is syntactically correct, otherwise I'm going to have to rely on the rule writer to ensure they are correct, which I can't do, as many people will wrote rules, only one duff script will bring the engine down. I can't do that as the engine is an enterpise class product designed for six sigma uptime.

I think the way to do it is to use this, which is a v2 lib.

http://msdn.microsoft.com/en-us/library/system.management.automation.parseexception(VS.85).aspx

I think there is way of creating a ScriptBlock and putting a try catch around it to catch the ParseException. Can somebody tell me how to do it. This is becoming a real challenge.

Thanks.

Hey, Well I spoke to a guy in MS (he's sharepoint pm) and he spoke to one of the powershell guys, and he informed me that there is no real way in powershell v1 to check the syntax of the script without executing. So I guess the -whatif flag is the closest, but it not a static checker unfortumately. Good news is, in v2 there is a way to tokenize the input stream, via the Automation.PsParser class, Tokenize member. This will tokenize a script in accordance with the PS grammes, so if it craps out, its a crap script. Question is v2 doesn't have an release date as yet.

Thanks for help. Bob.

like image 616
scope_creep Avatar asked Apr 16 '09 13:04

scope_creep


2 Answers

The thing you want is prolly whatif / confirm. Its direct port from Unix world.

like image 182
majkinetor Avatar answered Nov 16 '22 15:11

majkinetor


So, are you asking for functional correctness or syntactic correctness?

Functionally you'd need to create a test case and environment to test in.

Syntactically you're looking for a static code checker for powershell.

like image 24
chills42 Avatar answered Nov 16 '22 15:11

chills42