尝试将CS​​V和哈希表中的数据混合以创建变量 [英] Trying to mix data from a CSV and a hashtable to make a variable

查看:82
本文介绍了尝试将CS​​V和哈希表中的数据混合以创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码审查停了下来,问我如何精简脚本并被建议使用哈希表 strong>,因为它将清理代码.我得到了一个非常基本的示例,但它不是即插即用.我已经编写了一些基本代码,但是没有按照我认为的做.知道Code Review的人们并没有像这样的支持,在这里,我正在寻找有关将CSV和哈希表中的变量组合在一起的帮助.我将从下面的CSV和Powershell代码中获取示例数据.

I stopped over at Code Review, asking how I could streamline a script and was advised to use a hashtable as it would clean up the code. I was given a very basic example but it wasn't plug-and-play. I've worked up some basic code but it's not doing what I think it should. Knowing the Code Review folks aren't there for support like this, here i am, looking for help with combining a variable from a CSV and a hashtable. I'll leave sample data from my CSV and the Powershell code below.

示例CSV:

Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000@mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000@mydomain.org,40,2021

示例Powershell:

# Testing simple hash table
$SchoolCodes = @{
        20 = "Exeter Township Senior High"
        30 = "Exeter Township Junior High"
        40 = "Lorane Elementary School"
        50 = "Jacksonwald ES"
        70 = "Reiffton School"
        90 = "Owatin Creek Elementary School"
}

# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"

# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"

# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users) {
    # Creating the basic variables.
    $FirstName = $User.'Student First Name'
    $MiddleInitial = $User.'I'
    $LastName = $User.'Student Last Name'
    $ADUserName = $User.'Stu Access Login'
    $StudentID = $User.'Other ID'
    $GradYear = $User.'Grad Year'
    $CapFInitial = $FirstName.substring(0,1).ToUpper()
    $MInitial = $MiddleInitial.substring(0,1).ToLower()
    $LInitial = $LastName.substring(0,1).ToLower()
    $Password = "$CapFInitial$MInitial$LInitial" + "#" + "$StudentID"
    $SchoolCode = $SchoolCodes[$User.School]


    If (-Not(Get-ADUser -Filter {SamAccountName -eq $ADUserName})) {
        Try {
            # Create user.
            New-ADUser `
                -Name "$FirstName $LastName" `
                -SamAccountName "$ADUserName" `
                -GivenName "$FirstName" `
                -Initials "$MiddleInitial" `
                -Surname "$LastName" `
                -DisplayName "$FirstName $MiddleInitial. $LastName" `
                -UserPrincipalName "$ADUserName@mydomain.k12.pa.us" `
                -EmailAddress "$ADUserName@mydomain.k12.pa.us" `
                -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
                -Enabled $false `
                -PasswordNeverExpires $true `
                -CannotChangePassword $true `
                -Path "OU=$GradYear,OU=Students,OU=$SchoolCode,OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us" `
                -WhatIf
        }

        Catch {
            Write-Error "[ERROR] Can't create user [$($ADUserName)] : $_"
        }
    }
}

我的问题: 我认为该脚本最终会出错,因为$SchoolCode变量设置为 null .我想让脚本从CSV的 school 字段中找到数字(代码),并将其与最终在AD中成为OU的名称相匹配-将在其中创建用户对象.基本上,代码尝试在"CN=Tome Smith,OU=2021,OU=Students,OU=,OU=accounts,DC=academic,DC=exeter,DC=k12,DC=pa,DC=us"中创建用户对象,该对象显示$SchoolCode变量为空或未正确设置.

My issue: The script ultimately errors out because of the $SchoolCode variable being set to null, I think. I'm wanting the script to find the number (code) from the school field in the CSV and match that to the name which ends up being an OU in AD - where the User Object will get created. Basically, the code tries to create the User Object in "CN=Tome Smith,OU=2021,OU=Students,OU=,OU=accounts,DC=academic,DC=exeter,DC=k12,DC=pa,DC=us" which shows the $SchoolCode variable is either blank or otherwise not getting set correctly.

正如我在评论中提到的那样,我们正在考虑将其他静态数据作为(嵌套的?)哈希表添加到哈希表中.这是我们正在考虑的示例.随着时间的流逝,AD组的列表可能会增加.

As I mentioned in a comment, we're thinking of adding other static data to the hashtable as a (nested?) hashtable. Here's an example of what we're thinking about. As time goes by, the list of AD groups may grow.

嵌套哈希表的示例:

Example of the nested hashtable:

$SchoolCodes = @{
    20 = @{
        Name = "Exeter Township Senior High"
        ADGroup1 = "Students"
        ADGroup2 = "Secondary Students"
    }
    30 = @{
        Name = "Exeter Township Junior High"
        ADGroup1 = "Students"
        ADGroup2 = "Secondary Students"
    }
    40 = @{
        Name = "Lorane Elementary School"
        ADGroup1 = "Students"
        ADGroup2 = "K4 Students"
    }
    50 = @{
        Name = "Jacksonwald ES"
        ADGroup1 = "Students"
        ADGroup2 = "K4 Students"
    }
    70 = @{
        Name = "Reiffton School"
        ADGroup1 = "Students"
        ADGroup2 = "Secondary Students"
    }
    90 = @{
        Name = "Owatin Creek Elementary School"
        ADGroup1 = "Students"
        ADGroup2 = "K4 Students"
    }
}

我正在网上搜索并试图更好地了解哈希表.如果我能把头缠住,下一步就是将它们嵌套.

I'm scouring the web and trying to get a better understanding of hashtables. If I can wrap my head around it, nesting them would be my next step.

推荐答案

除非重新使用数据,否则将其转换为哈希表并不重要.另外,错误在于访问$SchoolCodes值.出于某种原因,访问器无法与[String]一起使用,但是当您强制转换为[Int]

Unless you're re-using the data, it's not important to turn it into a hashtable. Also, the error is in accessing the $SchoolCodes value. For some reason, the accessor isn't working with a [String], but does work when you cast to an [Int]

样本数据集:

Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000@mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000@mydomain.org,40,2021

代码:

#requires -Version 3
$SchoolCodes = @{
    20 = "Exeter Township Senior High"
    30 = "Exeter Township Junior High"
    40 = "Lorane Elementary School"
    50 = "Jacksonwald ES"
    70 = "Reiffton School"
    90 = "Owatin Creek Elementary School"
}

# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"

# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"

# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users)
{
    [String]$LoginName = $User.'Stu Access Login'
    If (-not (Get-ADUser -Filter {SamAccountName -eq $LoginName}))
    {
        $FirstName = $User.'Student First Name'
        $LastName = $User.'Student Last Name'

        $Params = @{
            Name = "$FirstName $LastName"
            SamAccountName = $LoginName
            GivenName = $FirstName
            Initials = $User.I
            Surname = $LastName
            DisplayName = "$FirstName $($User.I) $LastName"
            UserPrincipalName = "$LoginName@mydomain.k12.pa.us"
            EmailAddress = "$LoginName@mydomain.k12.pa.us"
            AccountPassword = ConvertTo-SecureString -String (
                '{0}{1}{2}#{3}' -f @(
                    $FirstName[0].ToString().ToUpper(),
                    $User.I[0].ToString().ToLower(),
                    $LastName[0].ToString().ToLower(),
                    $User.'Other ID')) -AsPlainText -Force
            Enabled = $False
            PasswordNeverExpires = $True
            CannotChangePassword = $True
            Path = 'OU={0},OU=Students,OU={1},OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us' -f @(
                $User.'Grad Year',
                $SchoolCodes[[Int]$User.School])
            WhatIf = $True
        }

        Try {New-ADUser @Params}
        Catch {Write-Error "[ERROR] Can't create user [$LoginName] : $_"}
    }
}

这篇关于尝试将CS​​V和哈希表中的数据混合以创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆