We have a very old tool that our company uses that runs some basic command line scripts to deploy some text files to our servers. It works well, but the process is repetitive.
When the exe runs it does 3 prompts...
"Enter The destination Folder"
"Enter The Server"
"Enter the Password"
We have to do this for about 10 servers, and its sitting there doing a lot of copy paste. Since this process was created everything has been standardized.
So I wanted to make a powershell script that ran the exe process and basically pasted the 3 pieces of information and just loop the server name..
I THOUGHT I had the process working using SendKeys... but even though it appeared to work in every way... it never ACTUALLY did anything. So im not sure if the exe did not like send keys or what.
So then I resolved to trying to use Send Keys outside of Windows forms and launch cmd.exe and run it that way.
That way seemed to work as well, but the results were the same, the files were never updated.
If I did this process manually in powerhsell they worked fine though.
My final attempt was doing this.
try {
$MyProcess = New-Object System.Diagnostics.Process
$MyProcess.StartInfo.FileName = "c:\MyProcess.exe"
$MyProcess.StartInfo.Arguments = "arguments for process"
$MyProcess.StartInfo.UseShellExecute = $false
$MyProcess.StartInfo.RedirectStandardInput = $true
$MyProcess.Start()
$StdIn = $MyProcess.StandardInput
$StdIn.WriteLine($destinationFolder)
$StdIn.WriteLine($server)
$StdIn.WriteLine($password)
} finally {
if($StdIn) {
$StdIn.Close()
}
This process DOES update the files, however I cannot loop it, because as soon as the first exe finishes the script crashes with the error
"Cannot Read Keys when Either application does not have a console or when a console inout has been redirected"
I am looking for a way to get this to work...
Related
I am fairly new to writing code in Powershell. For my job I have to write multiple Powershell scripts to make changes in the Hardware and Software settings as well as the Registry and Group Policy Editor to get these applications to run. These applications are a little older. Upgrading these software applications or the hardware then run on is NOT an option. as an example, when Microsoft releases the new patches on like Patch Tuesday...when those patches are applied there is a high probability that something will be changed which is where I come in to write a script to fix the issue. I have multiple scripts that I run. When those scripts are ran they may end up terminating because of an Error Code or an Exit Code. A large part of the time I do not that the script has failed immediately.
I am trying to figure out a script that I can run in a 2nd PowerShell Console Window. I am thinking that the only purpose of this script is to just sit there on the screen and wait and monitor. Then when I execute a script or Application (the only file extensions that I am worried about are: EXE, BAT, CMD, PS1) if the script/application that I just ran ends with an exit code or an error code....then output that to the screen...in REAL TIME.
Below, I have a small piece of code that kind of works, but it is not what I am wanting.
I have researched online and read and read tons of stuff. But I just can't seem to find what I am looking for.
Could someone please help me with getting a script that will do what I am wanting.
Thank you for your help!!!!
$ExitErrorCode =
"C:\ThisFolder\ThatFolder\AnotherFolder\SomeApplication.EXE # (this
would
# either be an EXE or CMD or BAT or PS1)"
$proc = Start-Process $ExitErrorCode -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Possible duplicate of the approaches shown here:
Monitoring jobs in a PowerShell session from another PowerShell session
Monitoring jobs in a PowerShell session from another PowerShell session
PowerShell script to monitor a log and output progress to another
PowerShell script to monitor a log and output progress to another
I have a .bat file that starts up a powershell script.
Within this powershell script, i startup PowerBI with a given database.
The powershell script waits till powerBI has been done starting up, and will then be exporting data to some datadump files.
Doing this manually works fine, and also when its on the task scheduler to run when user is logged on.
The moment i change this to "Run whether user is logged on or not" it doesnt work anymore.
The reason behind this, is that it seems that powershell is unable to start PowerBI and therefore there is no open data to query in the rest of the script.
So the positive side is it runs the bat and powershell just fine, only the powershell itself seems incapable to start powerBI.
Are there any solutions to this? should i for example use a different method to call the appliation to start?
currently the powershell snippit to start the app looks like this:
$PBIDesktop = "C:\Program Files\Microsoft Power BI Desktop\bin\PBIDesktop.exe"
$template = "C:\LiveData\Data.pbix"
$waitoPBD = 60
$app = START-PROCESS $PBIDesktop $template -PassThru
log_message "Waiting $($waitoPBD) seconds for PBI to launch"
Start-Sleep -s $waitoPBD
I faced similar issue. So, sharing my experience..
First of all, please verify couple of things.
Specify user account which will be used to invoke the job. Also, ensure that, the account have sufficient permission.
Don't forget to un-check the checkbox (as shown in screenshot) under Conditions Tab
Just found this one - sorry it took so long :D
But, i had this totally nervwrecking issue to.
Solution for me is to realize that the task scheduler is very deep part of the OS.
Thats why i have to grant access to the file, for the computername$ (system name) on the file or folder containing the file to run.
Rightclick on the file or folder -> Security. Select edit and add [Name of your computer]$ and give the read and execute permissions.
That's the only way I can make it run.
But i hope you found the solution in the meantime :)
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.
I have a scheduled task set to run on a machine overnight. This task will iterate through a folder printing all the files found therein. I can run the process without issue while logged in however it does not print when run via the scheduled task.
More Info:
The scheduled task executes a powershell script that performs multiple functions such as generating and emailing reports, copying files across network folders and finally printing the contents of a folder. All of these tasks are performed without error if the executing account is currently logged in. If the account is not logged in and run via a scheduled task everything except the printing of Office and PDF documents works correctly (Text documents print fine).
Here is the function I am using to print the documents.
Function Print-File($file)
{
begin
{
function internal-printfile($thefile)
{
if ($thefile -is [string])
{
$filename = $thefile
}
else
{
if ($thefile.FullName -is [string] )
{
$filename = $thefile.FullName
}
}
$start = new-object System.Diagnostics.ProcessStartInfo $filename
$start.Verb = "print"
[System.Diagnostics.Process]::Start($start)
}
if ($file -ne $null)
{
$filespecified = $true;
internal-printfile $file
}
}
process
{
if (!$filespecified)
{
$test = write-Host process ; internal-printfile $_
}
}
}
When running from a scheduled task I can see the process start (Winword or AcroRd32) as I am dumping output to a text file however I do not see anything print. One other difference I noticed is that when I use this function while logged in the Applications other than Adobe reader (Office Apps) start to print the document then close. However when run from a scheduled task the applications do not close on their own.
I would appreciate any feedback, suggestions or pointers at this time as I have hit a wall as far as knowing what else I can check. I would also take suggestions as to an alternative way to accomplish the printing of the files. (NOTE: I cannot predict the file type in the folder)
NOTE: These symptoms are present on two machines, Windows server 2008 and Windows 7, both running Office 2007 and Adobe Reader 10.1.7
I'm trying to do the same thing that you are attempting. I'm pretty sure what you're running into is session 0 isolation. You can read more about it at this MSDN site and this Windows blog post.
I haven't tried the suggestions in the following answer to another question on SO, but it might be worth a try.
Creating Desktop-Folders for session 0
Here is another guy who is trying to print without having a user logged into the machine. There is an answer from someone who claims to know how to do what we're all trying to do, but he doesn't actually post the answer.
Too late for OP, but for future readers... I had the same problem, but with a windows shell .bat file, not PowerShell. As a scheduled task, the script would launch AcroRd32.exe /t, but it wouldn't print anything. Then after a delay, Acrobat was stopped, and the file was moved to the "Printed" folder like everything was good. It printed fine standalone, just not as a scheduled task.
(Background: I'm running Windows 10 x86 on one older computer so that we can use our two bulletproof HP LaserJet 1000 printers. However, the program we used for this in Win 7, batchdocprint, is incompatible with Win 10 and the company is gone. Due to having to learn arcane syntax and workarounds, I've spent way more money in hours getting a few lines of code (below) working right than the program cost, but I couldn't find a suitable replacement. The programs that I found either printed incorrectly, or had options for only one printer.)
The problem for me did seem to be Session 0 isolation blocking GDI+. I went with the seemingly "spammy" suggestion of getting Foxit Reader. It worked, and like Acrobat, the reader is free. I just replaced the path to AcroRd32.exe with the path to FoxitReader.exe
I don't think this will ever be possible with Acrobat Reader. The CLI is not officially supported, so the likelihood of Adobe ever changing it to print without launching the GUI is minimal.
As far as other file types, it depends on what you're using to print them, and whether it can open and print without a GUI. I haven't decided whether to implement this for other common file types so that we can just drag-and-drop, or to keep forcing the users to use the Acrobat PDF printers that are set up to save PDFs in the hot folders. Right now, it's the latter.
My code, for reference, to hopefully save someone else my headache. I only changed/shortened names, and removed duplicate code for the second folder/printer. Note that taskkill requires administrative privileges. Also, you probably need to have a folder named "Printed" in your hot folder, since I don't check for its existence:
#ECHO OFF
REM Monitors folders for PDF's and prints.
REM Use PING for delay - no built-in sleep functionality.
REM Using START backgrounds the process so the script can move on.
:LOOP
cd C:\Hot Folder\
for %%a in ("*.pdf") do (
start "" "C:\Path\To\FoxitReader.exe" /t "C:\Hot Folder\%%a" "HP 1000"
ping 1.1.1.1 -n 2 -w 5000 >NUL
taskkill /IM FoxitReader.exe /F
move /Y "%%a" ".\Printed\%%a")
ping 1.1.1.1 -n 2 -w 5000 >NUL
goto LOOP
Not sure if you ever found the solution to this, but it happens that the printer to be used by task scheduler job should be registered under:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers (local printers)
vs
HKEY_Current_User\Printers\Connections (session printers)
Wrote the following in PowersHell as a quick iTunes demonstration:
$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
foreach ($PList in $LibrarySource.Playlists)
{
write-host $PList.name
}
This works well and pulls back a list of playlist names.
However on trying to close iTunes a warning appears
One or more applications are using the iTunes scripting interface. Are you sure you want to quit?
Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?
Itunes 7.7.1, Windows XP
Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)
I also run my scripts the majority of time from a shortcut, not from the powershell prompt.
Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message.
One method of running your script from powershell, is to prefix your script with powershell.
powershell .\scriptname.ps1
The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.
You should be able to set $itunes to $null. Alternatively, $itunes should have a quit method you can call. $itunes.quit()