Trying to delete multiple appfabric cache names using a batch script - batch-file

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).

Related

Log Me In Rescue Service issues

I have not been coding for very long but am looking to create a work around with some issues that log me in rescue has, during reboots log me in rescue will frequently lose connection and cause the program to break for lack of better terms, currently the fix for the issues is to delete the service which looks something like LMIRescue_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
So what i would like to do is create a batch that can delete an service starting in LMIRescue_
or if that's not possible to have a workaround where I can find service and the grab the out put and use that to delete
can any one give me an example of how to use batch to find the service and delete it on its own or at least point me in the right direction?
I have tried
#echo off
set /p UserInputPath1= What is the First Service Name?
set /p UserInputPath2= What is the Second Service Name?
net stop %UserInputPath1%
net stop %UserInputPath2%
sc delete %UserInputPath1%
sc delete %UserInputPath2%
this works but it requires user input and takes extra time, and the whole point in making this is to avoid wasting time
if wildcards would work, I could just do this
net stop LMIRescue*
sc delete LMIRescue*
net stop LMIRescue*
sc delete LMIRescue*
is there a way to delete a service using wild cards?
is there any way to delete a service in batch other than sc Delete "ServiceName"
and/or how can i use batch to find and output the name of the service and then use that to delete it.
You could use the sc query command to retrieve the names of all the active services that are currently running on the local machine. The findstr command can be used to filter anything that doesn't meet the given criteria (in this example, only lines starting with SERVICE_NAME: LMIRescue remain). The remaining line can be tokenized with the use of the for /f command to temporarily store the retrieved service name in for-loop variable %%j.
#for /f "tokens=1,*" %%i in ('"sc query | findstr /b /c:"SERVICE_NAME: LMIRescue""') do #(
net stop "%%~j"
sc delete "%%~j"
)

Batch script fails when run as admin from explorer, but not when run as admin from terminal?

I have a batch script that needs to run as admin. I will be distributing to users so it would be best if they can run it from Windows Explorer.
Unfortunately, it doesn't work when run from explorer (right click -> run as admin). It does work when called from a pre-existing admin terminal.
Initially I thought the problem was with the active directory, but I added a "cd /d %~dp0" as the first command. I confirmed through echo that this places them both in the same directory, but it still fails when running from explorer.
The failure occurs when reading an external file in the same directory as the .bat. It pulls empty strings when run from explorer. Here is sample code:
rem Make sure active directory is correct (verified that this works)
cd /d %~dp0
rem Load parameters from params.txt
for /f "delims== tokens=1,2" %%G in ("params.txt") do set %%G=%%H
rem Print params (it's a loop so you can read it when running from expl.)
for /l %%a in (1 1 100000) do echo %DST%
Then you just need to make sure params.txt is in same directory as .bat and includes the line "DST=some\directory\name"
Anybody know why this doesn't work?
As has been pointed about by #nephi12 in his answer if your file name does not have spaces you can remove the quotes, otherwise it thinks the IN clause is a string you want to parse. If you need to quote your file names then you need to use the USEBACKQ option as pointed out by the comments. Once you use that option your code works just fine.
But I would like to make a point with your code. If the contents of your params.txt file is:
"DST=some\directory\name"
Then your FOR command can just be this:
for /f "usebackq tokens=1 delims=" %%G in ("params.txt") do set %%G
I am not understanding why you are echoing the %dst% variable 100,000 times?
For one thing, take away the "s from around params.txt as double-quotes means string parsing, while unquoted is a list of files.
Second, try prepending params.txt with %~pd0\ to ensure the correct path, rather than changing directory.

Removing websites from hosts file with batch file

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.

%Computername% Up to a certain character for naming files

So we are running a backup script for my job and until now they just had the script pull the computer name and use that as the folder it creates. The problem that we are encountering is that when we go to then use the restore script it becomes useless.
Our computer names are for example SMITHT#-Year-A.
But I would like the batch script to not use the whole name because often this is used when we change the year of the computer. And because sometimes there are numbers after a persons name there are variying lengths so most of the knowledge I have on deciding start and stop points is coming up useless.
Is there a way to have the batch create a folder using the %COMPUTERNAME% function telling it to stop at the "-" so all we get is the name and number of the person?
To split a string at a certain character use for /F:
for /F "tokens=1 delims=- eol=-" %L in ("%COMPUTERNAME%") do (set SHORTNAME=%L)
This command line stores the string portion before the (first) - into variable SHORTNAME.
For details type for /? in the console window.
To use the above line in a batch script, replace %L by %%L.

trying to recursively search for files with a certain word in their file name using CMD (windows)

I'm trying to write a script that will search for all file recursively in a folder and run a command and/or list of commands on each file. Here's an example of how I need it to work:
Search folder for files containing "1080p" in the file name
Copy this file to a local directory but remove the "1080p" from the filename
Run another batch script on those files (I already have that part working)
All this needs to be automated.
I need to do this in the Windows command prompt and I'm willing to use any other programs required.
I'm already using SED in a similar batch script.
#echo off
setlocal disableDelayedExpansion
set "src=sourcePath"
set "dst=destinationPath"
set "search=1080p"
for /r "%src%" %%F in (*%search%*) do (
set "full=%%~fF"
set "name=%%~nxF"
setlocal enableDelayedExpansion
copy "!full!" "%dst%\!name:%search%=!"
endlocal
)
REM call your batch script here to process the copied files
You could have problems if the same filename exists in multiple source folders. But that is a general problem with your stated requirements.
Explanation:
%%~fF gives the full path to the file contained in %%F
$$~nxF gives the name and extension only of the file contained in %%F
type HELP FOR or FOR /? for more information about the modifiers available for FOR variable expansion.
!name:%search%=! uses delayed expansion to search the contents of name and replace the search value with nothing. In this example %search%=1080p. Note that the search is not case sensitive.
I need to use delayed expansion when doing search and replace within the loop because normal expansion using percents occurs when the statement is parsed. But the entire FOR construct, encluding the contents of the parentheses, is parsed as one logical statement. So normal expansion would give the value of name prior to the loop executing. That won't work :-) Delayed expansion gives the current value each time the line is executed.
Type HELP SET or SET /? for more information about search and replace and delayed expansion.
I need to toggle delayed expansion on and off because ! is a valid character in a filename, and %%F expansion will corrupt the value if it contains !.
I would recommend using cygwin to easily take advantage of some common Unix utilities, although you can probably locate windows compiled versions one by one (i.e. perl):
Find a list of files by name, execute a command on each:
find . -name \*1080p\* | xargs <command>
Find a list of files, create a list of move/rename commands to strip out '1080p' string:
find . -name \*1080p\* | perl -ne 'chomp();$x=$_;s/1080p//g;print"cp $x /target/$_\n"'
# add "| sh" to run the commands, or "> commands.sh" to generate a script
Command that should run in CMD only requiring PERL
dir /s /b | perl -ne 'chomp();$x=$_;s/1080p//g;print"copy $x c:\target\$_\n"' > cmds.bat
Adjust the scripts, of course, to do what you need. However, I believe this will accomplish your goal. There may be a clever way to do this with Windows CMD, but I am not a CMD expert. Unix utilities are (IMHO) much more straightforward!

Resources