どうもミツシマです。

前回「Powershellコマンドでホスト名を変更する方法」を検証してみましたが、その続きとして今回はプラスαでドメイン参加を追加してみました。


検証環境は以下の通り
DC:Windows Server2016
PC:Windows10 1809


完成したスクリプト

Param(
    [switch]$Join
)


#=======================================================================
#Switchパラメータがない場合、ホスト名を変更して再起動(RunOnce仕込む)
#=======================================================================
Function ChangeComputerName{
    
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = '入力下さい'
    $form.Size = New-Object System.Drawing.Size(300,200)
    $form.StartPosition = 'CenterScreen'

    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Point(75,120)
    $OKButton.Size = New-Object System.Drawing.Size(75,23)
    $OKButton.Text = 'OK'
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $form.AcceptButton = $OKButton
    $form.Controls.Add($OKButton)

    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point(150,120)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = 'キャンセル'
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.CancelButton = $CancelButton
    $form.Controls.Add($CancelButton)

    $label = New-Object System.Windows.Forms.Label
    $label.Location = New-Object System.Drawing.Point(10,20)
    $label.Size = New-Object System.Drawing.Size(280,20)
    $label.Text = 'コンピュータ名を入力下さい'
    $form.Controls.Add($label)

    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Point(10,40)
    $textBox.Size = New-Object System.Drawing.Size(260,20)
    $form.Controls.Add($textBox)

    $form.Topmost = $true

    $form.Add_Shown({$textBox.Select()})
    $result = $form.ShowDialog()

    If($result -eq [System.Windows.Forms.DialogResult]::OK){
        $x = $textBox.Text
        Rename-Computer -NewName $x -Force  

        $RegRunOnceKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
        $Powershell = (Join-Path $env:windir "system32\cmd.exe")
        $RestartKey = "AutoADJoin"
$ScriptArgs = "/c `"powershell.exe -ExecutionPolicy RemoteSigned -command `"" + $ScriptFullPath + "`" -Join"
       
    #RunOnceキーにセット
        Set-itemproperty -path $RegRunOnceKey -name $RestartKey -value "$Powershell $ScriptArgs"

        $MessageText = ('PC名[' + $x + ']に変更しました.5秒後に再起動します')
        [System.Windows.Forms.MessageBox]::Show("$MessageText","通知")

        shutdown /r /t 5

    }else{
        [System.Windows.Forms.MessageBox]::Show("処理がキャンセルされました","通知")
    }
}


#=======================================================================


#=======================================================================
#Switchパラメータがある場合、ドメイン参加して再起動
#=======================================================================
Function AutoADJoin{

    $User = "MITSU\administrator"
    $Domain = "local.mitsushima.work"
    $PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force 
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord 

    Add-Computer -DomainName $Domain -Credential $Credential -Force
    
    $MessageText = ('ドメイン参加しました.5秒後に再起動します')
    [System.Windows.Forms.MessageBox]::Show("$MessageText","通知")

    shutdown /r /t 5

}
#=======================================================================

#=======================================================================
#管理者として実行しているかを確認し、管理者で実行されていなければ、管理者として再実行する
#=======================================================================
Function CheckRunAsAdministrator($PS1Path){
    $WindowsPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
    if (-Not($WindowsPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))){
        Write-Output "管理者として実行されていません。再度管理者で実行します。"
        Start-Process powershell.exe -ArgumentList "-ExecutionPolicy RemoteSigned -command $PS1Path" -Verb runas
        Exit
    }
}
#=======================================================================
#スクリプトのパス取得
$ScriptFullPath = $MyInvocation.MyCommand.Path

If($Join){
    $ScriptFullPath = $ScriptFullPath + " -Join"        

    CheckRunAsAdministrator $ScriptFullPath
    AutoADJoin

}else{
        
    CheckRunAsAdministrator $ScriptFullPath
    ChangeComputerName
}


〜解説〜

かなり長いスクリプトになってしまったが、大きく3つの関数を作成している。
CheckRunAsAdministrator」・「ChangeComputerName」・「AutoADJoin」である。
CheckRunAsAdministrator」では毎度おなじみの「管理者として実行しているかを確認し、ユーザー権限の場合には管理者として再実行させる」関数である。
ChangeComputerName」ではインプットボックスを表示させ入力したホスト名に変更後、レジストリのRunOnceキーに再度AD参加させるためにこのスクリプトを実行させるように値をセットしている。
AutoADJoin」は環境変数で設定したドメイン名・ユーザー名・パスワードから指定のドメインへPCを参加させる動きをしている。
これらを1つのスクリプトで実施するために、スクリプトの引数で「$Join」をスイッチとして「ChangeComputerName」と「AutoADJoin」を使い分けるようにparam(パラメータ)設定している。


実際、何度か検証してみたが「AutoADJoin」についてはユーザーがログイン直後にAD参加が実行される為か、失敗するケースがあった。
(起動直後で必要なサービス等が動いていないか、プロセスが同時起動していて処理出来なかったのか。。。。)
この辺りは本来、コマンドの結果を取得して通知すべきなのかもしれないが、
今回は疲れたので断念('д` ;)

今後の1つの課題として更に勉強しよう!!!
スポンサードリンク