want to make sure this code will remove a specific website from hosts file, unblocking it.
pushd %SystemRoot%\system32\drivers\etc\hosts
copy hosts hosts.bak
findstr /v /c:"drive.google.com" hosts.bak > hosts
popd
And if not then what I can use in a batch file to remove specific websites from hosts file.
If in doubt about potentially removing something then the following code, which utilises powershell from within your batch file, will just comment out any matching lines. (Edit SiteList as appropriate).
#Echo Off
Set SiteList="drive.google.com" "microsoft.com" "dostips.com" "stackoverflow.com"
For %%A In (%Sitelist%) Do Call :Sub %%A
Exit/B
:Sub
#Powershell "(Get-Content """$($env:windir)\System32\drivers\etc\hosts""") -replace ('^\s*127.0.0.1\s*%~1','#127.0.0.1 %~1') | Out-File """$($env:windir)\System32\drivers\etc\hosts""" -Force"
Because the hosts file is located in a protected area of your system you will need to Run as administrator.
The method is as used in the link kindly provided by Hackoo in the comments section, but due to your batch-file tag and your stated lack of knowledge I have provided this as an alternative.
It is also worth noting that some hosts use 0.0.0.0 instead of 127.0.0.1, so you may need to adjust the code accordingly.
Related
I just created simple batch script. I want to run uninstall.exe with switches like "-q" "-splash Uninstall"
Here is the code;
#echo off
echo This script will uninstall some features.
pause
SET path=C:\Program Files\Program\uninstall.exe -q -splash Uninstall
START "" "%path%"
pause
If I run this code it gives an error:
Windows cannot find 'C:\Program Files\Program\uninstall.exe -q -splash Uninstall'
Make sure you typed the name correctly, and then try again.
If I remove switches, uninstall process starts normally.
So how can I use this swtiches in a batch file?
As an aside, don't use path as an arbitrary choice of variable name. It has a special significance in Windows (and Unix-derived systems too).
Your main problem is that you are including the switches in your quoted string, which is then treated as a whole as the executable filename. Put your quotes only around the filename, and leave the switches outside:
SET command="C:\Program Files\Program\uninstall.exe" -q -splash Uninstall
START "" %command%
(The only reason for the quotes is the fact that the pathname contains spaces.)
Also, you don't really need to use a variable at all, but I've used one since you used one.
I'm not quite sure if every program you come across will have a uninstall.exe file waiting for you in the C:\Program Files(place program name here)\ directory. Even if it does, you will probably have to control it from the GUI. However, looking at another stack overflow thread here, I would like to credit the users Bali C. and PA. for coming up with a possible solution to uninstall files using a batch file by using the registry key to find an uninstall file for windows programs. I will re-paste PA.'s code below:
#echo off
for /f "tokens=*" %%a in ('reg query hklm\software\Microsoft\Windows\CurrentVersion\Uninstall\ ^| find /I "%*"') do (
for /f "tokens=1,2,*" %%b in ('reg query "%%a" /v UninstallString ^| find /I "UninstallString"') do (
if /i %%b==UninstallString (
echo %%d
)
)
)
This code will find the uninstall file for a specific program from the registry, and then it will print out the command needed to run the uninstall file. Remove the 'echo' to just run these commands when you are sure they are correct. However, even this will probably require using the program's uninstall GUI. I don't think this would be terribly inefficient. Is there any other specific reason you want to use a batch file besides efficiency?
I hope this helps!
I've gotten excellent help here recently, which I keenly appreciate. Thanks to the breadth of knowledge on this site I've been able to cobble together some code which is trivial in its purpose, yet important for my environment.
The simplified purpose, and my problem:
The goal: for the current user, upon login to Windows, move all files and folders into a desktop folder named "Archive" [create the latter if necessary]. (The content moved is put into a dynamically created subfolder based on timestamp.)
The existing problem: the code fails to move desktop folders into the (deskstop) Archive folder. (I obviously don't want to move the Archive folder itself.)
Any insight / solution would be hugely helpful. (PS if at all possible I wish to keep to DOS bat files vs more complex languages.)
My current .BAT file [note- the many variables are for initial debugging]:
++++++++++++++++++++++++++++
:: Establish desired base name for the primary desktop archive folder
set ARCH=Archives
:: Establish logged in user path to desktop
set G=%USERPROFILE%\Desktop
:: Now, if "Archives" folder does not yet exist on desktop, create it
if not exist "%G%\Archives" mkdir "%G%\%ARCH%
:: Consolidate pathname <user\desktop\Archives> into single variable (TARGET)
set TARGET=%G%\%ARCH%
:: Create [date+time specific] subfolder name -- two steps - build string, then assign
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
:: Set variable to hold new name Archives\Saved-<time-specific-subfolder> in final form
set "savedirname=Saved-%YYYY%-%MM%-%DD%-%HH%-%Min%-%Sec%"
:: Finally, append new foldername to user-specfic path (TARGET)
set MoveTo=%TARGET%\%savedirname%
:: Create final targeted destination folder - complete pathname
mkdir %MoveTo%
:: Move all desktop files/folders EXCEPT the Archives folder into the targeted destination
for %%i in (%G%\*.*) do move %%i %MoveTo%
Thank you!
(PS if at all possible I wish to keep to DOS bat files vs more complex languages.)
This isn't the answer you ask for, but this is PowerShell (v4) code to do what your code does:
$arch = "Archives"
$desktop = [Environment]::GetFolderPath("Desktop")
$saveDirName = Get-Date -f "yyyy-MM-dd-hh-mm-ss"
$target = "$desktop\$arch\$saveDirName"
mkdir $target -Force
dir $desktop | where Name -ne $arch | Move-Item -Destination $target -Force
Is it really "more complex" than your original code?
Your original code guesses that %USERPROFILE%\Desktop is the desktop - that's incorrect if the desktop is redirected, it could be \\fileserver\users\username\desktop\. It's incorrect if the OS is installed in a foreign language, in Swedish it's %UserProfile%\Skrivbord. Asking Windows where the desktop is gets the correct location every time. My code does this.
PowerShell handles dates sanely. No string manipulation, no WMI calls, one formatting string for what format you want.
I use the mkdir -Force option, it can make folders two levels deep in one go, and it does nothing if they already exist. No need for IF NOT EXIST... tests, although you could do them with Test-Path. You could use this approach in the batch file, mkdir can make multiple nested folders there, too.
NB. your code has a bug where you check for "%G%\Archives" but you mkdir "%G%\%ARCH%. If %ARCH% is meant to be configurable, they could differ.
And this version does the folder moving which you are asking about that your code doesn't yet do, and will need another abuse of a for loop to handle.
This script is half the amount of code, more readable because it directly does what it needs instead of wandering out to wmi and string manipulation and for loops for string handling, it's more correct in more situations, more resilient, and does the extra things your original doesn't.
Yes it's a bigger and more complex language - that's how it makes things easier for you, because it can do more things directly.
set fldr="%userprofile%\desktop\archive\%date:/=%%time::=%"
md %fldr%
For /f "delims=" %A in ('dir /a-d /b "%userprofile%\desktop" ^| Findstr /I /v /c:"archive"') Do #echo move "%userprofile%\desktop\%A" %fldr%
The above is all you need.
Batch isn't a programming language, although IBM engineers added programming like features.
It designed for copying files and starting programs. It becomes a stupid language if used as a programming language.
Use %%A in a batchfile. Remove Echo to have it actually move files.
To get the doc folder, which is always called desktop (explorer substitutes localised names for real names via the desktop.ini file)
for /f "skip=2 tokens=3" %A in ('Reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Personal"') do set doc=%A
Use %%A in a batchfile.
I'm a mortgage loan guy in Seattle, WA and I frequently set up a folder hierarchy into which I save a client's documents and as they come in to me. I've been creating these manually for years and I'd like to save the 3 to 4 minutes it takes to set these up by using a batch file.
So... I have a default set of folders, some of which contain a couple of small Adobe PDFs. What I'd like to do (and cannot make happen) is to run a batch file that would facilitate some custom remarks or input from me during the batch so that with a click and a couple of keystrokes, I have an organized folder setup for a new client within seconds rather than minutes.
I've written the following but it isn't producing any output folders or files.
______not sure character terms show correctly - see linked images below for actual______
#echo off
::Ask
echo Your Source Path:
set INPUT1=
set /P INPUT1=Type input:
echo Your Destination Path:
set INPUT2=
set /P INPUT2=Type input:
C:\WINDOWS\system32\xcopy.exe /e /v %INPUT1% %INPUT2%
My responses were:
to the first prompt "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014"
to the second prompt "E:\DV8333 MY DOCUMENTS\001 CLIENTS\"
I have verified that xcopy.exe is in fact located as indicated above.
I'm on XP SP3
My actual paths and .bat file are shown in the linked image for clarity.
http://www.avidrecording.com/images/01.png
Thanks in advance, much appreciated.
#Rem save this as a .bat file and run
#echo off
set /P source=Enter Source Folder:
echo %Source%
set /P destination=Enter Destination Folder:
echo %destination%
xcopy %source% %destination% /v /i /e
Fundamentally, your problem appears to be that the xcopy command can't figure out which of the data it is receiving is parameters and which switches and which superfluous because you have spaces in your directorynames.
Fortunately, the cure is simple. "quote your parameters"
C:\WINDOWS\system32\xcopy.exe /e /v "%INPUT1%" "%INPUT2%"
Now - the path to xcopy.exe is probably superfluous - as is the extension, so
xcopy /e /v "%INPUT1%" "%INPUT2%"
is more than likely all you'd need.
(I'd caution to experiment with a throw-away destination until you've perfected your method. I use a RAMDISK...)
Also, if you're copying a template, then there's no apparent reason for all the folderol about inputting Input1. If you have more than one template set, set up a separate batch and shortcut for each one with a fixed template path, eg
xcopy /e /v "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014" "%INPUT2%"
Note the use of quotes to defeat the evil spaces.
Next, your destination could be built, but may contain spaces. For instance, you may have a client to which you wish to refer as "037 - Fred Nurk". Now it's a pain to have to type in the full path, so make it easy. Just type in the 037 - Fred Nurk part and let batch fill in the rest.
xcopy /e /v "E:\DV8333 MY DOCUMENTS\002 ATLAS\ATLAS RESOURCES\000NEWCLIENTFOLDER2014" "E:\DV8333 MY DOCUMENTS\001 CLIENTS"\"%input2%"\
Note that this will append the input as a directory under E...001 clients. Note that the strings are concatenated and the double-quotes are there solely to tell batch "here be a string that may contain spaces."
If this works, and there's no reason why it wouldn't (does for me...) then all you'd need to do is enter the client details and the template would be copied to a new directory. Now actually playing around with the data in the files that are copied so that they are customised - well, at the price, that would be worthy of another question...
#echo off
echo Backing up file
set /P source=Enter source folder:
set /P destination=Enter Destination folder:
set /P Folder name=Enter Folder name
set xcopy=xcopy // Set the switches as per your need
%xcopy% %source% %destination%
pause
My goal is to write a batch script that will delete all of the cache names from a particular cache server.
The code I wrote below errors because it cannot execute the AppFabric PowerShell commands. It returns "Remove-Cache -CacheName blahblah" is not a recognized as an internal or external command.
I guess what I need to figure out and I need help from you guys is how can I use the shell script FOR /F command but yet be able to execute AppFabric PowerShell commands.
I tried adding the line:
powershell.exe -noexit -command "Import-Module DistributedCacheAdministration;Use-CacheCluster"
in the beginning of the batch script to first bring up the PowerShell window, import the AppFabric module and then run the batch script. But because PowerShell doesn't recognize FOR /F, it bombs there. I'm trying to delete multiple cachenames, but I'm just too not advanced enough to do it. HELP!
:
#echo off
REM using PING and batch line retrieval... only IP address info is called out from ping request
FOR /F "tokens=2,3" %%A IN ('ping %computername% -n 1 -4') DO IF "from"== "%%A" set "IP=%%~B"
echo %IP:~0,-1%
REM GET-CacheClusterHealth > C:\output.txt
REM FIND /n /i "NamedCache" C:\output.txt > C:\results.txt
FOR /F "tokens=4" %%i in (C:\results.txt) DO "Remove-Cache -CacheName %%i"
DEL "C:\output.txt"
DEL "C:\results.txt"
ECHO ALL Cache names have been deleted from Cache Server %IP:~0,-1%
Pause
To be honest it looks like you are making this way more complicated than it needs to be. PowerShell is the way things are moving so you may want to look into how it works a bit more. What you probably need is something along the lines of (kind of pseudo-code since I don't have the actual cmdlet to reference):
Import-Module DistributedCacheAdministration
Use-CacheCluster
$ServerName = "SomeServer01"
$ServerPort = "22233"
Get-Cache -HostName $ServerName -CachePort $ServerPort | ForEach{Remove-Cache $_.CacheName}
Now I don't know what is returned from Get-Cache but I imagine that it returns an array of things and from looking at your script one of the properties is NamedCache, which is what you want to work with. The above example would import the module needed to perform the commands. Then it sets the cache cluster to the current host, assign a variable to the name of a server that you want to work with, and then another variable to the port for it. Lastly it performs the Get-Cache command against the specified host and port, and sends the results of that to a ForEach loop that performs the Remove-Cache command against all of the items returned's NamedCache property. As I said before I assume it returns an array of objects which contain a NamedCache property.
As for FOR /F in PowerShell, what you could do if you really want to go that route is something like:
Get-Content Results.txt | ForEach{Remove-Cache -CacheName $_.Split(" ")[3]}
That gets the contents of the file, and then for each line it splits that line at each space, and references the 4th item (PowerShell's Split method will turn the string into an array of strings, and since arrays start at record 0 in PowerShell [3] references the 4th string in the array).
In C you can use %username% as a variable for the current user's name for directory listings and such: c:\documents and settings\%username%\
Is there something like this for a batch script?
Using just %username% doesn't seem to help.
I wrote a script that accesses my FTP server so I can load files to the server.
I want my friends to be able to use this script, but I don't want to have to write several different scripts.
Here is what I have so far:
#echo off
#ftp -s:"%~f0" &GOTO: EOF
open FTP.server.com
user
pass
cd /home/ftp
bin
lcd "c:\documents and settings\%username%\my documents\FTP"
mput *txt
pause
bye
There's gotta be a way
This can be done if you change the batch file so that it creates a script file every time the batch file runs. You can do this by using the echo command to write the script lines to script file, which you can then pass to the ftp command. The reason this works is that echo will expand the %username% variable before writing it to the script file:
#echo off
del script.txt
echo open FTP.server.com>>script.txt
.
[echo rest of script lines to file]
.
echo lcd "c:\documents and settings\%username%\my documents\FTP">>script.txt
echo echo mput *txt>>script.txt
#ftp -s:script.txt
I believe i found a better way, although it's a bit more code.
set "rootdir=%userprofile%\my documents"
set "destdir=c:\
for /f "delims=" %%a in ('dir /b /s "%rootdir%*.txt"') do copy "%%~a" "%destdir%"
And then the usual FTP stuff, including lcd c:\
Ive tested this and it works, although I would like to find a simpler way.
I tried using xcopy but for some reason it doesn't work on my system, the cmd screen just hangs.
Also tried just using copy, but that gave me "can't find file" errors.
Instead of using lcd, a better idea might be to change the working directory in the outer batch file.
#echo off
#pushd "c:\documents and settings\%username%\my documents\FTP"
#ftp -s:"%~f0" &GOTO: EOF
open FTP.server.com
user
pass
cd /home/ftp
bin
mput *txt
#pause
The only problem with this solution, is that the script itself is no longer in the working directory, and so you need to add a path for that. (Or, put it in the FTP folder ;)
Also, minor pedantry, but this is not actually a correct way to find My documents. In particular, on Vista or Windows 7, User profiles are stored in C:\Users. And, it's possible for users to move My Documents (on my computer, My Documents is located in D:\Mike's Documents)
However, there doesn't appear to be an environment variable that points directly at My Documents, so you will have to make do with this:
"%userprofile%\my documents\FTP"
If the people running this script are running XP and haven't moved their My Documents, then this doesn't really matter.