Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using read-host cmdlet when execute powershell script file in MSBuild

All , I am trying to execute a external power shell script file in the MSBuild. But every time when PS run the cmdlet Read-Host. The MSBuild seems stop. and doesn't prompt me to input . I don't know what happen to it . Seems the console is in deadlock..thanks.

enter image description here

The testloop.ps1 code is shown below.

$ErrorActionPreference = 'Stop'
$error.clear()


function GetAzureSubScription()
{
    read-host "please input something :"
} 

write-host "Get into script"

GetAzureSubScription

The MSBuild code is below (wrapped for clarity):

<Exec WorkingDirectory="$(MSBuildProjectDirectory)" 
    Command="$(windir)\system32\WindowsPowerShell\v1.0\powershell.exe -f
    E:\Work\AutoDeploy\testloop.ps1" />
like image 231
Joe.wang Avatar asked Jan 03 '14 05:01

Joe.wang


2 Answers

So yes, the console (just a minor point - powershell.exe does not run under cmd.exe - they are separate processes, but they both use a console window) window is hidden so it will appear to freeze when prompting for input. The simplest option here is to override the read-host function with a version that will prompt using a graphical window. Add the start of your script, add the following function:

# override the built in prompting, just for this script
function read-host($prompt) {
    $x = 0; $y = 0;
    add-type -assemblyname microsoft.visualbasic
    [Microsoft.VisualBasic.Interaction]::InputBox($prompt,
        "Interactive", "(default value)", $x, $y)
}

Now your script will be able to prompt for values. Also, you should run powershell.exe with the -noninteractive argument to catch any other places where you are accidentally calling interactive host functions. It will not stop the above function from working though.

like image 116
x0n Avatar answered Oct 26 '22 22:10

x0n


The MSBuild Exec tasks starts cmd.exe and let that execute the command. MSbuild has to channel the writes to the console through since the cmd.exe window itself is invisible. It seems the writes do get through, but the reads do not. You can see the same effect if instead of calling powershell you exec a command like "del c:\temp\somefile.txt /p" which asks for confirmation. Although that way it doesn't block, but there is also no way of giving an answer.

That it does not handle reads properly is not that strange. It is a build script, so it should just build and not ask questions. My advice is to have the MSBuild script run without asking questions. If you really need to ask questions, then ask them before calling MSBuild.

like image 36
Lars Truijens Avatar answered Oct 26 '22 22:10

Lars Truijens