Home > Blockchain >  batch coding to pipe through folder with spaces
batch coding to pipe through folder with spaces

Time:02-02

I am currently trying to pipe through spaces with my admin account. I am currently on my normal userid but I am running batch script as admin to pipe through the current userid but the user id come with spaces. My userid is johnny tan, how can I echo the user id exactly to johnny tan instead of johnny only?

for /F "tokens=1,2" %%i in ('qwinsta /server:%COMPUTERNAME% ^| findstr "console"') do set userid=%%j

echo %userid%

CodePudding user response:

Replace two consecutive SPACEs by a character that should not occur in user IDs (like |), split the string using this as delimiter and remove a potentially leading SPACE to extract the user ID:

@echo off
rem // Capture the line of interest from the `qwinsta` command line:
for /F delims^=^ eol^= %%J in ('qwinsta /SERVER:%ComputerName% ^| findstr "^.console"') do (
    rem // Store line, and toggle delayed expansion to avoid issues with `!`:
    set "LINE=%%J" & setlocal EnableDelayedExpansion
    rem /* Replace `  ` (two spaces) with `|`, assuming both do not occur in user IDs,
    rem    then extract the second token from the altered string, which is the user ID: */
    for /F "tokens=2 delims=| eol=|" %%I in ("!LINE:  =|!") do (
        rem // Split off a potentially remaining leading ` ` (space):
        endlocal & for /F "tokens=* eol= " %%H in ("%%I") do @set "userid=%%H"
    )
)
set "userid"

This should even work for user IDs like Johnny Fitzpatrick Tan.

CodePudding user response:

Test to see if the 3rd token is a number, if not, it means it is not the ID field and therefore it will use both meta variables %%j and %%k. If it is a number though, it means it is the ID field and we only use %%j as the username.

@echo off
for /F "tokens=1-3*" %%i in ('qwinsta /server:%COMPUTERNAME% ^| findstr "console"') do (
    echo %%k| findstr /vr "^[0-9][0-9]*$" >nul 2>&1 && set "userID=%%j %%k" || set "userID=%%j"
)
echo %userID%
  •  Tags:  
  • Related