Why a Powershell script executes on a previous version of a file that has been changed? - powershell

I am trying to modify several values of a PowerShell script template prior to execution. The approach I took was to use the Get-Content command to read the template file, then to use the replace operand to replace the content with a content of my choosing, and then the Set-Content command to update the file, then execute the script. However, according to the error messages that I encounter, it seems that the modified file is not running, but the template one.
The thing I find hard to understand is why, as I use the Get-Content once again and print the result prior to execution, where I witness that the file did change.
I use simple PowerShell scripting with no threads or so ever, the script is being executed on an Azure VM via the Run-Command feature. I wonder why it happens.
Can anyone please explain?

Related

How to Automate scripts with options in Powershell?

I'm not a native English speaker as such pardon some discrepancy in my question. I'm looking at a way to Automate option selection in Programs/Scripts running via PowerShell.
For example:
Start-Process -FilePath "velociraptor.exe" -ArgumentList "config generate -i"
In the above snipper PowerShell will run Velociraptor and initiate the configuration wizard from a Ps1 file. The Wizard has few options. After running it will generate some Yaml files.
As such what would be the way to have PowerShell Script automate the option selection process? I know what the option should be. I looked around but I don't know proper terms to find what I need. Nor am I sure this can be done with PowerShell.
The end goal is to have the Ps1 download Exe, run the config command and continue with choosing the selection based on predefined choices. So far I gotten download and lunching of the velociraptor.exe working. But not sure how to skip the window in screenshot and have PowerShell script do it instead.
I couldn't find a CLI reference for velociraptor at https://www.velocidex.com/, but, generally speaking, your best bet is to find a non-interactive way to provide the information of interest, via dedicated _parameters_ (possibly pointing to an input file).
Absent that, you can use the following technique to provide successive responses to an external program's interactive prompts, assuming that the program reads the responses from stdin (the standard input stream):
$responses = 'windows', 'foo', 'bar' # List all responses here
$responses | velociraptor.exe config generate -i

Jenkins Inject Environment variable works with batch command but not powershell

I'm dealing with a very weird anomaly in Jenkins that makes absolutely no sense to me. Essentially Jenkins is behaving differently for a powershell command than for a batch command.
My goal is to pass an environment variable (or parameter) from one Jenkins Job to another. However this variable to be passed is generated during the runtime of the first job.
I made a fake project to test passing variables and I was able to do so by adding a build step to echo out the variable into an env.props file on the node and then used the parameterized trigger plugin to call the next job. I was able to get this to work great in this test scenario but when I tried to implement the same steps in the actual build job (which relies on powershell scripts) it did not work.
After, a lot of trial and error I have found that when I use a windows batch command to echo the variable into a props file and then inject the variable into the job - it works perfect. But when I do the exact same thing with a powershell command it does not inject the variable back in to the job even though I use the exact same line of code. It still writes the variable to the file but Jenkins will not "reinject" this variable back into the job's env variable even though I am using the exact same step to do so.
The command is essentially this:
echo Testvar=Somevalue > C:\Jenkins\env.props
Both sucesffuly write the string to the props file, but when done with a powershell command, Jenkins will not absorb the txt from the run. Almost as if powershell is encoding it in a way that Jenkins cannot read but looks the exact same to me.
Any ideas?
Turns out, it was the encoding!
echo "string" > file.txt
does not produce the same result in batch as powershell.
Switching to
echo "string" | out-file -encoding ASCII file.txt
did the trick.

powershell running the code instead of create a new line

I think that my question is something too easy that you guys will solve in 1 minute.
I'm trying to run a script that have multiple lines of code. But, when I write the first line and hits SHIFT+ENTER it runs the code. I need to write a new line, instead of running what I've wrote.
Anybody knows what should I do (instead killing myself because I'm too dumb) ?
In powershell console there are a few ways to make a new line
A. Shift + Enter : Use this at any point to make a new line
B. The opening of a string " or ' until the closing of the string " or ' : use this when you have a string that you wish to span many lines
C. A pipe | : Use this if you have output that you would like to pass to another command
D. The Back tick (escape char) ` : use this to separate lines for a new command or splitting a command into other lines
If you are new to powershell, I would suggest using Powershell ISE. If its installed you can go to the powershell console and type ISE or go to start and type Powershell ISE. This will be a good place to run scripts and debug as you can add breakpoints to your scripts.
The easiest and best way to do this would be to create the script inside of the PowerSheell ISE program. You can then reference this script and run it in the console by preceding it with a .\script.ps1.
If needed you can create script on the command line by creating and writing to the file from the console.
Open the PowerShell console
Run the following command to create a file New-Item script.ps1
Run the next command as many times as it takes to populate the file Add-Content script.ps1 "My code line here"
Run the code using the script run command .\script.ps1
Now let it be known that the ISE is a much better tool because it allows for debugging of files and testing them on demand. The only downside is it will cache whatever it uses or creates (such as variables or references). If you aren't getting the expected result trying closing and reopening to clear the cache run it from the console in tandem. One last thing to note is that if you use the ISE and it successfully runs there that doesn't mean it will run in the console. Be sure to test thoroughly.

Azure startup task, wait for all other task to finish

I have a startup task for my webrole that download some executable file from a blob and then proceed to the installation.
From a .cmd file, I start a power shell script that download the files, then I start the file from the .cmd.
The script works fine if I run it manually through RDP after the publishing is done.
But, when running as startup script, it sometimes (often) fail at different points.
The taskType is set to background.
Last time, the error was that the command PowerShell does not exists...
Also, I use powershell -command set-executionpolicy unrestricted before running my PS script, but I read here that other task may reset this setting and make mine fail.
Quite a mess.
So that makes me think that if I could wait for all other task to perform before starting mine, it would eliminate these kinds of problems
I suppose I could check if some process is running and wait for it to finish, but I have no clue wich process to check.
Or maybe there's another solution.
~edit~
I read here that the error about powershell not existing may be caused by the batch file being saved as UTF-8 in visual studio. I re-writed it from scratch in notepad++ and made sure it is save as ANSI. Then, same error. The full message is :
'PowerShell' is not recognized as an internal or external command,
operable program or batch file.
Again, the script run perfectly from command line in remote desktop.
It would be possible to set an environment variable at the end of the script that is required to finish, then in the script which is awaiting the dependencies, loop until the environment variable is set, then kick off its activities.
You could also run everything from a single powershell script and use the '-asjob' switch on your installer statement, use the 'wait-job' cmdlet to block until the task is complete then carry on. Powershell also offers a '?!' operator which ensures the last statement executed properly.
This might be caused by an encoding issue. As mentioned in this answer you should save your file in ASCII to ensure correct interpretation of your script.
From the linked answer:
Open your whatever.cmd file with your VS 2012 Ultimate. Click on File->Save whatever.cmd as -> on the dialog there is little arrow next to the [save] button. It will show up a menu that will have the option Save with Encoding.
Select it. Now choose "US-ASCII Codepage 20127" from the list of available encodings.

PowerShell: send console output to file without deafening this console output

I have a lot of PowerShell script. One main, that calls other, child ones. Those PS scripts in their turn call windows CMD scripts, bash scripts and console applications. All these scripts and applications write messages to console. PowerShell scripts, for example, are using Write-Host scriptlet for this purpose.
Question: how can I easely redirect (send) all this console output to some file, while not deafening (canceling) this console output? I want to be able to see whats going on from console output and also have history of messages in log file.
Thanks.
You can use the tee equivalent of PowerShell : Tee-Object
PS: serverfault.com and/or superuser.com are more suitable for a question like this.
You can try Start-Transcript and Stop-Transcript. It has a couple of limitations like not capturing native exe output. It is also global to PowerShell session.
I've found script for grabbing console output: http://gallery.technet.microsoft.com/scriptcenter/e8fbffde-7d95-42d9-81de-5eb3d9c089e0. Script returns HTML to preserve colors.
The only big downside - you must call it at the end of your script to capture all console output it have made.
You'd probably need to write a custom host to do this. It's not a terribly hard thing to do, but it's does require some managed code.