Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Please could somebody recommend a Powershell, mouse tutorial. I have been searching the internet but cannot find instructions on how to do then following.
I have data in a database which I want to select via a mouse. I have been able to display an output from the database in a Textbox, but cannot select it.
What I want to be able to do is select the line in the output and then use the information in that line.
Any ideas greatly appreciated.
You can use Out-GridView -PassThru on Windows to achieve this:
$selected = $datatable |Out-GridView -PassThru
Select the relevant line(s) by clicking (ctrl-click for more than one), and click Ok in the lower right corner.
$selected will then contain the relevant row(s)
Here are some functions I use myself. I've tried to adapt them to how you will use it.
Add-Type -AssemblyName System.Windows.Forms
$wshell = New-Object -ComObject wscript.shell;
function Mouse-signature-import(){
$global:signature=#'
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'#
$global:SendMouseClick = Add-Type -memberDefinition $global:signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru
}
function Mouse-Drag($from1,$from2,$to1,$to2){
Mouse-signature-import
[System.Windows.Forms.Cursor]::Position = "$from1,$from2"
$global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
[System.Windows.Forms.Cursor]::Position = "$to1,$to2"
start-sleep -m 1500 # If we do not sleep, then the drag does not work right.
$global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";
}
function SendInput($a){
[System.Windows.Forms.SendKeys]::SendWait($a)
}
start-sleep -s 1
Mouse-Drag 90 166 126 358
start-sleep -s 1
sendInput "^(c)"
$a = Get-Clipboard
$a
And to figure out the coordinates for where I want to move the mouse cursor to, I use this: https://learn-powershell.net/2015/11/30/create-a-mouse-cursor-tracker-using-powershell-and-wpf/
Basically what I'm doing above is moving the mouse to a cursor position, then I drag the mouse to position 2. Send a CTRL+C to copy what we have highlighted, then use get-clipboard to push the selected text into a variable ($a).
This method is not perfect for what you're trying to do, but it is how you want to do it so this is why I supplied my code. I would recommend trying to get the data through some other means as there is a lot that could go wrong here.
What I am doing is returning a table from a function (RetriveData) that retrieves it from a database.
$listTable = RetriveData | Format-Table | Out-String
Write-host “$listTable”
$selected = $listTable | Out-GridView –PassThru
Write-host “$selected”
The write hosts are showing the table contents as I was expecting. The dialogue opened by Out-GridView shows the table highlighted in light blue, but seems to only be selectable as a complete table.
Am I using the | Format-Table | Out-String correctly here?
The code being used in the RetriveData function to return from the data base is.
$table = Invoke-Sqlcmd –ServerInstance $databaseServer $databaseName –Query $sql
Return $table
Related
I am unable to find clear information anywhere on how to use the ShowUI functions. I've created a function that searches for movie information in an effort to easily update my movie list. The function works fine and I can add the content to a New-Window but I would love to be able to add a button that closes it or perhaps close it after a certain period. For the latter, I run into the window taking priority until it is closed, which makes no sense for what I am trying to do. My code is below.
function movie($sss,$ii){
cls
$a = ((wget "https://www.allmovie.com/search/all/$sss" ).allelements|where tagname -match "LI"|where class -match 'movie')|select *
$a = ($a.innertext -join(";") -isplit('movie') -split(';'))
if($ii -lt ''){
$a = $a[4] -replace('\s\s')
}else{
$a -replace("(.?img|DB|#.*|_images*|.com).*|\s\s|(""\W)", "")|out-host
BREAK
}
$moviesearch = new-window $B -TaskbarItemInfo "Movie Search" -Background black -Foreground red -width 500 -Height 300 -top 100 -left 100 -FontSize 16 -show|out-null
}
I wish to create a script which accepts input from the command line and based on the first value, it then determines the next parameters on offer.
Such as to determine if you are to do a single Run or a Batch run for a Password change operation:
./script.ps1 -singleMODE -UserName -Password
./script.ps1 -batchMODE -filename
What i am confused about whilst learning Powershell is what this is? I have looked at Parameters and can read them into variables from command line...but what i want as above has some logic and i am a bit lost. Can someone give me a nudge as to what this is called....and then i can continue my googling! :)
I am thinking somehow i combine Params and Functions so it flicks to different blocks...but i am guessing
any help appreciated! :)
cheers
What you need are Parameter Sets
This is a demo with a function but it works just as well with a script (just put the param block at the top.)
function Demo {
param(
[Parameter(ParameterSetName='Funk')][switch]$Funk,
[Parameter(ParameterSetName='Rock')][switch]$Rock,
[Parameter(ParameterSetName='Funk')][string]$WriteFunk,
[Parameter(ParameterSetName='Rock')][string]$WriteRock
)
if($Funk){
foreach ($C in $WriteFunk.ToCharArray()){
$N = 0..15 | Get-Random
Write-Host $C -ForegroundColor $N -BackgroundColor $(15-$N) -NoNewline
}
Write-Host ''
}
if($Rock){
Write-Host $WriteRock -ForegroundColor Gray -BackgroundColor DarkGray
}
}
Demo -Funk -WriteFunk "Melt your brain"
Demo -Rock -WriteRock "Riders on the storm"
I wrote a Powershell script that asks questions, takes the user's input, plugs those variables in a label created in ZPL, then print it out via Out-Printer. Everything seems to work fine except the label that prints has incorrect spacing or missing data.
Originally I had the script create a .txt file that held the label in ZPL format. Checking the label all the data was correct. When I would print the .txt file from Notepad using the same printer (Driver was set to Generic/ Plain text). The label would be perfect.
I also tried switching the printing method to the WMI variant. It would do the same formatting issues and missing data, but now in different spots.
It almost seems Powershell is formatting the data before it prints.
Here is the current code I have with some data censored for privacy concerns.
$i = 0
$global:counter = $i + 1
$AllPrinters = gwmi win32_printer -computername $env:computername
$DefaultPrinterString = $AllPrinters | where {$_.Default -eq $true}
$DefaultPrinter = [regex]::match($DefaultPrinterString, '\"([^\"]+)\"').Groups[1].Value
Write-Host "========== Print Company Labels =========="
Write-Host "Question will be on the left, type in answer and hit ENTER"
$location = Read-Host "Which location? (LOC1 or LOC2)"
$pro = Read-Host "What is the Pro#?"
$quote = Read-Host "What is the quote number?"
$pallet = Read-Host "How many pallets are there?"
$printer = Read-Host "What printer do you want?"
While ($global:counter -le $pallet)
{
$printcode = "^XA^MCY^XZ^XA^SZ2^MMT^MTT~JSN^LT0^MD0^MNY^PR5^PON^PMN^CI0^LRN
^FT300,1300^A0B,350,160^FDPRO: $pro^FS
^FT480,1300^A0B,175,150^FD$location^FS
^FT480,1300^A0B,175,150^FD$location^FS
^FT480,900^A0B,175,100^FDQuote: $quote^FS
^FT800,1300^A0B,350,225^FDPallet $global:counter of $pallet^FS
^PQ01~*QUANT,04~,0,~*COPIES,04~,N^MCY^XZ"
(New-Object -ComObject WScript.Network).SetDefaultPrinter($printer)
$printcode | Out-Printer
Start-Sleep 1
(New-Object -ComObject WScript.Network).SetDefaultPrinter($DefaultPrinter)
$global:counter++
}
Any help would be greatly appreciated.
Thanks in advance
I'd like to get my prompt in powershell to be at the bottom instead of "from top to bottom".
There is a workaround for cmd (https://superuser.com/questions/644326/start-conemu-with-prompt-at-the-bottom) but I can't find a way to make it work in powershell.
Does anyone have an idea?
Thanks a lot!
Thought, more "clean" version of prompt function. No need of New-Object ... Just add/modify your prompt in the $profile.
function prompt {
# put cursor at the bottom of the buffer
$rawUI = (Get-Host).UI.RawUI
$cp = $rawUI.CursorPosition
$cp.Y = $rawUI.BufferSize.Height - 1
$rawUI.CursorPosition = $cp
# and the prompt itself
Write-Host -NoNewline -ForegroundColor Cyan "PS "
Write-Host -NoNewline -ForegroundColor Yellow $(get-location).ProviderPath
return ">"
}
I'm not sure this is what you want, but this works fairly well for me. Save this as a .ps1 file somewhere that makes sense or convert it into a cmdlet if you like. Then stick it in your profile so it runs when you open a powershell session:
cls
$Ui = (Get-Host).UI.RawUI
$Height = $UI.WindowSize.Height
$Coordinates = New-Object System.Management.Automation.Host.Coordinates 0,($Height - 1)
$Ui.CursorPosition = $Coordinates
Create an alias for it.
New-Alias -Name cl -Value \\Path_to_the_script_or_the_cmdlet
Use the alias to clear your screen rather than clear or cls.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm looking for different examples of custom Powershell prompt function implementations. If you have a custom implementation of your own please post the script. Links to existing resources are good as well.
Bonus points for posting a screenshot of what your prompt actually looks like (a preview).
This is modified version of jaykul's prompt. The benefit is that
-there is a current history id, so you can invoke previous items from history very easily (you know the id)
-it's a little reminder - I add my tasks to the prompt so I don't forget them (see the sshot)
function prompt {
$err = !$?
$origOfs = $ofs;
$ofs = "|"
$toPrompt = "$($global:__PromptVars)"
$ofs = $origOfs;
if ($toPrompt.Length -gt 0) {
Write-Host "$($toPrompt) >" -ForegroundColor Green -NoNewline }
$host.UI.RawUI.WindowTitle = "PS1 > " + $(get-location)
# store the current color, and change the color of the prompt text
$script:fg = $Host.UI.RawUI.ForegroundColor
# If there's an error, set the prompt foreground to "Red"
if($err) { $Host.UI.RawUI.ForegroundColor = 'Red' }
else { $Host.UI.RawUI.ForegroundColor = 'Yellow' }
# Make sure that Windows and .Net know where we are at all times
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# Put the ID of the command in, so we can get/invoke-history easier
# eg: "r 4" will re-run the command that has [4]: in the prompt
$nextCommandId = (Get-History -count 1).Id + 1
# Output prompt string
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine
# Set back the color
$Host.UI.RawUI.ForegroundColor = $script:fg
if ($toPrompt.Length -gt 0) {
$host.UI.RawUI.WindowTitle = "$($toPrompt) -- " + $host.UI.RawUI.WindowTitle
}
" "
}
function AddTo-Prompt($str) {
if (!$global:__PromptVars) { $global:__PromptVars = #() }
$global:__PromptVars += $str
}
function RemoveFrom-Prompt($str) {
if ($global:__PromptVars) {
$global:__PromptVars = #($global:__PromptVars | ? { $_ -notlike $str })
}
}
Here's mine:
function prompt {
# our theme
$cdelim = [ConsoleColor]::DarkCyan
$chost = [ConsoleColor]::Green
$cloc = [ConsoleColor]::Cyan
write-host "$([char]0x0A7) " -n -f $cloc
write-host ([net.dns]::GetHostName()) -n -f $chost
write-host ' {' -n -f $cdelim
write-host (shorten-path (pwd).Path) -n -f $cloc
write-host '}' -n -f $cdelim
return ' '
}
It uses this helper function:
function shorten-path([string] $path) {
$loc = $path.Replace($HOME, '~')
# remove prefix for UNC paths
$loc = $loc -replace '^[^:]+::', ''
# make path shorter like tabs in Vim,
# handle paths starting with \\ and . correctly
return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
}
Here is my prompt function
function prompt() {
if ( Test-Wow64 ) {
write-host -NoNewLine "Wow64 "
}
if ( Test-Admin ) {
write-host -NoNewLine -f red "Admin "
}
write-host -NoNewLine -ForegroundColor Green $(get-location)
foreach ( $entry in (get-location -stack)) {
write-host -NoNewLine -ForegroundColor Red '+';
}
write-host -NoNewLine -ForegroundColor Green '>'
' '
}
i often use posh as a calc, so i set $ans variable.
https://connect.microsoft.com/PowerShell/feedback/ViewFeedback.aspx?FeedbackID=386493
PS > 100
100
PS > $ans * 9
900
PS > $ans*$ans
810000
Here's mine. Just has the history ID at each command so I can easily identify the ID of the command. I also use the windowtitle to give me the current working directory rather than have it displayed in the prompt itself.
106 > cat function:\prompt
$history = #(get-history)
if($history.Count -gt 0)
{
$lastItem = $history[$history.Count - 1]
$lastId = $lastItem.Id
}
$nextCommand = $lastId + 1
$Host.ui.rawui.windowtitle = "PS " + $(get-location)
$myPrompt = "$nextCommand > "
if ($NestedPromptLevel -gt 0) {$arrows = ">"*$NestedPromptLevel; $myPrompt = "PS-nested $arrows"}
Write-Host ($myPrompt) -nonewline
return " "
One thing that many people forget is to deal with in custom prompts is the nested prompt. Note that I check $nestedPromptLevel and add an arrow for each nested level.
Andy
I tend to re-type
function prompt { "PS> " }
every time I am preparing examples I can copy/paste to someone, especially when I'm in cumbersome long paths which would only distract.
And I still plan to write a decent prompt function which shows me the drive and a useful approximation on the location by either using the current directory (without the path that led to there) or (if it's numeric) the next higher level too. But that's probably pretty specific to my own filesystem here. And I never was bothered enough by the default prompt to actually do it :-)