Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell AD samAccountname脚本编写错误_Powershell_Active Directory - Fatal编程技术网

Powershell AD samAccountname脚本编写错误

Powershell AD samAccountname脚本编写错误,powershell,active-directory,Powershell,Active Directory,我正在尝试输入一个csv文件,其中包含用户的Givename和Lastname信息。当我运行下面列出的命令时,samAccountName不会给我预期的输出 请看下面,让我知道应该纠正什么 输入: GivenName,LastName,Password,TargetOU,Description,Manager Jeffrey,Terry,Pass12,"OU=Users,DC=mmc,DC=local",mmc user,knadella A,King,Pass13,"OU=Users,DC=m

我正在尝试输入一个csv文件,其中包含用户的Givename和Lastname信息。当我运行下面列出的命令时,samAccountName不会给我预期的输出

请看下面,让我知道应该纠正什么

输入:

GivenName,LastName,Password,TargetOU,Description,Manager
Jeffrey,Terry,Pass12,"OU=Users,DC=mmc,DC=local",mmc user,knadella
A,King,Pass13,"OU=Users,DC=mmc,DC=local",mmc user,knadella
Chris ,Charles,Pass14,"OU=Users,DC=mmc,DC=local",mmc user,knadella
命令:

$samAccountName = ($csvcontent.GivenName.Substring(0,1))+( $csvcontent.LastName)
电流输出:

J A C Terry King Charles
期望输出:

ATerry, AKing and CCharles 

请帮忙,谢谢

您正在一次性聚合所有详细信息,将
GivenName
列(
jac
)的结果与
LastName
列(
Terry King Charles
)的结果相结合`

这将在每个用户上循环:

foreach($user in $csvcontent){
    [array]$samAccountName += $user.GivenName[0] + $user.LastName
}
输出:

JTerry AKing CCharles

我会给你我每天用30次的东西。您创建它的方式将破坏一些登录选项

# <FirstLetterGivingName><LastName> for example
# WGates (William Gates)
 $sam = $_.GivenName.substring(0,1)+$_.Lastname
我也见过一些公司这样做,但建议不要这样做,因为用户很难记住登录名

$sam = $_.GivenName.substring(0,1)+$_.Lastname.substring(0,7)
这个脚本已经被使用了数千次,但在这篇文章中被编辑了一些

#Test to make sure your output looks correct
#You can do this by running the following:
#Import-csv ".\import_create_ad_users.csv" | Out-GridView

# ERROR REPORTING ALL
Set-StrictMode -Version latest
Import-Module ActiveDirectory

#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------

$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath = $path + ".\import_create_ad_users.csv"
$log = $path + ".\create_ad_users.log"
$date = Get-Date
$i = 1
#$addn = (Get-ADDomain).DistinguishedName
#$dnsroot = (Get-ADDomain).DNSRoot
$DNdom = Get-ChildItem -Path Ad:\ | where {$_.Name -eq "Configuration"}            
$addn = ($DNdom.DistinguishedName -split "," ,2)[1] 
$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$( (Get-WmiObject Win32_ComputerSystem).Domain)'"
$dnsroot = $wmiDomain.DomainName  + ".local"

#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
  Create-Users
}

Function Create-Users
{
  "Processing started (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object {
      If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
      {
        Write-Host "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n"
        "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n" | Out-File $log -append
      }
      Else
       {

        # Replace dots / points (.) in names, because AD will error when a 
        # name ends with a dot (and it looks cleaner as well)
        $replace = $_.Lastname.Replace(".","")
        If($replace.length -lt 4)
            {
            $lastname = $replace
            }
        Else
            {
            $lastname = $replace.substring(0,4)
            }
        # Create sAMAccountName according to this 'naming convention':
        # <FirstLetterInitialGivingName><LastName> for example
        # WGates (William Gates)
        $sam = $_.GivenName.substring(0,1)+$_.Lastname
        Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
        Catch { }
        If(!$exists)
            {
          # Set all variables according to the table names in the Excel 
          # sheet /import CSV. The names can differ in every project, but 
          # if the names change, make sure to change it below as well.
          $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force

          Try
          {
            Write-Host "[INFORMATION]`t User is now being built : $($sam)"
            "[INFORMATION]`t User is now being built : $($sam)" | Out-File $log -append
            New-ADUser $sam -path $_.TargetOU -GivenName $_.GivenName -Initials $_.Initials `
            -Surname $_.LastName -UserPrincipalName ($sam + "@" + $dnsroot) -DisplayName ($_.GivenName + " " + $_.LastName) `
            -Description $_.Description -Manager $_.Manager -AccountPassword $setpass -Enabled $TRUE -ChangePasswordAtLogon $TRUE
            Write-Host "[INFORMATION]`t Created a new user named : $($sam)"
            "[INFORMATION]`t Created new user named: $($sam)" | Out-File $log -append

             $dn = (Get-ADUser $sam).DistinguishedName

            # Rename the object to a good looking name
            $newdn = (Get-ADUser $sam).DistinguishedName
            Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
            Write-Host "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n"
            "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append

          }
          Catch
          {
            Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
          }
        }
        Else
        {
          Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
          "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
        }
      }
    Else
    {
      Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
      "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    }
    $i++
  }
  "Processing ended (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" + "`r`n" | Out-File $log -append
}


Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************`r`n"
Start-Commands
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"
#测试以确保输出正确无误
#您可以通过运行以下命令来执行此操作:
#导入csv“\Import_create_ad_users.csv”|输出GridView
#报告所有错误
设置StrictMode-最新版本
导入模块ActiveDirectory
#----------------------------------------------------------
#静态变量
#----------------------------------------------------------
$path=拆分路径-父级$MyInvocation.MyCommand.Definition
$newpath=$path+“\import\u create\u ad\u users.csv”
$log=$path+“\create\u ad\u users.log”
$date=获取日期
$i=1
#$addn=(获取ADDomain).distrignizedName
#$dnsroot=(获取ADDomain).dnsroot
$DNdom=Get ChildItem-Path Ad:\\其中{$\.Name-eq“Configuration”}
$addn=($DNdom.differentiedName-split“,”,2)[1]
$wmiDomain=Get-WmiObject Win32\u NTDomain-筛选器“DnsForestName=”$(Get-WmiObject Win32\u ComputerSystem.Domain)“”
$dnsroot=$wmiDomain.DomainName+“.local”
#----------------------------------------------------------
#启动功能
#----------------------------------------------------------
功能启动命令
{
创建用户
}
函数创建用户
{
处理已开始(在“+$date+”):|输出文件$log-追加
“--------------------------------------------------”|输出文件$log-追加
导入CSV$newpath | ForEach对象{
如果($.GivenName-eq“”)或($.LastName-eq“”)
{
写入主机“[ERROR]`t请提供有效的GivenName和LastName。已跳过对第$($i)`r`n行的处理
“[ERROR]`t请提供有效的GivenName和LastName。已跳过对第$($i)`r`n'|行文件$log-append的处理。”
}
其他的
{
#替换名称中的点/点(.),因为当
#名称以点结尾(看起来也更干净)
$replace=$\ Lastname.replace(“.”,“”)
如果($replace.length-lt 4)
{
$lastname=$replace
}
其他的
{
$lastname=$replace.substring(0,4)
}
#根据此“命名约定”创建sAMAccountName:
#比如说
#WGates(威廉·盖茨)
$sam=$\u.GivenName.substring(0,1)+$\u.Lastname
请尝试{$exists=Get ADUser-LDAPFilter“(sAMAccountName=$sam)”}
捕获{}
如果(!$存在)
{
#根据Excel中的表名设置所有变量
#工作表/导入CSV。每个项目的名称可能不同,但
#如果名称更改,请确保在下面也更改名称。
$setpass=converttoSecureString-AsPlainText$\密码-force
尝试
{
写入主机“[信息]`t正在生成用户:$($sam)”
“[信息]`t用户现在正在生成:$($sam)”|输出文件$log-追加
新ADUser$sam-path$\ u0.TargetOU-GivenName$\ u0.GivenName-Initials$\ u0.Initials`
-姓氏$\.LastName-UserPrincipalName($sam+“@”+$dnsroot)-DisplayName($\.GivenName++++$\.LastName)`
-Description$\.Description-Manager$\.Manager-AccountPassword$setpass-Enabled$TRUE-ChangePasswordAtLogon$TRUE
写入主机“[INFORMATION]”未创建名为:$($sam)的新用户
“[信息]`t已创建名为:$($sam)的新用户”|输出文件$log-追加
$dn=(获取ADUser$sam).DiscrimitedName
#将对象重命名为好看的名称
$newdn=(Get ADUser$sam).DiscrimitedName
重命名ADObject-Identity$newdn-NewName($\ GivenName++$\ LastName)
写入主机“[INFORMATION]`t将用户$($sam)重命名为$($\u.GivenName)$($\u.LastName)`r`n”
“[INFORMATION]`t将用户$($sam)重命名为$($.GivenName)$($.LastName)`r`n'`Out文件$log-append”
}
抓住
{
写入主机“[ERROR]`t哦,出了点问题:$($\ux.Exception.Message)`r`n”
}
}
其他的
{
写入主机“[SKIP]`t User$($sam)($($.GivenName)$($.LastName))已存在或返回错误!`r`n”
“[SKIP]`t User$($sam)($($.GivenName)$($.LastName))已存在或返回错误!”|输出文件$log-追加
}
}
其他的
{
写入主机“[SKIP]`t将跳过用户($($.GivenName)$($.LastName))进行处理!`r`n”
“[跳过]`t用户($($.GivenName)$($.LastName))将被跳过以进行处理!”|输出文件$log-追加
}
$i++
}
处理已结束(在“+$date+”):|输出文件$log-追加
“--------------------------------------------------”+“`r`n”|输出文件$log-append
}
编写主机“*************************脚本已启动********************************”
编写主机“*************************脚本已启动********************************”
写入主机“*******************************脚本已启动******************************************************`r`n”
启动命令
编写主机“**********************脚本已完成”
#Test to make sure your output looks correct
#You can do this by running the following:
#Import-csv ".\import_create_ad_users.csv" | Out-GridView

# ERROR REPORTING ALL
Set-StrictMode -Version latest
Import-Module ActiveDirectory

#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------

$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath = $path + ".\import_create_ad_users.csv"
$log = $path + ".\create_ad_users.log"
$date = Get-Date
$i = 1
#$addn = (Get-ADDomain).DistinguishedName
#$dnsroot = (Get-ADDomain).DNSRoot
$DNdom = Get-ChildItem -Path Ad:\ | where {$_.Name -eq "Configuration"}            
$addn = ($DNdom.DistinguishedName -split "," ,2)[1] 
$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$( (Get-WmiObject Win32_ComputerSystem).Domain)'"
$dnsroot = $wmiDomain.DomainName  + ".local"

#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
  Create-Users
}

Function Create-Users
{
  "Processing started (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object {
      If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
      {
        Write-Host "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n"
        "[ERROR]`t Please provide valid GivenName and LastName. Processing skipped for line $($i)`r`n" | Out-File $log -append
      }
      Else
       {

        # Replace dots / points (.) in names, because AD will error when a 
        # name ends with a dot (and it looks cleaner as well)
        $replace = $_.Lastname.Replace(".","")
        If($replace.length -lt 4)
            {
            $lastname = $replace
            }
        Else
            {
            $lastname = $replace.substring(0,4)
            }
        # Create sAMAccountName according to this 'naming convention':
        # <FirstLetterInitialGivingName><LastName> for example
        # WGates (William Gates)
        $sam = $_.GivenName.substring(0,1)+$_.Lastname
        Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
        Catch { }
        If(!$exists)
            {
          # Set all variables according to the table names in the Excel 
          # sheet /import CSV. The names can differ in every project, but 
          # if the names change, make sure to change it below as well.
          $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force

          Try
          {
            Write-Host "[INFORMATION]`t User is now being built : $($sam)"
            "[INFORMATION]`t User is now being built : $($sam)" | Out-File $log -append
            New-ADUser $sam -path $_.TargetOU -GivenName $_.GivenName -Initials $_.Initials `
            -Surname $_.LastName -UserPrincipalName ($sam + "@" + $dnsroot) -DisplayName ($_.GivenName + " " + $_.LastName) `
            -Description $_.Description -Manager $_.Manager -AccountPassword $setpass -Enabled $TRUE -ChangePasswordAtLogon $TRUE
            Write-Host "[INFORMATION]`t Created a new user named : $($sam)"
            "[INFORMATION]`t Created new user named: $($sam)" | Out-File $log -append

             $dn = (Get-ADUser $sam).DistinguishedName

            # Rename the object to a good looking name
            $newdn = (Get-ADUser $sam).DistinguishedName
            Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
            Write-Host "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n"
            "[INFORMATION]`t Renamed the user $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append

          }
          Catch
          {
            Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
          }
        }
        Else
        {
          Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
          "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
        }
      }
    Else
    {
      Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
      "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    }
    $i++
  }
  "Processing ended (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" + "`r`n" | Out-File $log -append
}


Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************"
Write-Host "***************************SCRIPT HAS STARTED***************************`r`n"
Start-Commands
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"
Write-Host "***************************SCRIPT HAS FINISHED***************************"
$samAccountName = $csvcontent | % {
($_.GivenName.Substring(0,1))+($_.LastName)
}