Skip to content

Instantly share code, notes, and snippets.

@n-fukuju
Created January 18, 2014 07:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n-fukuju/8487441 to your computer and use it in GitHub Desktop.
Save n-fukuju/8487441 to your computer and use it in GitHub Desktop.
PowerShellで、リモート端末にログオン中のユーザ名を取得する。 (PowerShell 2.0で確認)
$target = "対象のホスト名か、IPアドレス"
$logonUser = (Get-WmiObject Win32_ComputerSystem -ComputerName $target).UserName
# リモートアクセスの資格情報を明示的に指定する場合
$admin = "ユーザ名"
$pass = "パスワード"
$securePass = ConvertTo-SecureString -String $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($admin, $securePass)
# コンソールから入力するなら、PromptForCredentialを使った方が楽
# $credential = $host.UI.PromptForCredential("資格情報入力", "","","")
$logonUser = (Get-WmiObject Win32_ComputerSystem -ComputerName $target -Credential $credential).UserName
# ユーザ名をActiveDirectoryから取得したい場合
$domain = "ドメイン名"
$userId = $logonUser
# 取得したログオンユーザに、ドメイン名が付いている場合、外しておく
if($logonUser.Contains("\")){
$userId = $logonUser.Split("\")[1]
}
# .NETのSystem.DirectoryService名前空間を使用する
# ローカル環境にActiveDirectory向けのPowerShellモジュールがあるなら、そちらでもよいかも
[void][Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$path = "WinNT://{0}/{1}" -f $domain,$userId
$entry = New-Object System.DirectoryServices.DirectoryEntry($path)
# 必要なら資格情報を指定
# $entry = New-Object System.DirectoryServices.DirectoryEntry($path, $admin, $pass)
$userFullName = $entry.Properties["FullName"].Value.ToString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment