0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

csvファイルをインポートして複数ユーザのADパスワードを変更するPowerShellスクリプト

Posted at

csvファイルをインポートして複数ユーザのADパスワードを変更するPowerShellスクリプトを作成してみました。

1.環境

Windows10

2.スクリプト

users.csv
sAMAccountName;NewPassword
hogehoge1;hogepw1
hogehoge2;hogepw2
chage_ad_password.ps1
import-module activedirectory

$ADUserID = 'domain\domainadmin'

$ADPW = "password"

$ADServer = "11.22.33.44"

$SecurePassword = ConvertTo-SecureString -String $ADPW -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($ADUserID, $SecurePassword)

# ログの出力先
$LogPath = ".\"

# ログファイル名
$LogName = "chage_ad_pw_ExecuteLog"
$LogFile = $LogName + ".log"
# ログファイル名
$LogFileName = Join-Path $LogPath $LogFile

#CSVファイル指定
$users = "C:\work\users.csv"

function PrintMsg(
            $LogString
            ){

    $Now = Get-Date

    # Log 出力文字列に時刻を付加(YYYY/MM/DD HH:MM:SS.MMM $LogString)
    $Log = $Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + " "
    $Log += $LogString

    # ログファイル名が設定されていなかったらデフォルトのログファイル名をつける
    if( $LogName -eq $null ){
        $LogName = "LOG"
    }

    # ログファイル名(XXXX_YYYY-MM-DD.log)
#    $LogFile = $LogName + "_" +$Now.ToString("yyyy-MM-dd") + ".log"

    # ログフォルダーがなかったら作成
    if( -not (Test-Path $LogPath) ) {
        New-Item $LogPath -Type Directory
    }

    # ログ出力
    Write-Output $Log | Out-File -FilePath $LogFileName -Encoding Default -append

    # echo させるために出力したログを戻す
    Return $Log
}

PrintMsg ("ADパスワード変更処理開始")

try {
#ADパスワード変更処理

Import-Csv $users -Delimiter ";" | `
Foreach { 
    $NewPass = ConvertTo-SecureString -AsPlainText $_.NewPassword -Force
    $ad_id = $_.sAMAccountName
    $ad_pw = $_.NewPassword
    $naiyou = "アカウント名: " + $ad_id + " パスワード: " + $ad_pw + " で設定します。"
     Write-Output $naiyou | Out-File -FilePath $LogFileName -Encoding Default -append
     Write-Output $naiyou
    Set-ADAccountPassword -Identity $_.sAMAccountName -NewPassword $NewPass -Reset -PassThru -Server $ADServer -Credential $Credential | Set-ADUser -ChangePasswordAtLogon $false | Tee-Object -FilePath $LogFileName -append
}

} catch {
PrintMsg ("ADパスワード変更処理に失敗しました")
PrintMsg ($error[0])
}

PrintMsg ("ADパスワード変更処理終了")

3.スクリプトの実行

chage_ad_password.ps1

ADのパスワードが変更され、実行ログ(chage_ad_pw_ExecuteLog.log)が出力されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?