在函数中修改PowerShell对象

时间:2018-02-12 13:57:51

标签: powershell

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'

有没有办法将对象传递给函数而不必命名对象本身?

换句话说,不是为每个$username重复相同的最后三行代码(有10个用户名文本框),我可以调用一个函数,使用对象的名称并对其进行更改对象

2 个答案:

答案 0 :(得分:2)

如果输入对象都是引用类型,则可以遍历$input枚举器:

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

并使用如:

# Input all the elements that need to be styled this way via the pipeline:
$Username1,$Username4,$Username10 |Set-UsernameFieldStyle

答案 1 :(得分:1)

Mathias提供了一种使用PowerShell过滤器的好方法。但是,如果你想使用一个简单的函数,这应该有效:

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