So i made an application with multiple Powershell commands. They work perfectly when i run it through Visual Studio, but when i publish the application and run the .exe then for some reason the commands dont work, even on my pc and they give me errors i have tried changing the command itself but whatever command i type i keep getting the error from powershell.
// These are 2 of the commands i use
Get-LocalUser -Name Almar
Get-LocalUser -Name Almar.Description
// I run them using a Process function
Process cmd2 = new Process();
cmd2.StartInfo.FileName = $#"powershell ";
cmd2.StartInfo.Arguments = $#"Get-LocalUser -Name Almar.Description";
cmd2.StartInfo.RedirectStandardInput = true;
cmd2.StartInfo.RedirectStandardOutput = true;
cmd2.StartInfo.CreateNoWindow = true;
cmd2.StartInfo.UseShellExecute = false;
cmd2.Start();
cmd2.WaitForExit();
StreamReader reader = cmd2.StandardOutput;
string output = reader.ReadToEnd();
Even when i open a Command prompt or a powershell these commands work, only when i publish it and run it as an .exe it gives me errors.
Here's a screenshot of my publishing settings
Here's a screenshot of when i try to run the published .exe
As i said in the beginning, when i run the application in Visual Studio all the commands work but for some reason when the .exe is ran it just gives me errors.
If anyone know's why this is or did i mess something up while publishing please let me know.
Related
I am trying to execute a Powershell script remotely that will launch an accdb file via MSAccess. I am able to get the Powershell script to execute successfully, but MSAccess is not launching since I know that the test.accdb file that I have is not getting updated. What am I missing in my code in order to be able to launch MSAccess? Or is it not possible?
My code is running in a Windows 2012 R2 environment in IIS and is being executed by a service account that has Admin privileges to the machine. If I run the code logged in as that service account, it works fine without issues. If I execute it remotely, only part of the code is executed
My code for the .NET app is as follows (running under service account). I've changed some of the private information, but it doesn't effect the code.
internal static HttpStatusCode ExecuteRemoteCommand()
{
WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
connectioninfo.ComputerName = "testcomputer";
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
var re = ps.AddScript(#"\\testcomputer\test\StartTest.ps1");
var results = re.Invoke();
}
}
return HttpStatusCode.Created;
}
My Powershell code is as follows:
try {
$msAccess = "C:\Program Files (x86)\Microsoft Office\Office14\msaccess.exe"
$fileLocation = "C:\test\DBT.accdb"
Start-Process -FilePath $msAccess -ArgumentList $fileLocation -Verb RunAs -WindowStyle Hidden -WorkingDirectory "C:\test"
$today = Get-Date
"SUCCESS: " + $today > "c:\test\TestExecutionSuccess.txt"
}
Catch
{
$_.Exception.Message > "c:\test\TestExecutionError.txt"
}
In both cases, the one where I run the script locally and the one where I execute it remotely, the TestExecutionSuccess.txt file is created.
However, in ONLY the local test run is the DBT.accdb file updated.
So lets talk about the problems
1 : You can run the code and open Excel when you run the code under your User account logged in.
2 : You can run the code and open Excel when you run the code under your the service account logged in.
3 : you can you the code But Excel will not load if you are not logged into the user.
Why?
This is about Interactive flag. When you are logged into a user then you have can load up GUI's using COM. If you are not logged into a user then you can not load a GUI.
Here is a more indeepth explanation from
Microsoft Interactive User
With ArcSet's guidance, I think I was able to figure out what the issue was. His answer led me down the path of investigating which version of powershell was running. Turned out the C# code was running Powershell x64 instead of x86 (32-bit) version. The office installation is 32-bit and hence why I couldn't run MSAccess.
I couldn't figure out how to run x86 version of Powershell from the C# code, but what I did was put the launch of MSAccess into a batch file and then executed the batch file from my powershell code. Not super clean, but it worked. Access is now running properly.
Here is the batch file code:
cd "C:\Program Files (x86)\Microsoft Office\Office14"
MSACCESS.EXE C:\test\DBT.accdb
and the new version of the PowerShell script:
try {
$msAccess = "C:\Program Files (x86)\Microsoft Office\Office14\msaccess.exe"
$fileLocation = "C:\test\executeTest.bat"
cmd.exe /c $fileLocation
$today = Get-Date
"SUCCESS: " + $today > "c:\test\TestExecutionSuccess.txt"
}
Catch
{
$_.Exception.Message > "c:\test\TestExecutionError.txt"
}
I am trying to start a .exe program from the build runner, but I don't want it to run in the teamcity console, I want a brand new console that runs independently from the current build. So far I have tried a few things without any success.
Tried with a powershell script:
$ErrorMessage = "POWERSHELL ERROR"
try {
Write-Output "About to start backend"
Start-Process Program.exe
Write-Output "Started backend"
} Catch {
Write-Output $ErrorMessage
exit(1)
}
Tried starting a new console with this command:
Start Program.exe
I'm starting to wonder if it's even possible.
Start-Process powershell -ArgumentList #("-NoExit", "-Command Start-Process cmd")
I got the answer from the teamcity forum, thought I might share it here though. My problem was caused to an issue with the build agent caused by windows.
Check out the full explanation here.
To solve the problem, you need to run the agent by running the command "agent.bat run" in the agent's bin folder under your installation directory.
I want to automate my Database creation. there are three Databases to create, I have a different powershell script for each DB creation. Now upon this powershell script i have one more layer batch file this batch file will invokes powershell script.
say #"D:\Parent\Sub\InstallDB1.cmd"; will invoke #"D:\Parent\Powerscript1.ps1 like wise two other.
Now i have single batch file say FinalDB.cmd. The batch file FinalDB.cmd. will invoke three command scripts one after the other will internally call powershell script.
So now the calls in `FinalDB.cmd`
call InstallDB1.cmd //comment: which internally calls Powerscript1.ps1.
call InstallDB2.cmd //comment: which internally calls Powerscript2.ps1.
call InstallDB3.cmd //comment: which internally calls Powerscript3.ps1.
I cant avoid the above scenario because of my application design.
If I run the Final script manually by double clicking, the DB creation process happening without any fail.But failing when i use following C# code to invoke the FinalDB.cmd.
public static RunCommand RunCommandInDir(string workingDirectory, string arguments, string executablePath)
{
RunCommand runResults = new RunCommand
{
Output = new StringBuilder(),
Error = new StringBuilder(),
RunException = null
};
try
{
using (Process proc = new Process())
{
proc.StartInfo.FileName = executablePath;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.WorkingDirectory = workingDirectory;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = false;
proc.OutputDataReceived +=
(o, e) => runResults.Output.Append(e.Data).Append(Environment.NewLine);
proc.ErrorDataReceived +=
(o, e) => runResults.Error.Append(e.Data).Append(Environment.NewLine);
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
runResults.ExitCode = proc.ExitCode;
}
}
catch (Exception e)
{
runResults.RunException = e;
}
return runResults;
}
When i invoke using the above code i am getting the error "Invoke-Sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program", which was not happening when i run my FinalDB.cmd file manually.
I have done the my googling it seems none of the suggested approaches are working.
Any help to fix the issue?Why does the error is coming when i use C# code.
thanks
Invoke-SQLCmd is a cmdlet provided either by the snap-in SqlServerCmdletSnapin100 (prior to SQL Server 2012) or module SQLPS (SQL Server 2012+). You need one or the other loaded into PowerShell (for example, at the beginning of your script) before you can call the cmdlet.
Here is the solution i found my self:
It seems some of the components related to sql server is not installed so i followed the following steps.
Step1:
Open Visual studio Command prompt:
If you have Visual Studio installed on your computer: On the taskbar, click Start, click All Programs, click Visual Studio, click
Visual Studio Tools, and then click Visual Studio Command Prompt.
Step2:
Search the dll file Microsoft.SqlServer.Management.PSProvider.dll in your c: drive which I found under
C:\Program Files (x86)\Microsoft SQL Server\100\Tools\PowerShell\Modules\SQLPS
or it may be under different path
Copy following dlls and paste under the location where your visual studio command window is pointing. So that you can run the
installUtil command from your visual studio command window
Microsoft.SqlServer.Management.PSProvider.dll
Microsoft.SqlServer.Management.PSSnapins.dll
Step3:
Run the Following commands from Visual studio Command prompt
installutil Microsoft.SqlServer.Management.PSProvider.dll
installutil Microsoft.SqlServer.Management.PSSnapins.dll
In my case, I had this error when I had a new development machine. Suddently, a powershell script that worked well started failing. It was because PowerShell Extensions for SQL Server 2008 R2 wasn't installed on the new machine.
Simply, you can download and install it from here. http://www.microsoft.com/en-us/download/details.aspx?id=16978#PowerShell
i'm trying to execute a .bat file through a c# console application using code from here:
Service hangs up at WaitForExit after calling batch file
Kevin's solution kinda works, but some commands in my .bat file get ignored for some reason, but when i manually execute the .bat file all commands work just fine.
e.g. xcopy command doesn't work while executing .bat from console app, but start command works fine.
Any idea why this happens?
p.s. recently i found that if the program is being launched from command prompt, it works well. How come? Still i need to put it on autorun, so this doesn't solve the problem.
Also, if launched by clicking on exe file, output shows
xcopy folder1 folder2
but if launched from command prompt, output shows
xcopy folder1 folder2
smth/smth.smth copied
....
5 files copied.
And it actually is being copied.
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout * NO_MILLISECONDS_IN_A_SECOND *
NO_SECONDS_IN_A_MINUTE
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
Batch file commands do not get ignored when you execute the command processor from a service. They however easily fail and can do so unobserved since you cannot see their output. Typical reasons for failure are having the ProcessStartInfo.WorkingDirectory not set correctly so that relative paths no longer work or trouble caused by the service running with a different user account that doesn't have the same rights as the one you use from the desktop.
Diagnose problems by redirecting output to a file, run cmd.exe /c and use the > operator. Append 2>&1 so that the file contains both regular and error output. And by using the %errorlevel% variable and EXIT command judiciously so you can discover that execution failed by using the Process.ExitCode property.
public void runBatchfile(String batchfilename)
{
try
{
ProcessStartInfo processInfo = new ProcessStartInfo(batchfilename);
processInfo.UseShellExecute = false;
Process batchProcess = new Process();
batchProcess.StartInfo = processInfo;
batchProcess.StartInfo.CreateNoWindow = true;
batchProcess.Start();
batchProcess.WaitForExit();
}
catch (Exception r) { }
}
runBatchfile(#"c:\lol.bat");
lol.bat contains these 2 lines
dir c:\ /s /b > c:\filelist.txt
exit
and when I run my code all it does is creating a filelist.txt file, but doesn't actually perform the rest of the command, which does work if I manually insert it into CMD.
Btw I've tried making the extension .cmd and I also tried without the exit command, without any other results.
please help me :)
On my Windows 7 64-bit machine with Visual Studio 2010, running this code straight from the IDE doesn't do anything whatsoever.
On a hunch that it might have something to do with permission to write to the root directory of drive C:, I tried running the .exe directly from an Explorer window with admin rights (right-click, Run as Administrator) and that worked.
I'd say it's a permission problem.
Maybe you could redirect the output to a file located elsewhere?
update:
I changed the batch file so that the dir command gets redirected to my desktop and it runs just fine.
I've had issues with this as well when calling from C#. The workaround that I usually use is to physically allow it to show the window when running the command. Not sure why this makes a difference but it has worked for me in the past.