Just need a little help with a Powershell Script.
I have a last messagebox on my script. what i want to accomplish is bring the messagebox in front of all the windows.
cmdlet that i use is
$end=[system.Windows.Forms.Messagebox]::Show('StartUP Tool Progress Completed!','StartUP Warning')
Alternatively, if all you need is a message box you can use the Wscript Shell:
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("StartUP Tool Progress Completed",0,"Completed",0x0)
For more information: Popup Method
This is a WinForms question, more than a PowerShell question. You'll need to pass in Form.ActiveForm. Form.ActiveForm would give you the currently active form, even if you are raising your MessageBox from any other class.
However, I think you might want to look at Read-Host -AsSecureString or, more preferably, Get-Credential if the prompt is for confidential data.
Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
Thankfully, PowerShell has a lot of built-in help for launching dialogs. You're trying to ask for parameters.
You should use the
[Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters. Read up on "params" if you haven't already.
If you use Parameter attribute on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.
Finally, you can try this dirty trick, leveraging Microsoft Visual basic DLLs:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$computer = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a computer name", "Computer", "$env:computername")
Related
I have a VB application, which starts several instances of a third party non-GUI application. To keep track of these multiple instances, I update their title, using the SetWindowText() function. This application however has the nasty habit of continuously updating the title, so each SetWindowText works only temporary. As soon as you click anywhere in the screen, the tile is changed back.
I found a way to update the title through PowerShell, using the following code:
$titletext = "My Title"
# Start a thread job to change the window title to $titletext
$null = Start-ThreadJob { param( $rawUI, $windowTitle )
Start-Sleep -s 2
if ( $rawUI.WindowTitle -ne $windowTitle ) {
$rawUI.WindowTitle = $windowTitle
}
}-ArgumentList $host.ui.RawUI, $titletext
& 'c:\Program Files\Application\Application.exe' '-id=userid -pass=password'
This works perfectly and the title change is permanent, so exactly what I want. The only problem is that everything is being logged in the Windows PowerShell log, including the parameters -id= and -pass=.
A solution would be if I can start application.exe through my VB application and do the rename through a PowerShell script, but I don't know if that is possible through a ThreadJob.
Is it possible to start a ThreadJob and rename another window, maybe through it's handle?
Changing the console title from inside that console is your best bet, which is what your PowerShell code does.
While it is possible to call the SetWindowText() API function to set another process' console-window title, this change isn't guaranteed to stay in effect, because any subsequent interaction with such a window causes the original window title to be restored (this behavior seems to be built into conhost.exe, the console host underlying regular console windows on Windows).
By contrast, setting the title of the console window associated with the current process, does stay in effect (unless overridden again later), which is what the SetConsoleWindow() WinAPI function does (which shell- and API-based mechanisms such as title in cmd.exe, and [Console]::Title / $hostUI.RawUI.WindowTitle in PowerShell presumably ultimately call).
Therefore, stick with your PowerShell approach and avoid the password-logging problem with the help of an environment variable, as detailed below.
Windows PowerShell's script-block logging - see about_Logging - logs the source code of code being created.
You can avoid argument values from being logged if you - instead of providing literal arguments - provide them indirectly, via variables that you set from outside PowerShell.
Therefore:
Make your VB.NET application (temporarily) set an environment variable that contains the password. (Perhaps needless to say, storing and passing plain-text passwords is best avoided).
In your PowerShell script, refer to that environment variable instead of passing a literal password - that way, the actual password will not be shown in the logs.
For example, assuming that your VB.NET application has created environment variable MYPWD containing the password, before launching the PowerShell script:
$titletext = "My Title"
# Start a thread job to change the window title to $titletext
$null = Start-ThreadJob { param( $rawUI, $windowTitle )
Start-Sleep -s 2
if ( $rawUI.WindowTitle -ne $windowTitle ) {
$rawUI.WindowTitle = $windowTitle
}
} -ArgumentList $host.ui.RawUI, $titletext
# Note:
# * Assumes that your VB.NET application has set env. var. "MYPWD".
# * The arguments must be passed *individually*, not inside a single string.
& 'c:\Program Files\Application\Application.exe' -id=userid "-pass=$env:MYPWD"
I have a general question regarding the possibilities of Powershell, which I am learning at the moment. As practice I wanted to create a simple script which automatically starts steam and logs me in. I got the following:
$steamExe = (Get-ItemProperty -Path HKCU:\Software\Valve\Steam\ -Name SteamExe).SteamExe
Invoke-Item $steamExe
After this the steam window pops up and Im not sure how to continue.
Can I reference and type into the input fields of the Username and Password?
I am trying to generate a shortcut for every printer I have on a print server. The idea is to be able to email these shortcuts to people and when they click on them, it automatically installs that printer for them.
I've populated an array from a list of printer names exported from the print server:
$list = #((get-contnet $home\dekstop\plist.txt))
I then created a method to create a shortcut:
function Make-Shortcut
{
param ([string]$dest, [string]$source)
$WshShell = New-Object -comObject Wscript.Shell
$Shortcut = $WshShell.CreateShortcut($dest)
$Shortcut.TargetPath = $Source
$Shortcut.Save()
}
The function works fine. I was able to create standard shortcuts with no problem.
This next part is where I am getting stuck:
foreach ($i in $list)
{
Make-Shortcut "C:\pshort\$i.lnk" "C:\Windows\System32\rundll32.exe
printui.dll,PrintUIEntry /in /q /n\\printserver\$i"
}
When this runs, it does generate a shortcut with the same name as the printer for each printer on the list. However, the problem comes in at the target path. Instead of
C:\Windows\System32\rundll32.exe printui.dll,PrintUIEntry /in /q /n\\printserver\printername
it changes it to:
C:\Windows\System32\rundll32.exe printui.dll,PrintUIEntry \in \q \n\printserver\printername
The three problems with this are:
It is reversing the forward slash for the parameters
It is removing one of the backslashes preceding the server name
It is adding quotes to both sides. I need the quotes to come off for the shortcut to work properly.
I assume this is happening because Powershell thinks I am trying to make a standard shortcut and thinks I made mistakes while typing out the path.
I have tried putting a ` in front of each forward slash hoping the escape character would prevent it from reversing it, but no luck. I also tried using a hyphen for each parameter but that did not work either.
Is there anyway to stop this from happening? Or is there perhaps a better way to try to accomplish what I am trying to do?
You need to add arguments to the com object
Try adding a new param $arguments to your Make-Shortcut function and do:
Make-Shortcut "C:\pshort\$i.lnk" "C:\Windows\System32\rundll32.exe"
"printui.dll,PrintUIEntry /in /q /n\\printserver\$i"
add this in your function:
$Shortcut.Arguments = $arguments
So the link is created successfully ... but I have no idea if it works :)
Completely different answer but in a standard windows environment simply clicking a hyperlink to \printserver\printer will add a shared printer to someone's system?
So an email that simply lists :
\\PrintServer\Printer01
\\PrintServer\Printer02
\\PrintServer\Printer03
Would probably do the job just as well.
I want to prompt the user for a series of inputs, including a password and a filename.
I have an example of using host.ui.prompt, which seems sensible, but I can't understand the return.
Is there a better way to get user input in PowerShell?
Read-Host is a simple option for getting string input from a user.
$name = Read-Host 'What is your username?'
To hide passwords you can use:
$pass = Read-Host 'What is your password?' -AsSecureString
To convert the password to plain text:
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in #Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].
To access information without invoking a method, leave the parentheses off:
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
As an alternative, you could add it as a script parameter for input as part of script execution
param(
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
)
See Title.
I specified needed parameters in the head of a script:
param ($G_ARCHIVE = $(throw "Need file to upload!"),
$G_LOGFILE = $(throw "Need logfile!"))
When I want to debug the script with Powershell ISE: how can I fill these parameters?
Use the command pane. Open the script file in the ISE editor, set the breakpoints (F9). Then in the command pane type a command invoking this script with required parameters. I do not think there is another (built-in) way of doing this in ISE.
Open the script (myscript.ps1) in Windows Powershell ISE
Press F9 at the variable you want to inspect (debug). For instance 2nd line in the sample below where the $outputText variable is being assigned
In the shell window provide the relative path of the script along with the param value. For instance: .\myscript.ps1 "my value"
Hit enter (you don't need to hit F5)
You'll be able to see the debugging breakpoints in highlighted with yellow color. Place your cursor to the desired variable to inspect the current value.
There is another way. You can use the $PSDefaultParameterValues automatic variable, which exists (since v3) to provide new default arguments to cmdlets and advanced functions (doesn't work with normal functions). However, it does work for scripts, even when debugging in ISE. You have to declare [CmdletBinding()] or [Parameter()] like you would for an advanced function.
So for your example,
[CmdletBinding()]
param ($G_ARCHIVE = $(throw "Need file to upload!"),
$G_LOGFILE = $(throw "Need logfile!"))
you would execute something like this on the ISE Prompt:
$PSDefaultParameterValues.add("ExampleScript.ps1:G_ARCHIVE","File-to-upload.txt")
$PSDefaultParameterValues.add("ExampleScript.ps1:G_LOGFILE","Example.log")
You could also set the parameter value to a script block which will auto-execute at run-time:
$PSDefaultParameterValues["ExampleScript.ps1:G_LOGFILE"]={
"Example-{0:yyMMddHHmm}.log" -f [datetime]::Now
}
The variable is a hashtable and all the standard syntax applies, except the key must have the name of the script (or advanced function or cmdlet) followed by a colon then the parameter name. You can set defaults for multiple scripts or commands, and multiple parameters for each (each parameter is a new table entry).
By doing it this way, you can just hit F5 to run your script like normal. The parameters will be taken from the variable, so you don't have to type anything in.
Other use cases for $PSDefaultParameterValues might be customizations, like have the Get-History get only the last 10 entries, unless you specify the -Count parameter in the command. Because entries only persist for the current session, you would want to add customizations to your profile. You can read more by typing Get-Help about_Parameters_Default_Values at the prompt or view the same information on TechNet.
There is a much simpler way to set needed Parameters in ISE:
Before pressing F5 in ISE, set the Parameter you need. I usually comment the Parameter I need, example:
# $G_ARCHIVE = "C:\Temp\TestFile_001.txt"
I select everything after "#" and press F8. Next time I debug the script with F5, the Parameter is set to the value I am testing with, no need to pass the Parameters through the command line.
At least in Powershell 5.1 ISE when you press F5 to run a parameterized script, you will be asked to enter values for the parameters one by one.
When using the $PSDefaultParameterValues to populate the variables, you can reference the loaded script through the $psISE variable like
$PSDefaultParameterValues.add("$($psISE.CurrentFile.DisplayName):G_ARCHIVE","test")
I had this problem today. After messing around I discovered that the lower panel was running in Debug E.g. Prompt '[Dbg]: PS'
I stopped the debugging and re-issued my script with paramaeters.
Example: ./myScript.ps1 -ForceBuild $true
My results were that the script started and the breakpoints fired and allowed me to debug as expected.