You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Git Bash的Shell脚本中获取Windows当前用户全名?

在Git Bash脚本中获取Windows当前用户全名的方法

问题背景

公司电脑禁用PowerShell,仅能使用Command Prompt和Git Bash,需在Git Bash的Shell脚本中获取Windows当前用户的全名,此前尝试两种方法均失败:

失败方法1:net user配合find命令

测试命令:

MSYS_NO_PATHCONV=1 net user %USERNAME% /domain |find /I "Nome completo"

报错信息:

find: ‘/I’: No such file or directory
find: ‘Nome completo’: No such file or directory
Could not find username.

For more info, type NET HELPMSG 2221.

失败方法2:Perl的Win32API::Net模块

测试命令:

perl -MWin32API::Net -E "Win32API::Net::UserGetInfo('',Win32::LoginName(), 10, my $info = {} ); say $info->{fullName}"

报错信息:

Can't locate Win32API/Net.pm in @INC (you may need to install the Win32API::Net module) (@INC contains: /usr/lib/perl5/site_perl /usr/share/perl5/site_perl /usr/lib/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib/perl5/core_perl /usr/share/perl5/core_perl).
BEGIN failed--compilation aborted.

可行解决方案

方案1:修正net user命令调用逻辑

Git Bash默认的find是Unix版本,需通过cmd /c调用Windows原生find命令,同时调整Shell变量语法:

# 英文系统用"Full Name",中文系统替换为"全名"
cmd /c "net user $USERNAME /domain | find /I \"Full Name\""

如果需要提取纯全名文本(去除前缀),可进一步处理:

full_name=$(cmd /c "net user $USERNAME /domain | find /I \"Full Name\"")
full_name=${full_name#*:}  # 去掉"Full Name:"前缀
full_name=$(echo "$full_name" | xargs)  # 清除前后空格
echo "$full_name"

方案2:使用Perl自带模块(无需额外安装)

利用Git Bash Perl自带的Win32::OLE调用Windows WMI查询用户信息,无需安装额外模块:

perl -MWin32 -E 'use Win32::OLE; $wmi = Win32::OLE->GetObject("winmgmts:"); foreach ($wmi->InstancesOf("Win32_UserAccount")) { if ($_->Name eq Win32::LoginName()) { print $_->FullName."\n"; last; } }'

内容的提问来源于stack exchange,提问作者Oo'-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:05:42