I'm using an IF statement to check if a computer might be domain joined before attempting to change the name of the computer. I have 2 blocks of code.
This block never has an issue on any Windows 7 or newer. But offers no checks before renaming.
#echo off
set /P "UserInput=Enter New Computer Name: "
wmic computersystem where name="%computername%" call Rename name="%UserInput%"
pause
But this block of code always exits in Error
#echo off
IF \\%computername%==%logonserver% (
echo \\%computername% == %logonserver%
set /P "UserInput=Enter New Computer Name: "
pause
wmic computersystem where name="%computername%" call Rename name="%UserInput%"
pause
) ELSE (
echo This computer may be DomainJoined contact your System Administrator
pause
)
The echo after comparison in the IF was strictly so I could verify the output. It was intended for debugging and added for clarity. This is the actual code with nothing omitted.
The Error is
ERROR:
Description = Invalid method Parameter(s)
If I force the comparison to fail. The ELSE statement runs. I don't believe the error is in the IF/ELSE
In order to remove the need to delay variable expansion, which is your issue, you could remove the need to include that portion of the code inside an If block:
#Echo Off
If /I Not "\\%COMPUTERNAME%"=="%logonserver%" (
Echo This computer may be DomainJoined; contact your System Administrator
Pause
Exit /B
)
Set /P "UserInput=Enter a new name for this computer: "
Pause
WMIC ComputerSystem Where "Not Name='%UserInput%'" Call Rename "Name='%UserInput%'"
Pause
You could also consider removing the If block completely by including an additional Where filter:
#Echo Off
Set /P "UserInput=Enter a new name for this computer: "
Pause
WMIC ComputerSystem Where "Not Name='%UserInput%' And Not Name='%logonserver:~2%'" Call Rename "Name='%UserInput%'"
Pause
The end user is free to type nothing or anything they wish; I would strongly advise that you perform some sort of validation on that input before considering renaming the system. Most certainly with respect to allowed naming conventions, disallowed characters, and even rude or offensive strings.
Related
There are things that we prefer not to understand in order to have an easier life to live.
But this is not something I can choose...
I made a batch file (or macro.doskey) to get the charset code. And it worked perfectly for a long time...
Basically it runs chcp:
> chcp
Code page active: 850
and then wraps the return before and after the colon
assigning what comes after to a variable:
FOR /F "tokens=1,* delims=:" %%s in ('CHCP') do (
#ECHO %%t
IF NOT "%1" == "" (SET %1=%%t)
)
For example:
> getCHCP.bat myVar
850
> ECHO %myVar%
850
However it started to lock, waiting for ENTER or displaying several echo messages. For example:
> getchcp myVar
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
850
I started to mix until I decided to change the ECHO %%t to ECHO %%s, and guess what?
No, is that the Bill Gates skull? Is it an easter egg from Microsoft? A virus?
No, none of that, this is just my autorun's welcome message.
This can be configured in
<[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]autorun>
In my case I called a batch file which, among other things, gives several echos showing this skull on the screen.
But the question is, why does it act like it reloads the autorun in background
when I've already opened the command prompt?
And why does it leave
everything in the buffer so that %%s pulls it again to the (Page code active) ':'?
And why are
you giving lots of ECHO is off on %%t when the only thing after
Code page active: is a number?
And the most important: How I solve it?
It's obvious, you already point to the problem.
this is just my autorun's welcome message.
This can be configured in
<[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]autorun>
The line FOR /F %%s in ('CHCP') ... start CHCP but that will be done in a NEW child cmd.exe instance.
And a NEW cmd.exe instance runs the autorun command!
Just before it starts your chcp.
You can disable the autorun at all, or add some code to detect the difference between a new cmd.exe instance for the user against a new instance from a FOR /F.
Put this code at the start of your autorun batch file
#echo off
setlocal EnableDelayedExpansion
REM *** ALWAYS make a copy of the complete CMDCMDLINE, else you destroy the originial!!!
set "_ccl_=!cmdcmdline!"
REM *** %1 contains only data, when the script itself was called from the command line
if "%~1" NEQ "" (
goto :direct_call
)
REM *** The check is necessary to distinguish between a new cmd.exe instance for a user or for a "FOR /F" sub-command
if "!_ccl_:~1,-2!" == "!comspec!" (
REM ***** INTERACTIVE ****
REM *** Show your skull or something else
)
exit /b
I have been fighting with this for 2 hours now. I need to set a variable from a second line output of a command. I found this code here at stackoverfglow:
for /f "skip=1delims=" %%a in (
'%SystemRoot%\System32\wbem\wmic.exe CSPRODUCT GET NAME'
) do set sid=%%a&goto next
The output for wmic.exe CSPRODUCT GET NAME is:
Name
PowerEdge T610
but when I run the batch file I get:
>set sid=PowerEdge T610
T610 was unexpected at this time.
I tried putting quotes everywhere.
I'm doing this script to check if the computer is a VirtualBox o VMware machine, the idea is to set a variable with the output of that command then compare it to "VirtualBox". But physical computers have product name with spaces.
THANKS!
I would offer the following method, as it will capture the full string without any potentially unwanted trailing space characters:
#For /F Tokens^=6Delims^=^" %%G In ('""%__AppDir__%wbem\WMIC.exe" CSProduct Get Name /Format:"MOF" 2>Nul"')Do #Set "SID=%%G"
Note: If you are using Windows 7, the use of some output formats may be broken, as the relevant .xsl stylesheets are located inside a language specific subdirectory which is not read by default. This issue can be worked around, by copying/moving or creating links to, all of the .xsl files one level higher, i.e. inside the wbem directory. (see potential alternative fix at the foot of this answer)
Alternatively, you could omit the for-loop completely, and instead of defining a variable, just use conditional statements:
#("%__AppDir__%wbem\WMIC.exe" CSProduct Where "Name Like '%%VirtualBox%%' Or Name Like '%%VMWare%%'" List Instance /Format:"List" 2>NUL|"%__AppDir__%find.exe" "__">NUL&&(Echo Virtual)||Echo Physical)&Pause
Note: In this example please ensure that you replace VirtualBox and/or VMWare as/if necessary. You can obviously replace the respective Echo commands with your chosen commands after testing.
Alternatively, for the actual process you need it for, based upon your comments, the following should also suffice:
#("%__AppDir__%wbem\WMIC.exe" ComputerSystem Where "Model Like '%%Virtual%%'" Get /Value 2>NUL|"%__AppDir__%find.exe" "=">NUL&&(Echo Virtual)||Echo Physical)&Pause
This should pick up a Hyper-V machine, (Model:Virtual Machine), a VMware machine, (Model:VMware Virtual Platform), and an Oracle VM, (Model:VirtualBox).
Here is a modified batch-file, which is intended to fix the potential Format issue in windows-7, as mentioned in my first example above:
#Echo Off
Set "XSL=MOF"
For /F "Delims==" %%G In ('"Set SID 2>NUL"')Do Set "%%G="
For /F "EOL=MDelims=" %%G In (
'""%__AppDir__%wbem\WMIC.exe" OS Get MUILanguages,Version 2>NUL"'
)Do For /F Tokens^=2^,4-5Delims^=.^"^ %%H In ("%%G"
)Do If %%I Equ 6 If %%J Equ 1 (Call :Target "%__APPDIR__%wbem\%%H\%XSL%"
)Else Call :Target "%XSL%"
Set SID 2>NUL&&Pause
GoTo :EOF
:Target
For /F Tokens^=6Delims^=^" %%G In (
'""%__AppDir__%wbem\WMIC.exe" CSProduct Get Name /Format:"%~1" 2>Nul"'
)Do Set "SID=%%G"
Line 9 is where you'd place your code, replacing mine which was added just for demonstration purposes.
Hi i wanted to change the value of hostname for new computer but things didn't work as i try to input the value and getting the value for the hostname. I try to restart the computer the result is still the same.. I am testing to see whether this script is capable of updating the hostname for pcs or computer name
thanks
here is my code
REM This script runs in MS-DOS Batch File Language
#echo off
set /p id= Enter ID or Hostname:
echo %id%
WMIC computersystem where caption='%ComputerName%' rename %id%
REM exit the applications
echo "Export completed successfully. Press any key to exit"
pause >nul
exit /B
Here's how I'd probably do it:
#Echo Off
Echo Your current name is %ComputerName%
:AskID
Set "ID="
Set /P "ID=Enter your new name: "
If Not Defined ID (Echo Can not be empty
GoTo AskID)
If /I "%ID%"=="%ComputerName%" Exit /B
If "%ID:~,1%"=="." (Echo Must not begin with a period
GoTo AskID)
Rem Put here some more checks for disallowed words or characters
WMIC ComputerSystem Where Name="%ComputerName%" Call Rename "%ID%"
Notes
This will need to be run 'As administrator'.
The change will not take effect until the next reboot.
It is important that you don't allow your end user, especially when running an administrative task to just enter anything at the prompt. Please consider following the Remarked line's advice.
I tested the below batch script to change the windows 10 hostname through batch script and it work perfectly fine try it out and reboot the system atlast !
set /p NEW_NAME="Please enter computer name: "
for /f %%i in ('hostname') do set OLD_NAME=%%i
echo %OLD_NAME%
echo %NEW_NAME%
WMIC computersystem where caption="%OLD_NAME%" rename "%NEW_NAME%"
pause
I am trying to create the interactive bat file which ask for the folder details it is able to take the userchoice but after that it is not able to set the folder path given by useri.e. it takes the path till Desktop only.Below is my code for the same:
#echo off
set /p UserInfo= "Do you have abc software(y/n)? "
echo %UserInfo% // here it is working as expected
IF %UserInfo%==y (
echo "Reply is true-----"
set /p Path= "Please enter path for abc directory? "
echo %Path% //but here it takes the path till the desktop only(C:\user\username\Desktop)
CD %Path%
dir
set /p Path1= "Please enter path1 directory path provided in package? "
echo %Path1% //but here it takes the path till the desktop only(C:\user\username\Desktop)
CD %Path1%
)
IF %UserInfo%==n (
echo "Reply is False**************"
)
pause
How to read the folder directive?
Hmm.. Please use the search bar as user Magoo, LotPings said.
Also, Stephan & Squashman mentioned, do not set a variable with the name path because there is a internal variable named path. If you rename it, other programs may not work properly.
What's DelayedExpansion?
When batch files are run, cmd process them line by line. The entire if statement get processed at once. That's why the variable are un-set.
Since we want cmd to process those variable at run-time, we will need to tell it to do so, by adding setlocal enableDelayedExpansion. This enables run-time variable expansion. To disable, just change enable to disable.
You may want to add it like so:
#echo off
setlocal enableDelayedExpansion
rem your code follows...
How To Make Variable Get Processed Run-Time?
Simply change %var% to !var!.
Please note that for loop metavariable %%n cannot be changed to !!n, since itself already implicated a delayed expansion.
Command-line arguments %n cannot be changed to !n. You may want to do this instead:
if "%var%"=="abc" (
set variable=%1
echo !variable!
)
SET /P Code Injection Cause Security Issue?!
If the input of %Userinput% is a==a format D:\ && echo, cmd sees:
if a==a
do format D:\
do echo ==y (
Which... formats your D drive. Adding quotes like if "%var%"=="abc" won't help since user can just escape the quote and execute the commands.
See here for more info.
SET /P Alternatives
You may want to consider CHOICE for single letter choice. It's command syntax is like so:
choice /c choices /n /cs /t timeout /d default_choice /m prompt
/n hides the list of options, letting /m to display it's own prompt
/cs == case-insensitive.
PATH Variable
Again mentioned above, PATH is a internal variable used by Windows and other programs. Mis-setting it may cause some Windows functions or programs to stop functioning properly.
Instead, use another variable name like programPath.
Okay here's another one.
So the idea for this batch uses two loops, but I feel like I lack the proper knowledge but here we go:
Batch code:
(Please be advised, that when user's are assigned computers, they are assigned by the description. Not my choice but anyway, it searches for computers owned by the description.)
#echo off
echo First and Last Name of User:
echo.
set /p name=
set desc="assigned to %name%"
echo.
dsquery computer domainroot -desc %desc%*
for /f "delims=," %%a in ('dsquery computer domainroot -desc %desc%*' ) do set CompName=%%a123
set CompName=%CompName:~4,-3%
pause
for /f "delims=" %u in ('wmic /node:%CompName% COMPUTERSYSTEM GET USERNAME^|find "\"') do set userfound=%~nxu
pause
The batch seems to break at the second loop. I feel as though maybe because the first loop that is assigned a variable, it won't allow for a second for /f command to run properly.
Any suggestions?