I am trying to use following cmd function inside R
rmdir /q /s myDir
I tried:
system("rmdir /q /s myDir")
but it returns an error:
rmdir: failed to remove '/q': No such file or directory
rmdir: failed to remove '/s': No such file or directory
rmdir: failed to remove 'public_html/croecon.contentio.biz': Directory not empty
How should I use slash option, e.g. /q?
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery("SELECT * FROM Win32_ProcessStartTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process where ProcessID=" & objReceivedEvent.ProcessID)
For Each objItem in colItems
wscript.echo objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
Next
Loop
Then type in a command prompt
cscript //nologo C:\folder\MonitorProcessCreation.vbs
This will monitor what starts when you run your command.
Related
I am trying to create a folder by date time in my batch file using following code
#echo off & for /F "tokens=1-4 delims=/ " %%A in ('date/t') do (
set DateDay=%%A
set DateMonth=%%B
set Date=%%C
set DateYear=%%D
)
#echo off & for /F "tokens=1-4 delims=/ " %%D in ('time/t') do (
set DateTime=%%D
)
set CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%
mkdir %CurrentDate%
using this I get folder name as 22-02-2021-010.01.37
But if time Hours is in 1 to 9 hr my folder is displayed as
22-02-2021-0 9.59.19 there is always a space in 0 and 9 and 1 to 9 hr is not displayed as 01,02,03 Hr
Answer Should Be:
22-02-2021-009.59.19
The best and the correct method to get this is to use the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
#echo off
Title Get FileName With Date and Time
Call :GetFileNameWithDateTime MyCurrentDate
echo %MyCurrentDate%
MkDir %MyCurrentDate%
pause & exit
::----------------------------------------------------------------------------------
:GetFileNameWithDateTime <FileName>
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set "MyDate=%%x"
set "%1=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%"
Exit /B
::----------------------------------------------------------------------------------
set "CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%"
set "CurrentDate=%currentDate: =0%"
mkdir %CurrentDate%
substituting 0 for in currentdate
Tips : Use set "var1=data" for setting values - this avoids problems caused by trailing spaces. In comparisons, use if "thing1" == "thing2" ... to avoid problems caused by spaces in thing1/2.
If you want something which will work on any modern system, and still output the directory name in your specific format/order, regardless of user or locale settings, then…
you could do it like this from a batch-file:
#For /F "Tokens=1-6 Delims=/: " %%G In ('%SystemRoot%\System32\Robocopy.exe \: . /NJH /L ^| %SystemRoot%\System32\find.exe " 123"') Do #MD "%%I-%%H-%%G-0%%J.%%K.%%L"
or directly from the Windows command-line, cmd.exe:
For /F "Tokens=1-6 Delims=/: " %G In ('%SystemRoot%\System32\Robocopy.exe \: . /NJH /L ^| %SystemRoot%\System32\find.exe " 123"') Do #MD %I-%H-%G-0%J.%K.%L
I am trying to run a R script from excel VBA. The script just queries data, formats and organizes it, and then exports it as a separate XLS file. However, I can not get the R script to run.
Going off of this post: (albeit the OG code is what I understood)
Running R from Excel VBA without RExcel
I don't have access to RExcel due to work restrictions on downloads. I have found my R.exe file paths and the macro below is able to run:
Dim rCommand As String
rCommand = "C:\Program Files\R\R-3.5.3\bin\R.exe --verbose U:\Reporting\Mix of Business Report\Morgan's Trials\Mix of Business Report v1.R"
'Timer Set to run full Model.R script
Application.Wait Now + TimeValue("00:01:05")
'Runs R Script and Arguments into process
shell rCommand, vbNormalFocus
'Timer Set to run full Model.R Script
Application.Wait Now + TimeValue("00:01:05")
I wanted my macro to run in the background, however the R window (NOT Rstudio, which is fine, as long as it works) doesn't run the R script.
Here is what I am shown in the "Rterm" window:
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
ARGUMENT 'U:\Reporting\Mix' __ ignored__
ARGUMENT 'of' __ ignored__
ARGUMENT 'Business' __ ignored__
ARGUMENT 'Report\Morgan's' __ ignored__
ARGUMENT 'Trials\Mix' __ ignored__
ARGUMENT 'of' __ ignored__
ARGUMENT 'Business' __ ignored__
ARGUMENT 'Report' __ ignored__
ARGUMENT 'v1.R' __ ignored__
'verbose' and 'quietly' are both true; being verbose then ..
now dyn.load("C:/Program Files/R/R-3.5.3/library/methods/libs/x64/methods.dll") ...
'verbose' and 'quietly' are both true; being verbose then ..
'verbose' and 'quietly' are both true; being verbose then ..
now dyn.load("C:/Program Files/R/R-3.5.3/library/utils/libs/x64/utils.dll") ...
'verbose' and 'quietly' are both true; being verbose then ..
Garbage collection 1 = 0+0+1 (level 2) ...
11.5 Mbytes of cons cells used (35%)
2.7 Mbytes of vectors used (4%)
now dyn.load("C:/Program Files/R/R-3.5.3/library/grDevices/libs/x64/grDevices.dll") ...
'verbose' and 'quietly' are both true; being verbose then ..
now dyn.load("C:/Program Files/R/R-3.5.3/library/graphics/libs/x64/graphics.dll") ...
'verbose' and 'quietly' are both true; being verbose then ..
now dyn.load("C:/Program Files/R/R-3.5.3/library/stats/libs/x64/stats.dll") ...
ending setup_Rmainloop(): R_Interactive = 1 {main.c}
>R_ReplConsole(): before "for(;;)" {main.c}
Why is my file path being ignored? I also tried changing the backslashes of my verbose r script path to forward slashes, same message.
Sorry if it's repetitive, I don't understand any of the other questions posted and the one linked above was my best shot.
It seems like the problem is in the path, because in UNC you need to put quotes in a path that contains spaces. Change the command like this and it will work:
Dim rCommand As String
rCommand = """C:\Program Files\R\R-3.5.3\bin\R.exe"" --verbose ""U:\Reporting\Mix of Business Report\Morgan's Trials\Mix of Business Report v1.R"""
Edit
Another problem was that R.exe shouldn't be used to simply execute scripts. We can use RScript.exe for that purpose and we can avoid the console closing, by adding && pause at the end of the command. Here's the complete code:
Dim rCommand As String
rCommand = """C:\Program Files\R\R-3.5.3\bin\RScript.exe"" --verbose ""U:\Reporting\Mix of Business Report\Morgan's Trials\Mix of Business Report v1.R"" && pause"
'Timer Set to run full Model.R script
Application.Wait Now + TimeValue("00:01:05")
'Runs R Script and Arguments into process
Shell rCommand, vbNormalFocus
'Timer Set to run full Model.R Script
Application.Wait Now + TimeValue("00:01:05")
Sync Method
A way to improve the function is to execute the shell with waitTillComplete flag, which executes the command with a Sync call. Here's the code:
Sub R_Exec()
Dim cmd As Object
Dim rCommand As String, rBin As String, rScript As String
Dim errorCode As Integer
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim debugging As Boolean: debugging = True
Set cmd = VBA.CreateObject("WScript.Shell")
rBin = """C:\Program Files\R\R-3.5.3\bin\RScript.exe"""
rScript = """U:\Reporting\Mix of Business Report\Morgan's Trials\Mix of Business Report v1.R"""
'Check if the shell has to keep CMD window or not
If debugging Then
rCommand = "cmd.exe ""/k"" " & rBin & " " & rScript
Else
rCommand = rBin & " " & rScript
End If
Debug.Print rCommand 'Print the command for debug
'Runs R Script and Arguments into process, returning errorCode
errorCode = cmd.Run(rCommand, vbNormalFocus, waitTillComplete)
End Sub
With this Sub you can decide if keep the shell window open or not.
Hope this helps.
Alternatively, for cleaner code to avoid too many quote handling and extendable to many arguments consider building command line call from an array of arguments (borrowed from #UriGoren). Also, use CMD.exe /k to launch window of the automated Rscript (which ideally should be accessible through the PATH environment variable):
Sub Run_R_Script()
Dim args(0 To 3) As String
Dim rCommand As String
Dim i As Integer
args(0) = "CMD.exe"
args(1) = "/k"
'args(2) = "Rscript.exe" ' IF R BIN FOLDER IN PATH ENV VARIABLE
args(2) = "C:\Program Files\R\R-3.5.3\bin\RScript.exe"
args(3) = "U:\Reporting\Mix of Business Report\Morgan's Trials\Mix of Business Report v1.R"
rCommand = args(0)
For i = 1 To UBound(args)
rCommand = rCommand & " """ & args(i) & """"
Next i
Debug.Print rCommand ' CHECK COMMAND LINE CALL
'Timer Set to run full Model.R script
Application.Wait Now + TimeValue("00:01:05")
'Runs R Script and arguments into process
Shell rCommand, vbNormalFocus
'Timer Set to run full Model.R Script
Application.Wait Now + TimeValue("00:01:05")
End Sub
We have created a mini web program for running PowerShell in asp.net. the PowerShell command is running fine. but when we try to import the MSOnline module, it will be shown the following error:
Could not load file or assembly
'file:///C:\Windows\system32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation.PSModule.dll'
or one of its dependencies. An attempt was made to load a program with
an incorrect format.
Dim Ps As PowerShell = PowerShell.Create()
Dim tempScript As String = "Import-Module MSOnline " + Environment.NewLine
tempScript = tempScript + "$username = 'xxx#xxx.com' " + Environment.NewLine
tempScript = tempScript + "$password = 'abcd1234' " + Environment.NewLine
tempScript = tempScript + "$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force " + Environment.NewLine
tempScript = tempScript + "$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd " + Environment.NewLine
tempScript = tempScript + "Connect-MsolService -Credential $creds " + Environment.NewLine
tempScript = tempScript + "Get-MsolDomain" + Environment.NewLine
Ps.Commands.AddScript(tempScript)
' Execute the script
Dim results = Ps.Invoke()
PS C:> $PSVersionTable | Out-String
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.34209
BuildVersion 6.3.9600.17400
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
Update : 3-Aug-2017
Try to use process.start to call a CMD, and then the cmd call a powershell, but it failed also. same error message.
Private Function RunBatch() As String
Dim proc As New Process
Dim strBuilder As StringBuilder = New System.Text.StringBuilder
proc.StartInfo.FileName = "C:\temp\enableMFA.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
strBuilder.Append(ln & vbNewLine + vbLf)
Next
Return strBuilder.ToString
End Function
Error Message:
C:\Users\admin\Desktop\Preview\Preview\bin\Debug>powershell -File
"C:\temp\enableMFA.ps1"
Import-Module : Could not load file or assembly
'file:///C:\Windows\system32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation.PSModule.dll'
or
one of its dependencies. An attempt was made to load a program with an
incorrect format.
At C:\temp\enableMFA.ps1:1 char:1
Import-Module MSOnline
~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [Import-Module], BadImageFormatException
FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand
Finally fixed the issue by change the CPU to x64, this is the steps
Right click the project >> properties >> complie >> Target CPU to x64
Go to TOOLS >> Options >> Projects and Solutions >> Web Projects >> use 64bit IIS Express
** Remember close the VS2013 and open the project again **
** Thx for the hints from David Brabant**
I need a command to use in a batch file, which copies the contents of a remote directory to a local directory over http.
For example to copy folder http ://path//folder to C:\folder
I need to do this without installing any additional tools.
Thanks in advance!
There's no standard way for an http server to list accessible directories.
For example I took http://unomoralez.com/content/files/catalog2/source/ as one of the common ways to list directory with http. Your site could look different though but there's no way for me tho know... (ther's a temp list2.txt file - you can remark its deletion to check the format of directory page and tell me if its not working. IF it is IIS could look like this: http://live.sysinternals.com/tools/)
the script downloads all content into .\download_dir (not recursive download) :
#if (#X)==(#Y) #end /****** jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist simpledownloader.exe goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"simpledownloader.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
:: download the file
:::::::::::::::::::::::::::::::::::::::::
::::just change the link and the file::::
:::::::::::::::::::::::::::::::::::::::::
::!!!!!!!!!!!!!!!!!!!!!!!!!:::
simpledownloader.exe "http://unomoralez.com/content/files/catalog2/source/" "list2.txt"
md download_dir >nul 2>&1
for /f "skip=1 tokens=4 delims=>< " %%a in ('type list2.txt^| find /i "href" ') do (
simpledownloader.exe "http://unomoralez.com/content/files/catalog2/source/%%a" .\download_dir\%%a
)
del /q /f list2.txt
exit /b 0
****** end of jscript comment ******/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var webClient:System.Net.WebClient = new System.Net.WebClient();
print("Downloading " + arguments[1] + " to " + arguments[2]);
try {
webClient.DownloadFile(arguments[1], arguments[2]);
} catch (e) {
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\nProblem with downloading " + arguments[1] + " to " + arguments[2] + "Check if the internet address is valid");
Console.ResetColor();
Environment.Exit(5);
}
As you have powershell you also have .net so this code will be executed without problems for you.
This was more or less a code that I already had but you can also check this -> https://code.google.com/p/curlie/ if you are familiar with cURL and create a hybrid jscript/.bat file.
I'm new in scripting. I need the code to receive some arguments and execute it in hidden cmd in HTA.
the command to execute is
netsh wlan set hosted mode=allow ssid="name" key="pwd"
Here i want to get "name" and "pwd" from submit box and execute the above command in hidden hta.
I made it, but not working properly. See
<script language="VBScript" type="text/vbscript">
set objShell = CreateObject("WScript.Shell")
strOut=""
sub StartProgram
cmdarg="%comspec% /c netsh wlan set hosted mode=allow ssid=" & T1.value "key=" & T2.value
iReturn=objShell.Run(cmdarg, 0, True)
If iReturn = 0 Then
MsgBox "Success"
Else
MsgBox "Cannot Start"
End If
TraceOut.innerHTML= strOut
end sub
</script>
I don't know if this is the whole problem, but at the very least:
cmdarg="%comspec% /c netsh wlan set hosted mode=allow ssid=" & T1.value "key=" & T2.value
should be
cmdarg="%comspec% /c netsh wlan set hosted mode=allow ssid=" & T1.value & " key=" & T2.value
In other words, you left an ampersand out after T1.value, and left a space out before key=.