check the parameters in powershell

Hi,

I need to check the parameters that we pass while execution…

for example…

param

(

servername,

databasename

)

saving the script as powershell.ps1…

executing the script as

powershell.ps1 DBATest Adventureworks

In the above example…i would like to do a check on the server name…

if the 4th character is ‘T’ …raise an exception…if its not then go ahead…

please help me on this…and let me know if you need any details…

 

Thanks

You could use the ValidateScript approach

function ptest {
[CmdletBinding()]
param(
 [ValidateScript({$_.Substring(3,1) -ne "T" })]
 [string]$server
)
 Write-Host "$server"
}

So the proper syntax is:

param(

[string]$computername,

[string]$databasename

)

I used -ComputerName since that’s more standard in PowerShell than -ServerName. So, to extend that:

[CmdletBinding()]

param(

[ValidatePattern('^...[^t]')]

[string]$computername,

 

[string]$databasename

)

So, I added a regular expression (regex) validation. Now, this is just off the top of my head - I’m not a regex wizard, so the actual pattern may need to be modified. But I think that’ll take any three characters at the start, followed by a fourth character that is not a “t,” followed by any number of other characters. That’s one way to do parameter validation.

Thank you both…i think i didn’t mention the logic properly…this is what exactly i’m looking for…

For example param

(

$computername

)

argument for $computername is DBATest

The computer name should not have T alphabet, if it has T it should raise an exception and give us an indication that it has T and should ask us to continue… e.g., yes or no…if we choose ‘yes’ it should continue or ‘no’ to abort the execution…

Please let me know your suggestions…thanks

 

You should be able to steal most of Richards logic.

If($ComputerName.Substring(3,1) -ne “T”){
Do Something
}
Else{
Write-Warning “We found a ‘T’”
Do something else
}

Thanks for your input David…

condition is working fine now…but when the computername do not have 'T ’ ,it goes into else block and executes…i need to put a condition in else so that i ask us to continue the execution…

for e.g., computer name has T in it…do you want to proceed with the execution yes[y], No [n] :

Thanks in advance…

Take a look at “Read-host”. You can save the results in a variable and then reference it in a nested if statement.

Thanks David…its working now…