Trying to mix data from a CSV and a hashtable to make a variable

后端 未结 1 872
逝去的感伤
逝去的感伤 2021-01-22 08:36

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 basi

1条回答
  •  半阙折子戏
    2021-01-22 08:54

    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]

    Sample dataset:

    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
    

    Code:

    #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] : $_"}
        }
    }
    

    0 讨论(0)
提交回复
热议问题