Erased System Path Variables - powershell

I was writing a batch file that was supposed to automatically set up a computer to receive "psexec" remote commads. Unluckly i didn't really pay attention to what i was writing and i wrote this command and then ran It:
setx /M Path "C:\Windows\System32\PSTools"
You can imagine what happened... I erased all the other path variables! Then, panicking, mis-reading an online-forum, I restarted the computer. I had no backups, no saving points and neither, obviously, opened cmd's or powershell's session. My questions are:
Is there still a way to recover the path variables i lost or they're gone forever?
If they're gone, is there a way for me to like "re-write" them or just get a list of the missing ones?
I know that my questions will seem stupid to the experienced programmers and i apologise for that, but I actually started this project with almost zero skills in bat, cmd, and the other stuffs...
Thanks to everyone that will help <3

Related

Powershell Remove-Variable cmdlet, do I need to call it at the end of each function/scriptblock?

This is a generic question, no code.
Not sure if I need to remove local variables as I thought it should be done by the Powershell Engine.
I had a script to gather info from WMI and used a lot of local variables. The output was messed up when running multiple times, but it got fixed after I clean up all local variables at the end of function/scriptblock.
Any thoughts/idea would be appreciated.
The trouble do not come from the fact that you do not remove your vars, but by at least from two beginers errors (or done by lazy developpers like me, supposing I'am a developper).
we forget to itialize our vars before using them.
we do not test every returns of our functions or CmdLets calls.
Once these two things done (code multipled by two at least) you can restart your script without cleaning anything except the processed datas.
For me scripting is most of the time done on a corner of a table even not push in a source repository.
So start scripting and ask yourself fewer questions.

Win7-64 %windir%, %path% environment variables disappear, can't reload

I am having recurring intermittent problems with "losing" my environment variables, most onerously %windir% and %path%. The problem occurs when I have locked the keyboard and log back in. Rebooting the system (cold- and warm-boot) does not reliably bring them back, but eventually multiple iterations of booting has (so far) brought everything back.
If I open a command window and type echo %windir% and echo %path% and find that the variables exist and are properly defined, and if I leave that command window open, I can leave my system running for days without a problem.
I have captured the results of set to list all envars, both when the system is broken, and when it is fixed. The broken list is much shorter (%windir% is not even defined, %path% contains the definition from registry HKCU\Environment, but not from HKLM\SYSTEM\CurrentControlSet\Control\SessionManager\Environment).
I am guessing that the boot-up process is getting sidetracked.
Spent all morning with Geek Squad but they had no concrete suggestions. (They did suggest "taking the computer back to a previous restore point", but I fear that could cause more problems... and they didn't have confidence it would help.)
Do I have any options beyond possibly reinstalling everything?
I did finally find the answer, and although I understand this subject was closed by the commenter, I thought others might want to know. This link explains it pretty well:
https://superuser.com/questions/355594/windows-7s-path-and-environment-variables-are-corrupted
The short version is this: My system PATH exceeded a Windows maximum of 2048 bytes (it was more than 2200 bytes long). When that happens, the boot process fails to instantiate PATH and WINDIR.
The "fix" was to run c:\windows\system32\systempropertiesadvanced.exe from a command prompt (because without WINDIR, you can't open the Control Panel app for environment variables), and manually extract anything from the PATH I thought I could live without, until I whittled the PATH string down to under 2048 bytes.

Polluted pipeline troubleshooting

I have a script, in which this code fails, with an exit code of -2145124322
$new.ExitCode > $null
$filePath = "wusa.exe"
$argumentList = "`"\\PX_SERVER\Rollouts\Microsoft\VirtualPC\Windows6.1-KB958559-x64-RefreshPkg.msu`" /quiet /norestart"
$exitCode = (Start-Process -FilePath:$filePath -argumentList:$argumentList -wait -errorAction:Stop -PassThru).ExitCode
Write-Host $exitCode
Now, the main script has about 15,000 lines of "other stuff going on", and these lines where not originally exactly like this. The variables are pulled from XML, there is data validation and try/catch blocks, all sorts of stuff. So, I started pulling the pertinent lines out, and put them in a tiny separate script, and hard coded the variables. And there, it works, I get a nice 3010 exit code and off to the races. So, I took my working code, hard coded variables and all, and pasted it back into the original script, and it breaks again.
So, I moved the code out of the function where it belongs, and just put it after I initialize everything and before I start working through the main loop. And there it works! Now, I gotta believe it's the usual "polluted pipeline", but dang if I can figure out what could cause this. My next step I guess is to just start stepping through the code, dropping this nugget in somewhere, run the test, if it works move it farther down, try again. Gack!
So, hopping someone has some insights. Either what it might be, or perhaps an improved test protocol. Or some trick to actually see the whole pipeline and somehow recognize the pollution.
FWIW, I normally work with PoSH v2, but I have tried this with v4 with the exact same results. But perhaps there is some pipeline monitoring feature in a later version that could help with the troubleshooting?
Also, my understanding is that PoSH v2 has issues with negative return codes, so they can't be trusted. But I think newer versions fixed this, correct? So the fact that I get the same code in v4 means it is meaningful to Google? Not that I have found any hint of that exit code anywhere thus far.
Crossed fingers.
EDIT: OK, a little more data. I searched on the exit code without the -, and with DuckDuckGo instead of Google, and found this.
0x8024001E -2145124322 WU_E_SERVICE_STOP Operation did not complete because the service or system was being shut down.
OK, that's some direction. And I have some code that would allow me to kill a service temporarily. But that seems a little draconian. Isn't the whole point of this, like 10th way to install updates from Microsoft, supposed to be to make automation easier? In any case, I can't find any indication there are command line flags for WUSA that would avoid the problem, but I have to believe I am doing something wrong.
Solved! After tracking a number of different errors trying different things, including turning off the firewall and such, it turns out the error isn't that a service won't stop, but that a service won't start. See, some of that 15K lines of code suppresses Windows Update for the duration of my script, because Windows Update causes lots of Autodesk deployments to fail, which is the whole point of my code. Well, of course WUSA needs that service. So, it looks like, rather than suppressing Windows Update for the duration of script execution, I need to be less heavy handed and only suppress for the duration of a deployment task. that will take a few hours to implement and test, but is totally doable. And probably more elegant anyway. Woot!
And yeah, for once it wasn't me pooping in my pipeline unintentionally. ;)

Perl: system command returns before it is done

I'm using a a few system() commands in my perl script that is running on Linux.
The commands I run with the system() function output their data to a log which I then parse to decide what to do next.
I noticed that sometimes it looks like the code that parses the log file (which comes after the system() function) doesn't use the final log.
For example, I search for a "test pass" phrase in the log file - and the script doesn't find it even though when I open the log it is there.
Another example - I try to delete the folder where the log was placed but it doesn't let me because it's "Not empty". When I try to delete it manually it is deleted with errors.
(These examples happen every now and then, but most of the time they don't)
It looks like some kind of "timing" problem to me. How can I solve it?
If you want to be safe and are on Linux, call system sync; after every command that writes to the disk before reading from the disk. That will force the OS to write everything still buffered to the filesystem and only return afterwards. Thus you can be sure that when it is finished, everything you wrote to files now actually has arrived there.
But be aware, that may be overkill in many situations. There are reasons for those buffers and manually calling sync constantly is most likely not the fastest way of achieving things. See also http://linux.die.net/man/8/sync
If, for example, you have something else that you could do between the writing and the reading, like some calculations or whatever, that would likely be enough and you would not waste time by telling the OS that you know better how and when it has to do it's jobs. ^^
But if perfect efficiency is not your main concern (and you should not be using Perl if it was), system sync; after everything that modifies files and before accessing those files is probably okay and safe.

Finding a Perl memory leak

SOLVED see Edit 2
Hello,
I've been writing a Perl program to handle automatic upgrading of local (proprietary) programs (for the company I work for).
Basically, it runs via cron, and unfortunately has a memory leak (or something similar). The problem is that the leak only happens when I'm not looking (aka when run via cron, not via command line).
My code does not contain any circular (or other) references, so the commonly cited tools will not help me (Devel::Cycle, Devel::Peek).
How would I go about figuring out what is using so much memory that the kernel kills it?
Basically, the code SFTPs into a server (using ```sftp...`` `), calls OpenSSL to verify the file, and then SFTPs more if more files are needed, and installs them (untars them).
I have seen delays (~15 sec) before the first SFTP session, but it has never used so much memory as to be killed (in my presence).
If I can't sort this out, I'll need to re-write in a different language, and that will take precious time.
Edit: The following message is printed out by the kernel which led me to believe it was a memory leak:
[100023.123] Out of memory: kill process 9568 (update.pl) score 325406 or a child
[100023.123] Killed Process 9568 (update.pl)
I don't believe it is an issue with cron because of the stalling (for ~15 sec, sometimes) when running it via the command-line. Also, there are no environmental variables used (at least by what I've written, maybe underlying things do?)
Edit 2: I found the issue myself, with help from the below comment by mobrule (in response to this question). It turns out that the script was called from a crontab of a user (non-root) just once a day and that (non-root privs) caused a special infinite loop situation.
Sorry guys, I feel kinda stupid for not finding this before, but thanks.
mobrule, if you submit your comment as an answer, I will accept it as it lead to me finding the problem.
End Edits
Thanks,
Brian
P.S. I may be able to post small snippets of code, but not the whole thing due to company policy.
You could try using Devel::Size to profile some of your objects. e.g. in the main:: scope (the .pl file itself), do something like this:
use Devel::Size qw(total_size);
foreach my $varname (qw(varname1 varname2 ))
{
print "size used for variable $varname: " . total_size($$varname) . "\n";
}
Compare the actual size used to what you think is a reasonable value for each object. Something suspicious might pop out immediately (e.g. a cache that is massively bloated beyond anything that sounds reasonable).
Other things to try:
Eliminate bits of functionality one at a time to see if suddenly things get a lot better; I'd start with the use of any external libraries
Is the bad behaviour localized to just one particular machine, or one particular operating system? Move the program to other systems to see how its behaviour changes.
(In a separate installation) try upgrading to the latest Perl (5.10.1), and also upgrade all your CPAN modules
How do you know that it's a memory leak? I can think of many other reasons why the OS would kill a program.
The first question I would ask is "Does this program always work correctly from the command line?". If the answer is "No" then I'd fix these issues first.
On the other hand if the answer is "Yes", I would investigate all the differences between having the program executed under cron and from the command line to find out why it is misbehaving.
If it is run by cron, that shouldn't it die after iteration? If that is the case, hard for me to see how a memory leak would be a big deal...
Are you sure it is the script itself, and not the child processes that are using the memory? Perhaps it ends up creating a real lot of ssh sessions , instead of doing a bunch of stuff in one session?