2
function Itil
{
    $_.Font = 'Microsoft Sans Serif, 8.25pt, style=Italic'
    $_.Text = 'Double-click to add username'
    $_.ForeColor = 'ScrollBar'
}

$Username10.Font = 'Microsoft Sans Serif, 8.25pt, style=Italic'
$Username10.Text = 'Double-click to add username'
$Username10.ForeColor = 'ScrollBar'

Is there a way to pass an object into a function without having to name the object itself?

In other words, rather than repeating the same last three lines of code for each $username (there are 10 username textboxes), I can call a function, with the name of the object and make the changes to that object?

2 Answers 2

2

If the input objects are all reference types you can iterate over the $input enumerator:

filter Set-UsernameFieldStyle {
    $input |ForEach-Object {
        $_.Font = 'Microsoft Sans Serif, 8.25pt, style=Italic'
        $_.Text = 'Double-click to add username'
        $_.ForeColor = 'ScrollBar'
    }
}

and use like:

# Input all the elements that need to be styled this way via the pipeline:
$Username1,$Username4,$Username10 |Set-UsernameFieldStyle
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to do $username$n (where $n is an integer)? ForEach ($n in 1..10 ) { UseSystemPasswordChar $Password$n }
1

Mathias provided a nice way using PowerShell filter. However, if you want to use a simple function, this should work:

function Set-BasicProperties
{
    [CmdletBinding()]
    Param
    (
        $UiObject
    )

    $UiObject.Font = 'Microsoft Sans Serif, 8.25pt, style=Italic'
    $UiObject.Text = 'Double-click to add username'
    $UiObject.ForeColor = 'ScrollBar'
}


Set-BasicProperties $Username10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.