I’m trying to write a code to check how many parameters ( with positions ) were entered when executing a powershell script.
For example
param ( sourceserver,
sourcedatabase,
destinationserver,
destinationdatabase
)
when executing a script , if i miss any parameters it should throw an error saying " a parameter is missing " I know we can put a mandatory params but not sure how to achieve what i’m looking for.
Is it possible to do in powershell ?
Please let me know
thanks in advance
For example. The shell will prompt for those values rather than throwing an error. If that’s not the behavior you want, you’d have to code it yourself.
if (-not $PSBoundParameters.ContainsKey('sourceserver')) { Write-Error "SourceServer parameter missing" }
Thanks Don…i’m aware of these mandatory parameters. If we schedule the PS script as SQL agent job ( including mandatory parameters as you mentioned above )
and if we miss a parameters and job runs, what will be its behavior ?
If you add the -NonInteractive argument when calling PowerShell.exe to launch your job, you won’t have that problem. Any missing mandatory parameters will cause an exception instead of prompting the user for input:
At command prompt:
C:\Users\Dave\SkyDrive\Source\Temp>powershell.exe -NonInteractive -Command "%cd%\test.ps1"
C:\Users\Dave\SkyDrive\Source\Temp\test.ps1 : Cannot process command because of one or more missing mandatory parameters: TestParam.
At line:1 char:1
+ C:\Users\Dave\SkyDrive\Source\Temp\test.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [test.ps1], ParameterBindingException
+ FullyQualifiedErrorId : MissingMandatoryParameter,test.ps1
Thank you both for the response…
Hi David, i have tried your suggestion, -NonInteractive. job is running but no progress…it never ends.
One thing i observed ( this is new issue ) is when i run the PS script from powershell console it works fine but when i run it as a sql agent job it fails with some error in code which i dont see when i run it from PS console.
Don, what do you mean by " run it as a shell task" ?
Thanks for your valuable responses,time and patience