I would like to make a self updater in c++. I have seen this post of how to delete itself after execution.
How to write a program in C++ such that it will delete itself after execution?
I would like my program to run this powershell code after execution:Image
And afterwards run the newFile.exe.
I already tried to get it to work but no luck. If I do CreateProcess() does the szCmd need to be delayed?
Thanks in advance :)
EDIT :
I almost got it the way I wanted it to, the code:
void shellMove(std::string source, std::string target) {
STARTUPINFOA si = { 0 };
PROCESS_INFORMATION pi = { 0 };
std::string str = "powershell.exe Move-Item -Path " + source + " -Destination " + target + " -Force; " + target;
LPSTR s = const_cast<char*>(str.c_str());
CreateProcessA(NULL, s, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
std::string getDirPath() {
char buffer[MAX_PATH] = { 0 };
GetModuleFileNameA(NULL, buffer, MAX_PATH);
return std::string(buffer).substr(0, std::string(buffer).find_last_of("\\"));
}
std::string getFilePath() {
char buffer[MAX_PATH] = { 0 };
GetModuleFileNameA(NULL, buffer, MAX_PATH);
return std::string(buffer);
}
void main() {
std::string fileName = "Test.exe";
shellMove(getDirPath() + "\\" + fileName + "~", getDirPath() + "\\" + fileName);
}
The problem is, the Test.exe is a c++ console app, which means if I do:
std::string str = "powershell.exe Move-Item -Path " + source + " -Destination " + target
+ " -Force; " + target;
+target; it starts the console app with Powershell :/ I would like it to start with the normal console, how to do this? please help thanks :)
possible delete self exe without create external process, which will be wait on our process terminate.
idea from Jonas L
or NT version of this code
tested and worked on win 7, 8.1, 10. but think this is bug in ntfs implementation.
file is really deleted, not simply become invisible. the parent folder after this also can be deleted (if no more files in it). checked by call
NtQueryVolumeInformationFilewithFileFsFullSizeInformation-AvailableAllocationUnitsis actually increased on file size and byFSCTL_GET_NTFS_FILE_RECORD( file id is get fromNtQueryInformationFilewithFileInternalInformation) - record became invalid after delete file in such way. if we copy exe back - the SequenceNumber is incremented (if the same MftRecordIndex reused)if want not based on bug and delete buy create child process, possible for example next solution:
here we exec cmd.exe (%ComSpec%) with order do exit - " /C exit\r\n"* command line (when we direct pass application name - system not need parse and modify command line and it can be constant string). and inject 2 APC calls to cmd - first wait for our process exit and then delete file