Author Posts

October 3, 2013 at 10:12 am

Hi,

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

October 3, 2013 at 10:17 am

[CmdletBinding()]
param(
  [Parameter(Mandatory=$True)][string]$sourceserver,
  [Parameter(Mandatory=$True)][string]$sourcedatabase
)

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" }

Or something along those lines.

October 3, 2013 at 12:38 pm

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 ?

Thanks

October 3, 2013 at 1:25 pm

If it's run under the standard PowerShell host, it'd probably hang waiting for input.

October 3, 2013 at 4:20 pm

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:

# Test.ps1:
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    $TestParam
)

$TestParam
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

October 3, 2013 at 4:25 pm

Running the job through Agent wouldn't give that option, though. You'd run it as a shell task, so you could specify that.

October 4, 2013 at 9:29 am

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