Invoke-expression on a previous script to add parameters to it from a csv

501 Views Asked by At

I'm learning powershell only from few month, and I'have been asked to write a script that outsides my actual knowledge. I have a script which work perfectly when I have to extract user from ONE AD group. My probleme here is that this script accept only one parameter and I have been asked this week to extract over 1000 groups...)

.\myscript.ps1 ADgroup

What I want to do : 1. I get an extract in CSV so I'd like to put in parameters all these groups to my script 2. I want to generate a file text of the result but I am not sure which is the best way to do that in this case.

So Here is my code

$grouplist=IMPORT-CSV C:\Myfile\Mytest\liste.csv
foreach ($group in $grouplist) {
    Invoke-Expression .\membre_group_AD_V2.ps1 $group
                                }

My CSV test had just to group to run my test, I get the same kind of error on each group

Invoke-Expression : Impossible de trouver un paramètre positionnel acceptant l'argument « @{grouplist=Administrators} ».

Au caractère C:\myfile\Mytest\script\dev\bouclage_membre_group_AD_V2.ps1:36 : 2
+     Invoke-Expression .\membre_group_AD_V2.ps1 $group
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Invoke-Expression], ParameterBindingException    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand

If required I can try to translate this error. If you can help to improve my knowledge it could be great! Thank you for tanking time to read this.

1

There are 1 best solutions below

3
On

It seems that you have a "grouplist" header in your CSV file. I assume it looks something like this:

"grouplist"
"Administrators"
"Other Group Name"

Now, when you use Import-Csv, all rows are read into an object with a single NoteProperty per column, named after the headers in the csv file.

So in your case, each object in $grouplist has a grouplist property that contains the name - this is the property value you want to pass as an argument to your script:

$grouplist=Import-Csv C:\Myfile\Mytest\liste.csv
foreach ($group in $grouplist) {
    .\membre_group_AD_V2.ps1 $group.grouplist
}

Assuming that the output from membre_group_AD_V2.ps1 is already what you expect, use the Out-File cmdlet with -Append to write it to the same text file:

$grouplist=Import-Csv C:\Myfile\Mytest\liste.csv
$OutfilePath = "C:\Myfile\membre_group_out.txt"
foreach ($group in $grouplist) {
    .\membre_group_AD_V2.ps1 $group.grouplist | Out-File $OutfilePath -Append -Encoding utf8
}

If not, you'll have to show us the membre_group_AD_V2.ps1 script