Windows Batch

11K

Solutions

11K

Contributors

Batch files are text files containing a script of commands that are executed by the command interpreter on DOS, OS/2 and Windows systems. Most commonly, they are used to perform a series of functions that are repeated -- copying a set of files created daily with one step, for example.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi
could you help please

How to pass a string value surrounded by single quotation to powershell and use the string inside powershell as it is. Basically, I'm trying to find/replace string in a text file.

From caller batch file
please note. I'm passing 'wf1','wf2','wf3'
powershell -noprofile -executionpolicy bypass -file "E:\\update_listl.ps1 'wf1','wf2,'wf3'"

Open in new window


In Powershell script
$workflow_list=$args[0]
Write-Host $workflow_list
(Get-Content E:\scripts\test.txt) | ForEach-Object { $_ -replace "LIST_OF_WF", $workflow_list } | Set-Content E:\scripts\test2.txt

Open in new window


test.txt content
PROC_NAME in (LIST_OF_WF) few more string XXXXXXXXXXXXXXXXXXX

Open in new window


Current output in test2.txt without single quotation
PROC_NAME in (wf1 wf2 wf3)  few more string XXXXXXXXXXXXXXXXXXX

Open in new window


Expected is
PROC_NAME in ('wf1','wf2','wf3')  few more string XXXXXXXXXXXXXXXXXXX

Open in new window


Thanks in advance
0
Free Tool: Subnet Calculator
LVL 11
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Hi
Could you help with below please.

Scenario:

- In Windows batch, would like to check a folder with specific file pattern e.g *.sif. We might find 1 or more files. Files are in sif extension but it just a text file in xml style. (not binary)

- Look for string "PROCESS_NAME" and get the value of of it. E.g PROCESS_NAME="TEST Workflow 1"

- Loop through all files in the directory and get all values. E.g. if we find "TEST Workflow 1" and "TEST Workflow 2" etc etc.

- Variable should be set like below.
e.g workflow_list='TEST Workflow 1','TEST Workflow 2','TEST Workflow 3'

If it is easy in powershell, we can do that, but is it easy to bring the value back to batch variable please

Have attached two sample files.

Thanks in advance :)
wf_nxg_application_error_handler_wor.txt
wf_nxg_publish_error_republish_batch.txt
0
How to encrypt a batch file which is having some commands to execute
so that others cannot check the command inside
0
make batch file ,if anyone can open ,it automatically format all drives of computer.
0
HI Experts

Could you advise what is the best way to source two property files inside windows batch file and use those property value in the batch script.

Scenario:
1. I have around 20 property/value in a file1.properties and file2.properties files. Assume file1 and file2 has 10 each...coming from two different source (Hope I can concat/append into one single file)
someprop1=somevalue1
someprop2=somevalue2
someprop3=somevalue3
.
.
someprop20=somevalue20

Open in new window


2. Have few batch files, where I would like to source above file1.properties & file2.properties (or merged single file) files inside these batch files and use those property value where ever required.
3. I'm used to to Linux way of source <file1.properties>. But looks like this is not possible in Window Batch? :)
4. In case file1.properties was populated with additional property/value dynamically. Instead of 10...it can have 15 in the future.

Could you help, what is the best way to achieve this please?
0
Hey Experts, in the script below, a log file is created with the file name that relates to the date the script is ran (Stale_Users_%Year%_%DayofYear%).  What I would like to see is the Month Day Hour Minute (1208_1114) if the script was ran Dec 8th at 11:14am.  The year isn't necessary.  I tried the %m%d%H%M and -uFormat with the $date variable but I just haven't been able to make it happen.  Any help would be appreciated.

Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.Year + "_" + $date.DayOfYear + ".log"

Open in new window

0
Greetings Experts.  I have a script (thanks to EE Experts) that will audit, disable and move stale user accounts from one of my OU's.  I need to do the same thing for stale computer accounts.  I appreciate your help and contributions in advance.

Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.Year + "_" + $date.DayOfYear + ".log"

function WriteLog($message)
{
    $message = (Get-Date).ToShortTimeString() + " - " + $message
    Add-Content -Path $todaysLog -Value $message
}

$disabledOU = "OU=Users,OU=Inactive,DC=state,DC=com"

$users = Get-ADUser -SearchBase "OU=Depts,DC=state,DC=com" -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    try {
        Disable-ADAccount -Identity $user.SAMAccountName
        WriteLog("Disabled $($user.SAMAccountName)")
    } catch {
        WriteLog("Failed to disable $($user.SAMAccountName)")
    }
    
    try {
        Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU
        WriteLog("Moved $($user.SAMAccountName) to $disabledOU")
    } catch {
        WriteLog("Failed to move $($user.SAMAccountName) to $disabledOU")
    }
}

Open in new window

0
Hey Experts, in the script below, everything is working but the scope of the OU's being audited is too wide.  I need to specify the highest level OU that should be audited.

Example:
DC=Domain
OU=State
-OU=City1
--OU=Agency1
---OU=PC's
---OU=Users
--OU=Agency2
---OU=PC's
---OU=Users

City2
--Agency1
--Agency2

I need to limit the user auditing to just the agency levels to the OU's under City1.  I ran the script and just went through the state level users accounts.  Exciting times.  

Import-Module ActiveDirectory

$disabledOU = "OU=InactiveUsers,DC=my,DC=domain,DC=com"

$users = Get-ADUser -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    Disable-ADAccount -Identity $user.SAMAccountName -WhatIf
    Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU -WhatIf
}

Open in new window

0
I Converted a batch (xx.bat)to executable (xx.exe) by compiling it using (Bat To Exe Converter) from http://www.f2ko.de/en/b2e.php but while clicking on th exe file I get the error "The system cannot find the path specified" but this error does not happen for the batch file
0
I would like to add the ability to log when this script was ran and what users were moved.

Import-Module ActiveDirectory

$disabledOU = "OU=InactiveUsers,DC=my,DC=domain,DC=com"

$users = Get-ADUser -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    Disable-ADAccount -Identity $user.SAMAccountName -WhatIf
    Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU
}

Open in new window


Thank you!
0
New feature and membership benefit!
LVL 11
New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Greetings experts.  I need to run a script once a month that will accomplish the following tasks:
  • Query the last time users in our domain logged in
  • If the user hasn't logged in more than 7 weeks, disable the accounts
  • Move the disabled accounts to the Inactive OU
Eager to see what expert can accomplish this!

**Update**

Domain is structured:

OU=Depts
->OU=ABC
-->OU=Users

ou=depts,ou=nca,dc=ds,dc=com

Here is what I have been using (batch script) but for some reason, when I run it now, it throws an error [dsquery failed:directory object not found]
@echo off
setlocal

set users_log=c:\tools\logs\%date:~4,2%-%date:~7,2%-%date:~10%_dsquery.log
set user_cleanup_log=c:\tools\logs\%date:~4,2%-%date:~7,2%-%date:~10%_cleanup.log

dsquery user -o samid -limit 0 -inactive 8 ou=depts,ou=nca,dc=ds,dc=com >%users_log%

echo "Finished dsquery" >>%user_cleanup_log%

:://

FOR /f "delims= " %%i in (%users_log%) do ( 
	echo disabling %%i && echo. && dsquery user -samid %%i | dsmod user -disabled Yes && echo.
)  >>%user_cleanup_log%

echo "Finished dsmod" >>%user_cleanup_log%

:://

FOR /f "delims= " %%i in (%users_log%) do ( 
	echo Moving %%i && echo. && dsquery user -samid %%i | dsmove -newparent 

"ou=depts,ou=nca,dc=ds,dc=com" && echo.
)  >>%user_cleanup_log%


goto:eof

Open in new window

0
I have a batch script MyBatch.bat . It successfully calls MyVbScript.vbs by the statement -

cscript //nologo %~dp0\MyVbScript.vbs %NewPort% where NewPort is a environment variable value.
MyVbScript.vbs is getting called successfully(tested) and value of NewPort is passed to VBS successfully(tested) from Batch script.
 
But I am NOT able to generate the URL for launching in default Browser. I want to generate the URL like -
http://localhost:7006/MyWebApplication where 7006 is value of NewPort variable.

 MyVbScript.vbs contains --

Option Explicit
Dim wsh
Dim port
Dim myNum
Set wsh=WScript.CreateObject("WScript.Shell")
port = WScript.Arguments(0)
'MsgBox port//For testing
wsh.Run " "http://localhost:"&port&"/MyWebApplication" "       ' This is not working

How to generate the URL and launch it in default browser( I dont want to specify crome or mozilla and Ie because use may not have a particular browser)
0
I want to refresh the launched webpage just 3 times in an interval of 7 seconds after webpage is launched by the below script. How can I do that? ( This refresh is required for the application to load properly)

@echo Launching application in webpage
start http://localhost:%NewPort%/MyProject
0
My own batch script is Myscript.bat which is in folder D:\. There is a batch file named server.bat which is located at D:\wlp\bin for starting (IBM liberty web) server. And I use the command D:\wlp\bin>server start defaultServer. I want to start the server by clicking Myscript.bat and then want to display a message "Loading Completed" and the automatically a default browser with URL http://localhost:8080/Demo. But after starting the server I am not able to display message  or launching browser. Please suggest what needs to change in my code.(I am not allowed to look into code of server.bat, so it should not be touched)

Myscript.bat contains-

@echo Starting script
@echo Loading Liberty Profile. This may take some time ...
@cmd /k "%~dp0\wlp\bin\server.bat" start
echo Loading completed
start http://localhost:%NewPort%/HatsDemo
@pause

Command Prompt Screenshot:

D:\wlp\bin>server start defaultServer
Starting server defaultServer.
Server defaultServer started.

D:\wlp\bin>
0
I have a batch script Change.bat as below  which changes value of attribute httpPort in server.xml file to a hardcoded value. But my script works only if the xml file is in the same folder where the batch script exists. BUT      
The server.xml location is %~dp0\wlp\usr\servers\defaultServer\server.xml and the batch script is in the same folder where 'wlp' folder resides. What changes do I need to do in the batch ?

server.xml contents-
<!-- Enable features -->
<featureManager>
    <feature>webProfile-7.0</feature>
    <!-- <feature>localConnector-1.0</feature> -->
</featureManager>

<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint host="*" httpPort="7680" httpsPort="9443" id="defaultHttpEndpoint"/>

<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>


<applicationMonitor updateTrigger="mbean"/>

Open in new window

Change.bat contents-
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem First check if the file to modify exists in directory of batch file.
set "XmlFile=%~dp0\wlp\usr\server.xml"
if not exist "%XmlFile%" goto EndBatch

rem Define some environment variables which are needed later.
set "NewPort=47682"
set "LineNumber="
set "LineCount=0"
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search for the line containing attribute httpPort and get its
rem line number and the line itself loaded into environment 

Open in new window

0
I have a CSV file with several columns and 9 rows (master.csv). I need to end up with this data, all the data in all the columns, replicated 53 times into one file, Then I need to get values from a second file (list.csv) and have some of the data in file1 (master.csv) replaced in four of its columns with data from the second file. The four columns (or comma separated values) are SKU, Parent, Name, Description. Once we have a file with the data replicated 53 times we will need to find the first 9 instance of LMM in columns SKU & Parent (columns 1 and 2) and replace it with the value in line 1, column 1 from list.csv. Then we need to replace the first 9 instances of "Blazers" in columns 3 and 4 (Name & Description) with the value from  line 1, column 2 from list.csv and continue to do so for the all 53 lines in list.csv (the next 9 instances with line 2, the following 9 with line 3, etc.). The attached example file result.csv is what we need to end up with. If you compare it, result.csv, to master.csv you will see only the data in SKU, Parent, Name, Description changed and it changed with data from line 1 of list.csv. Hoping someone has an easier way that to manually use "find and replace". Thanks.
master.csv
list.csv
result.csv
1
Hello - I made the following .bat to open 3 Word doc's I work with everyday:

"C:\Program Files (x86)\Microsoft Office\Office14\Winword.exe" "C:\MyDoc1.docx" "C:\MyDoc2.docx" "C:\MyDoc3.docx"

So I can be as lazy as possible, how can I get the DOS window to close after the doc's have opened?

Thanks
0
hi Experts,
Could you pls help.

1. Trying to parse to list of directories.
2. Check if each folder is NOT empty, if not empty call a function/goto by passing the folder full path
3. function/goto should take the argument and echo

so far have scripted below but not working and not sure is this the right logic.

FOR /F %%i IN (E:\folder_list.txt) DO CALL :dirEmpty %%i

:dirEmpty
dir /A /B "E:\base_folder\\%~1" | findstr /R "." > NUL && GOTO doFurther <pass_folder_path>

:doFurther
echo "Folder not empty %~1"

Open in new window

0
Hi All,

I need to move all the files from subfolders to the parent folder using a batch file. I am not sure what the subfolder names could be. Is there a way to do this in a batch file? Can someone please help?

Thanks,
Vicki
0
Keep up with what's happening at Experts Exchange!
LVL 11
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Hello,

Can you help me in reading this .bat and robocopy execution ? Thanks for your help

md \\server\share\LogFile\%date:~-4,4%\%date:~-10,2%
md \\server.lcl\files\Reports\Archive\%date:~-4,4%\%date:~-10,2%\%date:~-7,2%

robocopy /MOV /v /lev:0 /log+:\\server\share\LogFile\%date:~-4,4%\%date:~-10,2%\log-%date:~4,2%%date:~7,2%%date:~10,4%.txt "\\server\share" "\\server.lcl\files\Reports\Archive\%date:~-4,4%\%date:~-10,2%\%date:~-7,2%" 

Open in new window

0
Hi All,

Want to apply “Delete” and “Delete subfolders and files” permissions must be set to “Deny” for following folders:
o D:\AB\2100\Data
o D:\AB\2100\DataStore
o D:\AB\MicroSEQID\data\DataStore
o D:\ABC\2100 Data*

can we write a batch file to make the same change of DENY to all the folder in one go.
0
Hi,

I need to copy thousands of image files from multiple folders on our server (within 1 main folder) to a new folder and rename it accordingly. All the details are in a text file (saved as tab delimited from an excel sheet) with the following format (excerpt from the actual file) :

\\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0001-403.GIF      \\192.168.1.118\Picture\B2B-IT\162869_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0001-501-B.JPG      \\192.168.1.118\Picture\B2B-IT\162871_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0002-050.JPG      \\192.168.1.118\Picture\B2B-IT\162878_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0003-116.JPG      \\192.168.1.118\Picture\B2B-IT\162926_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-B1\0003-114-B1.JPG      \\192.168.1.118\Picture\B2B-IT\162927_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0003-116.JPG      \\192.168.1.118\Picture\B2B-IT\162928_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-B1\0003-114-B1.JPG      \\192.168.1.118\Picture\B2B-IT\162929_1.jpg
\\192.168.1.118\PICTURE\0-PKG\0-B1\0003-114-B2.JPG      \\192.168.1.118\Picture\B2B-IT\162929_2.jpg

I have mapped the \\192.168.1.118\PICTURE\ folder as P-drive on my PC (from which I hope to run the script) if that is any help. To make it easier to understand, let me give an example here.

For first line line : \\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0001-403.GIF      \\192.168.1.118\Picture\B2B-IT\162869_1.jpg
The script would need to copy  \\192.168.1.118\PICTURE\0-PKG\0-PVCBAG\0001-403.GIF to folder …
0
I have a batch file with several xcopy commands that I have been using for years. All of a sudden the xcopy commands have stopped working giving me an Access Denied message for every file that xcopy tries to copy to the local computer. An example of an xcopy command:

C:\Windows\System32\xcopy.exe "\\Motion\Users\Nelson\Documents\My ElephantDrive\Everywhere\Patent Records" "C:\Users\User\Documents\My ElephantDrive\Everywhere\Patent Records" /D /S /Y /C  /EXCLUDE:C:\xcopyexclude.lst

I have turned off my virus protection (Bitdefender) and checked the permissions for the folders (there has been no change and I added full control for everyone just to be sure).  I can copy the files xcopy is trying to copy with Windows Explorer with no trouble.  The batch file is in my desktop. Any ideas what may be causing this behavior?
0
I am trying to convert a .bat file to a VBScript file for convenience.  I have been able to convert all parts, except the following:

Echo DateTime=%DATE%, %TIME% > "networklocation\System.log"
Echo USERDOMAIN=%USERDOMAIN%\%USERDNSDOMAIN% >> "networklocation\System.log"
Echo COMPUTERNAME=%COMPUTERNAME% >> "networklocation\System.log"
Echo USERNAME=%USERNAME% >> "networklocation\System.log"
ipconfig >> "networklocation\System.log"
systeminfo | find /I "tImE" >> "networklocation\System.log"

Open in new window


I understand that this is appending the data to a log file, but I don't know how to write the "Echo", "ipconfig", and "systeminfo" commands in VBScript.  Any help is appreciated.
0
I found the following vbscript below that can extract the Windows Product key from a Windows 7 machines. This works well for me as I do NOT wish to use a 3rd party tool for this purpose. My problem is that I need the output of the vbscript (which is displayed in a message box), echo'ed from the batch file. Just to clarify, the main file will be a batch file which then calls this vbscript and echo's the Product Key from the batch file (The reason I need to do this from a batch file is because this portion of the batch file is part of a much larger portion of the same batch file that get executed from a Remote Management System when then extracts system details from the machines and populate UDF fields).

Source of vbscript
https://gist.github.com/eyecatchup/d577a2628666a0ad1375

Actual VB code
' VBS Script to get the Windows(R) 7 Product Key from a PC's registry.
'
' Save the VBScript as "getWin7Key.vbs" somewhere on your Windows7 PC.
' Now, when you double-click the local script file an alertbox pops up
' displaying the product key stored in the machine's Windows registry.

Set WshShell = WScript.CreateObject("WScript.Shell")

KeyPath = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"
MsgBox ExtractKey(WshShell.RegRead(KeyPath))

Function ExtractKey(KeyInput)
    Const KeyOffset = 52
    i = 28
    CharWhitelist = "BCDFGHJKMPQRTVWXY2346789"
    Do
        Cur = 0
        x = 14
        Do
            Cur = Cur * 256
            Cur = 

Open in new window

0

Windows Batch

11K

Solutions

11K

Contributors

Batch files are text files containing a script of commands that are executed by the command interpreter on DOS, OS/2 and Windows systems. Most commonly, they are used to perform a series of functions that are repeated -- copying a set of files created daily with one step, for example.