Created
January 18, 2014 07:34
-
-
Save n-fukuju/8487441 to your computer and use it in GitHub Desktop.
PowerShellで、リモート端末にログオン中のユーザ名を取得する。
(PowerShell 2.0で確認)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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