当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell - Calling a cmdlet with custom arguments

问题描述:

I have a powershell script which can be called by certain users. The script runs with some elevated permissions so I need to make sure they can't use it to bypass the intended behavior. One of the parameters to the script is a string which acts as the arguments for another cmdlet.

So a user might supply the string '-Day 4 -Year 1989 -Month 3'

then in my script, I'd want to run: Get-Date -Day 4 -Year 1989 -Month 3

Now I know I could do this via Invoke-Expression but that would leave me vulnerable to powershell injection (ie: the user could pass in '-day 4; do-bad-stuff')

Alternatively, I could write a wrapper for Get-Date but that seems like a lot of work since the cmdlet I'm actually calling (it's not Get-Date) has a lot of different parameters and it seems like a lot of work to wrap them all. There's no arguments they could call on that cmdlet which could cause harm (since it's a Get-xxx cmdlet).

Anyone know of a way to call a specific cmdlet with a string as it's arguments?

网友答案:

Using parameter validation:

Function Foo 
{ 
    Param( 
        [ValidateRange(1,31)] 
        [String] 
        $day 
    , 
        [ValidateRange(1900,2013)] 
        [Int] 
        $Year 
    , 
        [ValidateRange(1,12)] 
        [string] 
        $Month 
    ) 
    Process 
    { 
         Get-Date -Day $day -Year $year -Month $month 
    } 
}

Read here and here to learn improve the validation

分享给朋友:
您可能感兴趣的文章:
随机阅读: