使用CSV填充Import-Gpo的参数

时间:2018-04-23 17:09:49

标签: powershell csv import group-policy

CSV:

BackupGpoName,BackupId,GPOName,path
"GPO1",11111111-2222-3333-444444444444,"GPO1","C:\BackupGPO"
"GPO2",78888888-1222-4555-8777-123456789123,"GPO1","C:\BackupGPO"

脚本:

$csv = Import-Csv -Path "C:\gpotest.csv" -Header BackupGpoName, BackupId, gponame, Path
$csv | ForEach-Object {
    $params = @{
        BackupGpoName = $_.BackupGpoName
        BackupId      = $_.backupid
        TargetName    = $_.gponame
        Path          = $_.path
    }
    $params.$type = $true
    Import-Gpo @params -CreateIfNeeded
}

但我收到错误:

Foreach-Object : Cannot bind parameter 'BackupId'. Cannot convert value
"BackupId" to type "System.Guid". Error: "Guid should contain 32 digits
with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."
At line:2 char:10
+   $csv | Foreach-Object {
+          ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand

1 个答案:

答案 0 :(得分:0)

Bill_Stewart是正确的,如果您的csv包含标题,则不应指定-Header。使用示例csv和简单的打印语句:

$csv = import-csv -Path "C:\temp\test.csv" -Header BackupGpoName, BackupId, 
gponame, Path
$csv | Foreach-Object {

$_.BackupGpoName
$_.backupid
$_.gponame
$_.path

$params = @{
    BackupGpoName=$_.BackupGpoName
    BackupId=$_.backupid
    TargetName=$_.gponame
    Path=$_.path
}
$params.$type = $true

#import-gpo @params -CreateIfNeeded 
}

导致错误,因为代码正在尝试投射" BackupId"作为GUID:

BackupGpoName BackupId GPOName path GPO1 11111111-2222-3333-444444444444 GPO1 C:\BackupGPO GPO2 78888888-1222-4555-8777-123456789123 GPO1 C:\BackupGPO

由于你的csv有一个标题,你的代码应该是

$csv = import-csv -Path "C:\temp\test.csv"
$csv | Foreach-Object {

$_.BackupGpoName
$_.backupid
$_.gponame
$_.path

$params = @{
    BackupGpoName=$_.BackupGpoName
    BackupId=$_.backupid
    TargetName=$_.gponame
    Path=$_.path
}
$params.$type = $true

#import-gpo @params -CreateIfNeeded 

}

和预期的输出:

GPO1 11111111-2222-3333-444444444444 GPO1 C:\BackupGPO GPO2 78888888-1222-4555-8777-123456789123 GPO1 C:\BackupGPO