【问题标题】:Use variable in batch file multiple times在批处理文件中多次使用变量
【发布时间】:2015-12-16 11:47:33
【问题描述】:

我正在尝试编译一个批处理文件来获取当前用户的用户 ID,然后使用输出删除某个注册表项。

我发现这个是为了获取当前登录用户的 SID:

wmic useraccount where name='%username%' get sid

这很好用,给了我:

SID

S-1-5-21-XXXXX-XXXXX-XXXX-XXX

现在我想使用 S-1-5-21.... 等来删除当前登录用户的某个注册表项,所以 S-1-5-21 等。我该怎么做去做?还是有更简单的方法,能够确定当前 SID 并因此删除密钥?

谢谢!

【问题讨论】:

    标签: variables batch-file


    【解决方案1】:

    假设您要删除注册表项...

    HKEY_USERS\[SID-OF-USER]\test
    

    ...这个脚本应该删掉它:

    @ECHO OFF
    SET USERNAME=SomeUserName
    
    :: retrieve user's SID, store in file. NOTE: a user can have more than 1 SID.
    wmic useraccount where name='%USERNAME%' get sid | FINDSTR "^S-" > tmp.txt
    
    :: load result into variable. NOTE: this will load the first line only.
    SET /P SID_=<tmp.txt
    
    :: remove spaces which turned out to be appended at the end.
    SET SID=%SID_: =%
    
    :: delete key in the registry (will probably required elevated privileges)
    :: the /F causes reg.exe not to ask for confirmation
    REG DELETE "HKEY_USERS\%SID%\test" /F
    
    :: cleanup
    DEL tmp.txt
    

    我不知道“确定当前 SID 并删除密钥”的更简单方法。

    【讨论】:

    • 抱歉回复晚了,我对此做了一些小改动,效果很好!谢谢!
    【解决方案2】:

    试试这个:

    @echo off
    wmic useraccount where name='%username%' get sid > temp.txt &more temp.txt > temp2.txt &del temp.txt
    for /F "tokens=*" %%A in (temp2.txt) do set "userID=%%A"
    del temp2.txt
    echo %userID%
    pause
    

    您可以在此代码之后使用 %userID% 变量。

    请注意,由于 wmic 解析其输出的方式,您需要使用 more

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多