PowerShell parameters from file

╄→гoц情女王★ 提交于 2020-01-03 05:30:09

问题


I am having some issue in calling a function using named parameters.

This is the declaration of the function in a separate file (Security.ps1):

function Add-SSRSItemSecurity
(
    [Parameter(Position=0,Mandatory=$false)]
    [Alias("SSRSrange")]
    [string]$range,[Parameter(Position=1,Mandatory=$false)]
    [Alias("path")]
    [string]$itemPath,

    [Parameter(Position=2,Mandatory=$false)]
    [Alias("grp")]
    [string]$groupUserName,

    [Parameter(Position=3,Mandatory=$false)]
    [Alias("SSRSrole")]
    [string]$role,

    [Parameter(Position=2)]
    [bool]$inherit=$true
)

I then call this function in another Host.ps1 script as:

    Set-Location 'C:\SSRSJobs'
    . .\SSRSsecurity.ps1

This call works in the Host file:

Add-SSRSItemSecurity -range "server1" -itemPath "/Test" -groupUserName "CN\Group" -role "Browser"

I tried to pass in multiple parameters to the function as a loop, but calling new variables each time:

$securityArray = @()
$securityArray = Get-Content -Path "C\ReleaseSecurity.txt"
    foreach($line in $securityArray)
    {
        Add-SSRSItemSecurity $line;
    }

The file having:

-range "server1" -itemPath "/Test" -groupUserName "CN\Group" -role "Browser"
-range "server2" -itemPath "/Test" -groupUserName "CN\Group" -role "Browser"
-range "server3" -itemPath "/Test" -groupUserName "CN\Group" -role "Browser"

The error I get is:

Add-SSRSItemSecurity : Cannot bind positional parameters because no names were given.
At line:229 char:27
+                         Add-SSRSItemSecurity <<<<  $line;
    + CategoryInfo          : InvalidArgument: (:) [Add-SSRSItemSecurity], ParameterBindingExcepti
   on
    + FullyQualifiedErrorId : AmbiguousPositionalParameterNoName,Add-SSRSItemSecurity

Inspecting the string, the $line variable does hold correct naming for parameters. I've tried all sorts of error trapping, but I'm unable to get a decent error message other than the above. I've also tried forms of quoting, but I cannot get the function to see the name binding.

Can multiple variables be called in a function that are bound to just a PowerShell variable name?


回答1:


You can use splatting for that. Save the parameters as a CSV like this:

"range","itemPath","groupUserName","role"
"server1","/Test","CN\Group","Browser"
"server2","/Test","CN\Group","Browser"
"server3","/Test","CN\Group","Browser"

and load it like this:

Import-Csv 'C:\ReleaseSecurity.txt' | % {
  Add-SSRSItemSecurity @_
}


来源:https://stackoverflow.com/questions/28088460/powershell-parameters-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!