Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Need Help with Advanced Functions

$
0
0

Yeah I am still trying to grasp the concepts of PowerShell toolmaking. I know my code looks a bit scatter brained. I guess I just need to study up on functions more.

One question, I put cmdletbinding, param stuff within a function, is that not right? I was able to type it in and use tab completion in the ISE’s host, but when I opened up a separate PowerShell command window and typed in:

” .\Check-ADUserExist -UserName”

It spit back an error regarding not being recognized and the -UserName parameter was not resolved using tab completion. So am I supposed to keep the cmdletbinding and param() adv function stuff completely external to a function?

Why is it that the ISE had no issue with it, but the PowerShell command line did? I set the path to where the script was and still I got back an error.

————————————–
Regarding Your Advice
————————————–

So let me see if I understand you correctly. What you recommend is that I should do something like the following instead:

#Example Script Tool Name: Do Stuff Tool
#Example Script File Name: Do-Stuff.ps1
#Author: Someone Doe
#Date Created:
#Modified By:
#Date Modified:

<#

Modifications Record
————————-

<ThatDate>
————–

Explain modifications made

<ThisDate>
————–

Explain modifications made

#>

Function Show-Menu
{
1. Do stuff
2. Help
3. Exit

$MenuPrompt = Read-Host -Prompt “Enter selection 1 thru 3″

While ($MenuPrompt -lt “1″ -or $MenuPrompt -gt 3)
{
[void][System.Windows.Forms.Messagebox]::Show(“You did not make a proper selection! Please try again.”, “Menu Selection Error”)

Show-Menu
}

Switch (Show-Menu)
{
“1″
{
Do-Stuff -Parm “something”
}

“2″
{
Do-Stuff -Help
}

“3″
{
Exit
}
}

Function Do-Stuff
{
#Region: Parameter Input Validation

[CmdletBinding()]
[OutputType([String])]
Param
(
[Parameter(Position=0,
Mandatory=$true,
HelpMessage="Does stuff")]
[ValidateNotNullOrEmpty()]
[String]
$Parm,

[Parameter(Position=1,
Mandatory=$false,
HelpMessage="Enter -ShowMenu to view the menu instead of using command line parameters")]
[Alias('menu')]
[String]
$ShowMenu

#EndRegion: Parameter Input Validation

#Region: Load Prerequisites

Begin
{
#Requires -Version x
#Requires -Modules YadaYada

[void][System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
}

#EndRegion: Load Prerequisites

#Region: Process Parameter Input and Call Functions

Process
{
If ($Parm)
{
Do some stuff here
}

If($ShowMenu)
{
#Call the Show-Menu function
here

Show-Menu
}

If ($Parm -and $ShowMenu)
{
Write-Host “Cannot use both -DoStuff and -ShowMenu parameters together. Please use one or the other”

Write-Host “Press any key to continue …”

$Pause = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)

Do-Stuff
}

#EndRegion: Process Parameter Input and Call Functions

End

{
Exit
}

}


Viewing all articles
Browse latest Browse all 13067

Trending Articles