【问题标题】:Trying to create a variable with the format operator but the data for the variable changes尝试使用格式运算符创建变量,但变量的数据发生了变化
【发布时间】:2018-07-20 12:32:23
【问题描述】:

所以,我又回到了我之前玩过的script 的工作上。自构思以来,它发生了很大变化。但是,它仍然基本上从 CSV 中提取数据并根据需要在 AD 中创建帐户。它工作得很好,但是当我们注意到我们有没有中间名的人时,我遇到了麻烦。中间的首字母是我们密码格式的一部分。所以,我尝试了一些事情,包括回收我的一些other code,但我似乎无法使用正确的密码创建 AD 帐户。该帐户已创建,但我永远无法使用该帐户应接受的凭据进行身份验证。

我添加了我认为相关的代码。这不是整个脚本,因为它有 200 多行并且似乎运行良好,但是,如果您想查看全部内容,请告诉我,我将编辑以下 sn-p。

只要孩子有一个中间名首字母,工作的 code-sn-p

    # 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 the user if the account doesn't already exist in AD.
ForEach ($User in $Users) {
    [String]$LoginName = $User.'Stu Access Login'
    If (-Not (Get-ADUser -Server $ADServer -Filter {SamAccountName -eq $LoginName})) {
        $FirstName = $User.'Student First Name'
        $LastName = $User.'Student Last Name'
        $ADUserParams = @{
            Name = "$FirstName $LastName"
            SamAccountName = $LoginName
            GivenName = $FirstName
            Initials = $User.'I'
            Surname = $LastName
            DisplayName = "$FirstName $($User.'I') $LastName"
            Description= $SchoolCodes[$User.School].Name
            ScriptPath= "student.bat"
            UserPrincipalName = "$LoginName@academic.mydomain.k12.pa.us"
            EmailAddress = "$LoginName@mydomain.org"
            Company = "$LoginName@mydomain.org"
            EmployeeID = $User.'Other ID'
            HomeDirectory = "$FileServer\$LoginName"
            HomeDrive = "Z:"
            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 = $True
            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[$User.School].Name)
            Server = $ADServer
            WhatIf = $False
        } # End ADUserParams

        Try {
            # Create new user.
            New-ADUser @ADUserParams -Verbose -ErrorAction Stop
        }

        Catch {
            # If there's an error, write the error to the event log.
            Write-EventLog -LogName $EventLogName -Source $EventLogSources[0][1] -EntryType Warning -EventId $EventLogSources[0][0] -Message "Something went wrong with the creation of a new user, [$LoginName] : $_"
        }}}

首先尝试绕过丢失的中间名首字母:

# 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 the user if the account doesn't already exist in AD.
ForEach ($User in $Users) {
    [String]$LoginName = $User.'Stu Access Login'
    If (-Not (Get-ADUser -Server $ADServer -Filter {SamAccountName -eq $LoginName})) {
        # Attempt #1 for Dealing with passwords for people without a middle initial.
        IF([String]::IsNullOrEmpty($User.I)) {
            $AccountPass = '{0}{1}#{2}' -f @(
                $FirstName[0].ToString().ToUpper(),
                $LastName[0].ToString().ToLower(),
                $User.'Other ID')
            } Else {
            $AccountPass = '{0}{1}{2}#{3}' -f @(
                $FirstName[0].ToString().ToUpper(),
                $User.I[0].ToString().ToLower(),
                $LastName[0].ToString().ToLower(),
                $User.'Other ID')
            }
        $FirstName = $User.'Student First Name'
        $LastName = $User.'Student Last Name'
        $ADUserParams = @{
            Name = "$FirstName $LastName"
            SamAccountName = $LoginName
            GivenName = $FirstName
            Initials = $User.'I'
            Surname = $LastName
            DisplayName = "$FirstName $($User.'I') $LastName"
            Description= $SchoolCodes[$User.School].Name
            ScriptPath= "student.bat"
            UserPrincipalName = "$LoginName@academic.mydomain.k12.pa.us"
            EmailAddress = "$LoginName@mydomain.org"
            Company = "$LoginName@mydomain.org"
            EmployeeID = $User.'Other ID'
            HomeDirectory = "$FileServer\$LoginName"
            HomeDrive = "Z:"
            AccountPassword = (ConvertTo-SecureString -String $AccountPass -AsPlainText -Force)
            Enabled = $True
            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[$User.School].Name)
            Server = $ADServer
            WhatIf = $False
        } # End ADUserParams

        Try {
            # Create new user.
            New-ADUser @ADUserParams -Verbose -ErrorAction Stop
        }

        Catch {
            # If there's an error, write the error to the event log.
            Write-EventLog -LogName $EventLogName -Source $EventLogSources[0][1] -EntryType Warning -EventId $EventLogSources[0][0] -Message "Something went wrong with the creation of a new user, [$LoginName] : $_"
        }}}

第二次尝试绕过丢失的中间名首字母:

# 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 the user if the account doesn't already exist in AD.
ForEach ($User in $Users) {
    [String]$LoginName = $User.'Stu Access Login'
    If (-Not (Get-ADUser -Server $ADServer -Filter {SamAccountName -eq $LoginName})) {
        # Attempt #2 for Dealing with passwords for people without a middle initial.
        If ($User.I -ne "") {
            $AccountPass = 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

        } Else {
            $AccountPass = ConvertTo-SecureString -String (
                '{0}{1}#{2}' -f @(
                    $FirstName[0].ToString().ToUpper(),
                    $LastName[0].ToString().ToLower(),
                    $User.'Other ID')) -AsPlainText -Force
        } # End If
        $FirstName = $User.'Student First Name'
        $LastName = $User.'Student Last Name'
        $ADUserParams = @{
            Name = "$FirstName $LastName"
            SamAccountName = $LoginName
            GivenName = $FirstName
            Initials = $User.'I'
            Surname = $LastName
            DisplayName = "$FirstName $($User.'I') $LastName"
            Description= $SchoolCodes[$User.School].Name
            ScriptPath= "student.bat"
            UserPrincipalName = "$LoginName@academic.mydomain.k12.pa.us"
            EmailAddress = "$LoginName@mydomain.org"
            Company = "$LoginName@mydomain.org"
            EmployeeID = $User.'Other ID'
            HomeDirectory = "$FileServer\$LoginName"
            HomeDrive = "Z:"
            AccountPassword = $AccountPass
            Enabled = $True
            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[$User.School].Name)
            Server = $ADServer
            WhatIf = $False
        } # End ADUserParams

        Try {
            # Create new user.
            New-ADUser @ADUserParams -Verbose -ErrorAction Stop
        }

        Catch {
            # If there's an error, write the error to the event log.
            Write-EventLog -LogName $EventLogName -Source $EventLogSources[0][1] -EntryType Warning -EventId $EventLogSources[0][0] -Message "Something went wrong with the creation of a new user, [$LoginName] : $_"
        }}}

如果我运行ADUserParams,我可以看到AccountPassword 参数是System.Security.SecureString,所以我认为这是一件好事。那么,我做错了什么?我想这些方法中的任何一种都行得通——只要我把一切都做对了。但是,正如我所说,除非我恢复到无法处理没有中间首字母的帐户的旧代码,否则我无法进行身份验证。

【问题讨论】:

    标签: arrays variables active-directory powershell-5.0


    【解决方案1】:

    我觉得你的顺序有点不对。在定义它们之前,您正在使用变量 $FirstName$LastName 创建 $AccountPass

    这应该可以工作

    # 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 the user if the account doesn't already exist in AD.
    ForEach ($User in $Users) {
        [String]$LoginName = $User.'Stu Access Login'
        If (-Not (Get-ADUser -Server $ADServer -Filter {SamAccountName -eq $LoginName})) {
            $FirstName = $User.'Student First Name'
            $LastName = $User.'Student Last Name'
    
            # generate passwords
            If (!([String]::IsNullOrEmpty($User.I))) {
                # this person has an initial to use in the password
                $AccountPass = 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
            } 
            Else {
                # this person does not have an initial to work with
                $AccountPass = ConvertTo-SecureString -String (
                    '{0}{1}#{2}' -f @(
                        $FirstName[0].ToString().ToUpper(),
                        $LastName[0].ToString().ToLower(),
                        $User.'Other ID')) -AsPlainText -Force
            }
    
            $ADUserParams = @{
                Name = "$FirstName $LastName"
                SamAccountName = $LoginName
                GivenName = $FirstName
                Initials = $User.'I'
                Surname = $LastName
                DisplayName = "$FirstName $($User.'I') $LastName"
                Description= $SchoolCodes[$User.School].Name
                ScriptPath= "student.bat"
                UserPrincipalName = "$LoginName@academic.mydomain.k12.pa.us"
                EmailAddress = "$LoginName@mydomain.org"
                Company = "$LoginName@mydomain.org"
                EmployeeID = $User.'Other ID'
                HomeDirectory = "$FileServer\$LoginName"
                HomeDrive = "Z:"
                AccountPassword = $AccountPass
                Enabled = $True
                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[$User.School].Name)
                Server = $ADServer
                WhatIf = $False
            } # End ADUserParams
    
            Try {
                # Create new user.
                New-ADUser @ADUserParams -Verbose -ErrorAction Stop
            }
    
            Catch {
                # If there's an error, write the error to the event log.
                Write-EventLog -LogName $EventLogName -Source $EventLogSources[0][1] -EntryType Warning -EventId $EventLogSources[0][0] -Message "Something went wrong with the creation of a new user, [$LoginName] : $_"
            }}}
    

    【讨论】:

    • 附注对于组合显示名称,我认为这可能会更好:"$FirstName $($User.'I') $LastName".Trim() -replace '\s+', ' '。当没有$($User.'I') 时避免双空格
    • 哇!这正是为什么一双新的眼睛会派上用场的原因。我整天都在和这个作斗争。不敢相信我没有看到...谢谢您的帮助。而且,是的,当用户没有中间名首字母时,我将尝试找出一种干净的方法来清理显示名称,所以我也会尝试一下你的想法。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多