If EXE opens, then RUN - if-statement

I need a script that. If exe opens, then URL will open. And I did make a shortcut for the URL.
I found this script, on stack overflow, and was going to use it changing the arguments of course, but I figured there would be a simpler way
EDIT: If League of Legends.exe opens [This is the client itself], then run C:..\KSD.url
Option Explicit
Private Const Folder As String = "c:\windows\system32\foldername"
Private Const FileToRun As String = "\\servername\folder\software.exe"
Sub Run(ByVal sFile)
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run Chr(34) & sFile & Chr(34), 1, False
Set shell = Nothing
End Sub
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(Folder) Then
Run FileToRun
End If

Try Exec : http://msdn.microsoft.com/en-us/library/ateytk4a(v=vs.84).aspx
objExec = shell.Exec Chr(34) & sFile & Chr(34)
if objExec.Status = 0 then ' your program is running
' open your url
end if
You may need error handling if your file does not open (see MSDN documenation above). Please code responsibly :-)

Related

Error using VBScript in BGInfo File not found error

I'm an amateur VB scripter.
I am creating a script to output the ID.
The file contains the line "ad.annnet.id = 564654068". It is necessary to output "ID: 564654068"
With New RegExp
.Pattern = "\nID=(\d+)"
Echo .Execute(CreateObject("Scripting.FileSystemObject").OpenTextFile("this.conf").ReadAll)(0).Submatches(0)
End With
There are multiple issues with the script, the actual cause of the "File not found" error is as #craig pointed out in their answer the FileSystemObject can't locate the file "this.conf". This is because the OpenTextFile() method doesn't support relative paths and expects an absolute path to the file whether it is in the same directory as the executing script or not.
You can fix this by calling GetAbsolutePathName() and passing in the filename.
From Official Documentation - GetAbsolutePathName Method
Assuming the current directory is c:\mydocuments\reports, the following table illustrates the behaviour of the GetAbsolutePathName method.
pathspec (JScript)
pathspec (VBScript)
Returned path
"c:"
"c:"
"c:\mydocuments\reports"
"c:.."
"c:.."
"c:\mydocuments"
"c:\"
"c:"
"c:"
"c:.\may97"
"c:.\may97"
"c:\mydocuments\reports*.*\may97"
"region1"
"region1"
"c:\mydocuments\reports\region1"
"c:\..\..\mydocuments"
"c:....\mydocuments"
"c:\mydocuments"
Something like this should work;
'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = "this.conf"
Dim filepath: filepath = fso.GetAbsolutePathName(filename)
Dim filecontent: filecontent = fso.OpenTextFile(filepath).ReadAll
Update: It appears you can use path modifiers in OpenTextFile() after all (thank you #LesFerch), so this should also work;
'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = ".\this.conf" '.\ denotes the current directory
Dim filecontent: filecontent = fso.OpenTextFile(filename).ReadAll
Another issue is the current RegExp pattern will not match what you are expecting, would recommend using something like Regular Expressions 101 to test your regular expressions first.
In bginfo, click Custom, New, enter ID for the identifier, Check the VB Script file radio button, and then click Browse to select a VBScript file you have saved with the code below. Then add the "ID" item to the bginfo display area. Note: The "file not found" error is resolved by using the AppData environment variable to reference the AnyDesk data file.
Const ForReading = 1
Set oWSH = CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
AppData = oWSH.ExpandEnvironmentStrings("%APPDATA%")
DataFile = AppData & "\AnyDesk\system.conf"
Set oFile = oFSO.OpenTextFile(DataFile,ForReading)
Do Until oFile.AtEndOfStream
Line = oFile.ReadLine
If InStr(Line,"ad.anynet.id") Then ID = Split(Line,"=")(1)
Loop
oFile.Close
Echo ID
Please note that the data is returned to bginfo via one or more Echo statements. If testing this script outside of bginfo, change Echo to WScript.Echo.
You will never get the value/display that you're looking for if the output is
File Not Found
The regexp is meaningless until the path to the file is specified. As it stands, the "this.conf" file must be in the same location as the script itself - and from the error, I'm assuming that's not the case.

How to Zip folder with AppleScript-objc?

I'm generating a few Logs on the system, and then copying it to /tmp/MyFolder, and then
I move the folder to the desktop, I'm trying to compact it before you move on, but I don't know how to do it, I have tried the following:
tell application "Finder"
set theItem to "/tmp/MyFolder" as alias
set itemPath to quoted form of POSIX path of theItem
set fileName to name of theItem
set theFolder to POSIX path of (container of theItem as alias)
set zipFile to quoted form of (theFolder & fileName & ".zip")
do shell script "zip -r " & zipFile & " " & itemPath
end tell
While this isn't an AppleScript-ObjC script, I'm posting the corrected version of your own script so that it functions to do as you described:
tell application "System Events"
set itemPath to "/tmp/MyFolder"
set theItem to item itemPath
set fileName to quoted form of (get name of theItem)
set theFolder to POSIX path of (container of theItem)
set zipFile to fileName & ".zip"
end tell
do shell script "cd " & quoted form of theFolder & ¬
"; zip -r " & zipFile & space & fileName & ¬
"; mv " & zipFile & space & "~/Desktop/"
Trying to avoid using Finder for file system operations. It sounds counter-intuitive, but it's not well-suited for it. Use System Events, which has—among many other benefits—the ability to handle posix paths.
The script now zips the folder and its containing items into an archive at /tmp/MyFolder.zip, then moves this archive to the desktop.

How to execute a powershell script within C++?

The point of the whole program:
Pass in a username and password to elevate a user's privileges so that if they are not a user that is allowed to access a protected folder they can still open and view it. The username is mapped in a <map> which contains a key to their folder, it searches for their folder then passes it along with the username and password to do the real elevation in the following powershell script:
param(
    [string]$username,
    [string]$password,
    [string]$folder
    )
    Write-Host $username $password $folder
 
    $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
    Start-Process T:\folders\Explorer++\Explorer++.exe \\foo\boo\fileserver\allusers\specialUsers\$folder -Credential $credential
I am passing in the username, password, and folder into this script through the use of System().
The c++ code to execute the script and pass in variables looks like this:
String^ runCommand(string folder, string username, string password)
{
string explorerpp = "\\\\foo\\boo\\examplefolder\\Explorer++\\EXPLORER++.exe";
string space = " ";
string quote = "\"";
string start = "C:\\ProgramData\\Microsoft\Windows\\Start Menu\\Programs\\System Tools\\Windows Powershell";
string open = "open";
string domain = "domain\\";
string pwShell = "S:\\foo\\boo\\locationofscript\\pwShell.ps1 ";
string parentFolder = """\\\\foo\\boo\\folder\\Parent_folder\\special_users \\""";
string path = parentFolder + folder;
String^ dir = gcnew String(path.c_str());
string param = quote + domain+ username + quote + space + quote + password + quote + space + quote + folder + quote;
string command = "start powershell.exe" + space + pwShell + param;
system(command.c_str());
return dir;
}
Note: The code looks the way it does due to a massive amount of debugging, I understand that I am probably using a lot of un needed variables.
When ran through System() or _popen it either opens up a .txt containing a script or errors out on the command prompt.
If I were take what the value of string command is and paste it into a command prompt I would get the script running correctly and then opening the correct folder.
What is the issue with C++ that is not allowing the script to execute properly when the command prompt is executing everything correctly?
BIG EDIT:
The error I am getting is C:\OurProj\pwShell.ps1 : File C:\OurProj\pwshell.ps1 cannot be loaded because running scripts is disabled on this system.
I did just talk to the IT guys, and I am able to run scripts on this system, tried to make everything local, and if I run the script through powershell it works.
EDIT 2:
I have changed the Execution Policy as has been suggested, and it does return RemoteSigned, however when the code executes in C++ I am still told that I have scripts disabled.
In one environment you can execute unsigned power shell scripts, but in another one you can't. 64-bit and 32-bit each have a separate execution policy for power shell. Most likely you're running on a 64-bit operating system and building a 32-bit C++ program (default for visual studio).
You can get to a 32-bit power shell by doing the following:
On the Start screen, type Windows PowerShell (x86). Run this as administrator.
Next run the command:
Set-ExecutionPolicy RemoteSigned
Now you should be able to run unsigned local power script files from a 32 bit environment on your computer.
From the start menu you can get to either PowerShell environment, be sure the same execution policy is set for both using the command:
Get-ExecutionPolicy

Python 2.7 - I need to open a file twice in order for the 'w' mode to be accepted

This script searches for a string and replaces it.
The first script works but if you notice I have to open the file for a second time and give it the 'w' mode.
On the second script I try to open the file in the same line I use "with" but it doesn't work. It complaints about
IOError: File not open for writing
Why is this happening? What am I doing wrong? Even though I am glad the first script is working, it looks to be inefficient.
oldstr = 'Time'
newstr = 'TIME'
file_path = '/home/gmastrokostas/PycharmProjects/learning/file.csv'
fopen = open(file_path)
with fopen as f:
filedata = fopen.read()
strg = filedata.replace(oldstr, newstr)
fopen = open(file_path,'w')
fopen.write(strg)
fopen.close()
--------------------------------------
oldstr = 'Time'
newstr = 'TIME'
file_path = '/home/gmastrokostas/PycharmProjects/learning/file.csv'
with open(file_path, 'w') as f:
filedata = fopen.read()
strg = filedata.replace(oldstr, newstr)
fopen.write(strg)
fopen.close()
Why can't you just pass 'w' paramater as first call?
And you don't need to close the file, if you did 'with open..', it will close it anyway.
Instead of 'w' use 'r+'. This will open file for both reading and writing.

How to replace string in multiple files in the folder?

I m trying to read two files and replace content of one file with content of other file in files present in folder which also has sub directories.
But its tell sub process not defined.
i'm new to python and shell script can anybody help me with this please?
import os
import sys
import os.path
f = open ( "file1.txt",'r')
g = open ( "file2.txt",'r')
text1=f.readlines()
text2=g.readlines()
i = 0;
for line in text1:
l = line.replace("\r\n", "")
t = text2[i].replace("\r\n", "")
args = "find . -name *.tml"
Path = subprocess.Popen( args , shell=True )
os.system(" sed -r -i 's/" + l + "/" + t + "/g' " + Path)
i = i + 1;
To specifically address your actual error, you need to import the subprocess module as you are making use of it (oddly) in your code:
import subprocess
After that, you will find more problems. I will try and keep it as simple as possible with my suggestions. Code first, then I will break it down. Keep in mind, there are more robust ways to accomplish this task. But I am doing my best to keep in mind your experience level and making it make your current approach as closely as possible.
import subprocess
import sys
# 1
results = subprocess.Popen("find . -name '*.tml'",
shell=True, stdout=subprocess.PIPE)
if results.wait() != 0:
print "error trying to find tml files"
sys.exit(1)
# 2
tml_files = []
for tml in results.stdout:
tml_files.append(tml.strip())
if not tml_files:
print "no tml files found"
sys.exit(0)
tml_string = " ".join(tml_files)
# 3
with open ("file1.txt") as f, open("file2.txt") as g:
while True:
# 4
f_line = f.readline()
if not f_line:
break
g_line = g.readline()
if not g_line:
break
f_line = f_line.strip()
g_line = g_line.strip()
if not f_line or not g_line:
continue
# 5
cmd = "sed -i -e 's/%s/%s/g' %s" % \
(f_line.strip(), g_line.strip(), tml_string)
ret = subprocess.Popen(cmd, shell=True).wait()
if ret != 0:
print "error doing string replacement"
sys.exit(1)
You do not need to read in your entire files at once. If they are large this could be a lot of memory. You can consume a line at a time, and you can also make use of what is called "context managers" when you open the files. This will ensure they close properly no matter what happens:
We start with a subprocess command that is run only once to find all your .tml files. Your version had the same command being run multiple times. If the search path is the same, then we only need it once. This checks the exit code of the command and quits if it failed.
We loop over stdout on the subprocess command, and add the stripped lines to a list. This is a more robust way of your replace("\r\n"). It removes whitespace. A "list comprehension" would be better suited here (down the line). If we didn't find any tml files, then we have no work to do, so we exit. Otherwise, we join them together in a space-separated string to be suitable for our command later.
This is called "context managers". You can open the file in a way that no matter what they will be closed properly. The file is open for the length of the context within that code block. We are going to loop forever, and break when appropriate.
We pull a line, one at a time, from each file. If either line is blank, we reached the end of the file and cannot do any more work, so we break out. We then strip the newlines, and if either string is empty (blank line) we still can't do any work, but we just continue to the next available line.
A modified version of your sed command. We construct the command string on each loop for the source and replacement strings, and tack on the tml file string. Bear in mind this is a very naive approach to the replacement. It really expects your replacement strings to be safe characters and not break the s///g sed format. But we run that with another subprocess command. The wait() simply waits for the return code, and we check it for an error. This approach replaces your os.system() version.
Hope this helps. Eventually you can improve this to do more checking and safe operations.