本文目录导读:

Windows (PowerShell)
# 获取当前用户名 $env:USERNAME # 或使用 whoami 命令 whoami # 获取完整用户信息 [System.Environment]::UserName # 获取当前Windows用户 [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Windows (CMD/Batch)
@echo off echo %USERNAME% REM 或使用 whoami whoami
Linux/macOS (Bash)
#!/bin/bash # 获取当前用户名 echo $USER # 或使用 whoami whoami # 或使用 id 命令 id -un # 获取完整的用户信息 logname
Python (跨平台)
import getpass
import os
# 方法1:使用 getpass
current_user = getpass.getuser()
print(f"当前用户: {current_user}")
# 方法2:使用 os
current_user = os.getlogin()
print(f"当前用户: {current_user}")
Node.js
const os = require('os');
// 获取当前用户
const user = os.userInfo();
console.log('用户名:', user.username);
console.log('用户完整信息:', user);
PowerShell (获取更多信息)
# 获取当前用户详细信息 $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() $currentUser.Name $currentUser.User # 获取用户所属组 $currentUser.Groups # 检查是否是管理员 ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
实用技巧
Windows 环境变量
echo %USERNAME% %USERPROFILE% %USERDOMAIN%
Linux 环境变量
echo $USER echo $HOME echo $LOGNAME
检查管理员权限
PowerShell:
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) Write-Host "是否为管理员: $isAdmin"
Bash:
if [ "$EUID" -eq 0 ]; then
echo "当前为root用户"
else
echo "当前为普通用户"
fi
选择哪种方法取决于你的操作系统和使用的脚本语言。whoami 命令在 Windows 和 Linux 上都可用,是最简单的跨平台选项。