Search Results for 'sendkeys'

Welcome Forums Search Search Results for 'sendkeys'

Viewing 15 results - 1 through 15 (of 41 total)
  • Author
    Search Results
  • #173263

    ofergenat
    Participant
    Topics: 6
    Replies: 15

    Hi all,

    I am rewriting my script that used the com object InternetExplorer.Application to login, navigate, find elements (links) in page source. So now I am using selenium module to work with FireFox driver to do the same.

    I have reached a point where I am able to do the login and navigate, I just can't find a way to convert the page source (HTML string) into an object that I can filter by tag name and class and select hrefs.

    I found an example at a website that I could create a com object of HTML and write the page source so I would get a DOM object, however it still doesn't work when I try to look for 'a' tags there nothing found, like this data was not added to the object.

    I need your help converting a page source (HTML string) into an object that I can work with.

    Here is the sample code which uses 'selenium' module:

    
    $PSCred = Get-Credential
    $FFDriver = Start-SeFirefox
    $FFDriver.Navigate().GoToURL('https://login.somewebsite.com/')
    $FFDriver.FindElementByName('email').sendkeys($PSCred.Username)
    $FFDriver.FindElementByName('password').sendkeys($PSCred.GetNetworkCredential().password)
    $FFDriver.FindElementByName('password').submit()
    Start-Sleep -Seconds 3
    $FFDriver.Navigate().GoToURL('https://www.somewebsite.com/aaa/bbb/')
    $FFDriver.Title
    $Source = $FFDriver.PageSource
    # Create HTML file Object
    $HTML = New-Object -ComObject "HTMLFile"
    # Write HTML content according to DOM Level2
    $HTML.IHTMLDocument2_write($Source)
    $LinkElements = $HTML.getElementsByTagName('a') | where{$_.href -like "$xxx*"} | where{$_.className -eq 'xxx'}
    
    # cleanup
    Remove-Variable -Name PSCred
    $FFDriver.Close()
    $FFDriver.Quit()
    $FFDriver.Dispose()
    
    
    #168157

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    What are you asking here?

    8 separate monitors and tiled does not make since. If you have 8 windows open and 8 monitors to use, are you saying, you want each window on one of each monitor?

    Tiled, means you want them on one monitor, then you'd call windows proper to tile / cascade windows feature not use sendkeys stuff.

    For example:

    How Can I Tile the Windows on the Desktop?

     

     

    #167995

    Tony Antony
    Participant
    Topics: 74
    Replies: 167

    I have a script to open 8 windows using VNC viewer (for seeing screens from computer).  This works fine.  After the script runs and I have the 8 windows open, I have to manually snap them to the monitors so they look tiled.  Is there a way to resize a window and move it using powershell?

    This is what I have so far.  This just opens the 8 screens using TightVNC Viewer.

    $laptops = '172.16.2.88', '172.16.1.145', '172.16.2.75', '172.16.2.87',
    '172.16.2.84', '172.16.2.83', '172.16.2.79' , '172.16.2.77'
    
    $wshell = New-Object -ComObject wscript.shell;
    
    foreach ($l in $laptops) {
    Start-Process -FilePath 'C:\Program Files\TightVNC\tvnviewer.exe'
    sleep 2
    $vlc = Get-Process -Name tvnviewer
    sleep 1
    $wshell.SendKeys($l)
    Write-Host "Using VNC for" $l -ForegroundColor Green
    sleep 1
    $wshell.SendKeys('~')
    sleep 1
    $wshell.SendKeys('12345')
    sleep 1
    $wshell.SendKeys('~')
    sleep 1
    }
    #146229

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    As for …

    How to close currently open particular notepad

    … what does this mean to you?

    All opened or the current one that has focus / in the foreground (which is almost impossible to do BTW – even if you check by StartTime).

    As noted by 'js', that is a way to get the isolated instance by that name. Yet, you can do a bit more.
    Use what 'js' gave, but you need to know what else you need to pull and there really is not much else useful for what you are after. The most relevant is the below.

    Get-Process -Name Notepad | 
    Select Name, MainWindowTitle, Responding, StartTime
    
    Name    MainWindowTitle        Responding StartTime
    ----    ---------------        ---------- ---------
    notepad Untitled - Notepad           True 3/22/2019 11:02:38 AM
    notepad Untitled - Notepad           True 3/22/2019 11:16:57 AM
    notepad TestFile.txt - Notepad       True 3/22/2019 11:35:21 AM
    

    So, you check for all titles that are either 'Untitled – Notepad' or 'named'.
    Of course, named means the file has been saved at least once.

    However, for those, 'Untitled – Notepad ones, you may want to check for content before closing it, as the user may not yet have had time to save it. Thus you need to save it for them with some name that you report back to them so that can find it again.

    So, anything with a name, save. Anything else should be checked and saved with say a timestampe and the close. The automation of this as pointed out by Olaf, use AutoIT, or you can use SendKeys. They later is a bit more quirky (timing, etc.), especially if any of these are minimize, and SendKeys chokes until you restore or maximize those windows.

    So here is how I've handled such use cases, but again, it can get really quirky. No guarantees at all from system to system you would target with it.

    ### Automating notepad checks
    
    Clear-Host
    
    Function Set-WindowStyle 
    {
        param
        (
            [Parameter()]
            [ValidateSet('FORCEMINIMIZE', 'HIDE', 'MAXIMIZE', 'MINIMIZE', 'RESTORE', 
                         'SHOW', 'SHOWDEFAULT', 'SHOWMAXIMIZED', 'SHOWMINIMIZED', 
                         'SHOWMINNOACTIVE', 'SHOWNA', 'SHOWNOACTIVATE', 'SHOWNORMAL')]
            $Style = 'SHOW',
            [Parameter()]
            $MainWindowHandle = (Get-Process -Id $pid).MainWindowHandle
        )
    
        $WindowStates = @{
            FORCEMINIMIZE   = 11; HIDE            = 0
            MAXIMIZE        = 3;  MINIMIZE        = 6
            RESTORE         = 9;  SHOW            = 5
            SHOWDEFAULT     = 10; SHOWMAXIMIZED   = 3
            SHOWMINIMIZED   = 2;  SHOWMINNOACTIVE = 7
            SHOWNA          = 8;  SHOWNOACTIVATE  = 4
            SHOWNORMAL      = 1
        }
        Write-Verbose ("Set Window Style {1} on handle {0}" -f $MainWindowHandle, $($WindowStates[$style]))
    
        $Win32ShowWindowAsync = Add-Type –memberDefinition @” 
        [DllImport("user32.dll")] 
        public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    “@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru
    
        $Win32ShowWindowAsync::ShowWindowAsync($MainWindowHandle, $WindowStates[$Style]) | Out-Null
    }
    
    
    
    [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms") | Out-Null
    
    
    Get-Process -Name Notepad | 
    ForEach {
        If($PSItem.MainWindowTitle -NotMatch 'Untitled')
        {
            "The process $($PSItem.MainWindowTitle) with start time of $($PSItem.StartTime) has been saved at least once."
            'Saving the file in its current state to the current working directory.'
            Set-WindowStyle RESTORE $PSItem.MainWindowHandle
            [Microsoft.VisualBasic.Interaction]::AppActivate($PSItem.ID)
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%(fs)")
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%{F4}")
            "`n"
        }
        Else
        {
            Write-Warning -Message "
            The process $($PSItem.MainWindowTitle) with start time of $($PSItem.StartTime) is not saved.
            Saving the file using the title and start time to the current working directory."
            Set-WindowStyle RESTORE $PSItem.MainWindowHandle
            [Microsoft.VisualBasic.Interaction]::AppActivate($PSItem.ID)
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%(fa)")
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("$((($PSItem.MainWindowTitle) -split '-')[0])$(($PSItem.StartTime).ToString('ddMMyyyy@hhmmss'))")
            Start-Sleep -Seconds 3
            [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
            [System.Windows.Forms.SendKeys]::SendWait("%{F4}")
            "`n"
        }
    }
    

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    You are going to get prompted with those tools, by design.
    You have to do additional UI automation to deal with that dialog, i.e. SendKeys (which is just kind of hack'y, but does have it's place or use other GUI tools, Selenium, UIAutomation, WASP, AutoIT, etc...) while trapping the handle to the dialog prompt.
    Again, as for the AKI add, you cannot do that with any of those tools.


    As I and kvprasoon is saying, you need to use opensssl to do that.
    I have the links to all that in my first response.


    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    Things are only complicated when you first come to them.

    As one that has been in IT as a Dev, Eng, architect, etc., I have had to deal with everything from mainframe, to mini, to PC, to mobile and cloud. AS well as assembler, bash, batch, wmic, vbscript, python, Perl, etc. Many things I see may or may not make since, but they are what they are.

    My philosophy, is never dive in to anything you have not spent time researching / ramping up on, because all you will do is lead yourself to confusion and frustration. There is a great deal of stuff to PowerShell, but you have to be willing to commit to it.

    Automation, and user interactive / UI coding are seriously different things, though you can use them together.

    Yet, only you can decide what works for you. We all here love PS, which is why we are here. Yet, PS is not always the right answer to everything.

    Use, whatever you like, and does the job, but don't ever expect one language (full or scripting) to be / act like the other. If that were the case, we'd all still be programming in Assembler, JCL, Fortran, Cobol, etc.

    My Computer Eg professor always said, if you are not use to or can't handle change, don't go into IT. ;-}

    This whole sendkeys thing is not a PS thing at all, but it can use it.
    Sendkeys is from the VBScript days, and the approach in PS for sendkeys is the same with using WSHScript COM, or .Net as I've shown.

    https://social.technet.microsoft.com/wiki/contents/articles/5169.vbscript-sendkeys-method.aspx

    As for this...

    By judging your instructions, it seems like I need to target a scriptfile, this seems rather weak in terms of PowerShell-capabilities.

    You cannot pass user interactive commands as command line switches in virtually any language, without writing a script. .bat, .cmd, .vbs, .ps1, etc...

    Which is all you did, when you said this...

    With CMD, all I need to do is create a batch file and execute a rather unlimited amount of commands.

    There has been no improvements to cmd.exe stuff since DOSv6+ days, and never will be. Yet, if that is your thing, them that's cool.

    You can do the same in PS, if you are willing to learn how. Virtually anything you can do on .bat/.cmd, you can do with PS, and there are things you can do with PS that you'd never be able to do with .bat /.cmd. Yet, again, use what works for your use case.

    There are tons for no cost eBooks and video training in the free resource section of this site or stuff discussed / shown here: https://www.reddit.com/r/PowerShell/comments/afqmmw/i_want_to_help_my_husband_advance_his_powershell/ee3k6p6/?context=3), that can be used to get your head around this.

    If you are really planning an IT career, especially with the MS stack, learning and master PowerShell is an absolute must. All of MS products (Exchange, SharePoint, Skype, Hyper-V, etc.) use / rely on it and when it comes to MS cloud, PowerShell or the GUI is the only options.

    BTW, tons of other vendors have invested as great deal into supporting PS for there stack as well. I.e., VMWare, AWS. etc...

    So, just say'in…

    As for this...

    How about if I skip the SendKeys requirement and just want the net user-commands to be followed up by each other and input in the elevated PowerShell instance?

    … I was really unsure why you were doing that {enter} thing anyway. Yet, you had it, so I addressed out., Yet no, there was no reason, I can see by what you were doing, that you needed those, and thus no sendkeys, but you'd still need a script, just as you needed a .CMD to do this.

    BTW, the Start-Process cmdlet, allows for multiple arguments to be pass in that argument list switch, see the documentation for directions.

    # get function / cmdlet details
    (Get-Command -Name Start-Process).Parameters
    Get-help -Name Start-Process -Examples
    Get-help -Name Start-Process -Full
    Get-help -Name Start-Process -Online
    

    It's as simple as just doing something like this...

    Start-Process powershell -Verb runas -ArgumentList 'cd c:\','dir'
    

    Yet, you are not just running commands, you are running executables in a command string. Hence the need for a .CMD or .PS1 to do it.
    Start-Process, will run only one shell at a time and since you are passing executables and thinking they are commands, then you do this script block approach..

    Start-Process powershell.exe -ArgumentList "-NoExit","-Command  `"&{net User; nslookup}`"" -Wait
    
    # Your use case.
    Start-Process powershell.exe -ArgumentList "-NoExit","-Command  `"&{net user administrator /active:yes; net user administrator *; shutdown /l}`"" -Wait
    

    PowerShell offer multiple ways to do things, you just have to know where and why to use X or approach.

    https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx

    If that executable and switches, you pass those in the argument list.

    Lastly, you could have just written this as a .ps1 file, and set it to auto elevate (there are many articles on how to do this), then just run PowerShell as normal calling the script directly, just as you would call that .bat/.cmd file.


    Inactive
    Topics: 1
    Replies: 2
    Points: 0
    Rank: Member

    Wow, that's a ridiculous strange and long command to perform such a simple instruction.

    Why would someone invent "Power"Shell when it basically makes no common sense?

    I'm sorry, coding and scripting is totally new to me, but those instructions you posted are not logical to what I'm trying to achieve.

    I appreciate your help and supplying me with instructions on how to proceed, but I actually ended up just creating three different CMD-shortcuts, targeting my commands.

    I found this to be alot easier and with less hassle than using PowerShell.

    To answer your questions, I need to elevate PowerShell to perform the net user-commands, otherwise I would not open another instance of PowerShell.

    By judging your instructions, it seems like I need to target a scriptfile, this seems rather weak in terms of PowerShell-capabilities.

    With CMD, all I need to do is create a batch file and execute a rather unlimited amount of commands.

    I'm in no place to tell whats right or wrong, but commands needs to stay logical for one to remember and keep using them, at least for me.

     

    How about if I skip the SendKeys requirement and just want the net user-commands to be followed up by each other and input in the elevated PowerShell instance?

    Would the input prompts from net user "administrator" * break the script process?

    Thanks!

     

    Edit: Typos


    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    These are interactive user keyboard commands. You cannot do this they way you are asking.
    You must create a .ps1 and then use …
    To do that keyboard stuff, you'll need to use sendkeys.

    If you are already in PowerShell, which you have to be to do this...

    start-process powershell -verb runas

    Why are you starting PowerShell to call PowerShell, that you can already do in the PowerShell session you are already in.

    If you are saying you are not running as admin when you start a PowerShell instance, that makes sense.

    Still, you cannot pass interactive user commands...

    {enter}
    
    {enter}
    

    ... the way you are trying. You can only do that by writing sendkeys code. You need a script to do that.

    Start-Process -FilePath PowerShell -ArgumentList 'PathToScriptFile' -Verb RunAs
    
    # In your script file
    net user administrator /active:yes
    net user "administrator" *
    
    # Send key strokes
    [system.reflection.assembly]::loadwithpartialname("System.Windows.Forms")
    [System.Windows.Forms.SendKeys]::Sendwait('{enter}{enter}')
    
    shutdown /l
    
    #113506

    Joseph
    Participant
    Topics: 1
    Replies: 1

    This is my first post and I am a complete beginner to this wonderful language.

    I have 2 folders both containing MP4 files named like partn.mp4  where n is an integer.

    I have a playlist file that contains the absolute path of each file like C:\Series\Show\part1.mp4, C:\Series\Adv\part2.mp4 and so on...

    Series contains even numbered files (part1.mp4, part3.mp4,...), Adv contains odd ones.

    Media player classic will play these files if given the playlist as an argument.

    What I need is a way to send a Ctrl-4 to odd numbered ones, I only limited myself to 3 parts for simplicity, so I need to send the keystroke to part2.mp4

    This code sends the keystroke to all files.

    Other codes that I've tried create race conditions and only the last file will play, any help.

    I am not attached to creating a playlist, any solution is fine.

    mpc-hc.exe playlist.m3u /play
    [void][System.reflection.assembly]::loadwithpartialname('system.Windows.forms')
    Foreach ($line in get-content playlist.m3u) {
    If ($line.substring($line.length-5,1) -match 2) {
     [System.Windows.forms.Sendkeys]::sendwait("^4")
      }
    }
    #110428

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    Either what Rob says or using the sometimes reliable SendKeys to mimic these actions. There is an old module to assist with such PS GUI automation, but it is what it is, old and not maintained, but it still works.

    WASP is a PowerShell snapin for Windows Automation tasks like selecting windows and controls and sending mouse and keyboard events. We have automation cmdlets like Select-Window, Select-Control, Send-Keys, Send-Click, Get-WindowPosition, Set-WindowPosition, Set-WindowActive, Remove-Window ... etc.

    Our goal is to enable you to accomplish most Windows GUI Automation scripting from inside PowerShell, without resorting to specialized (and expensive) scripting tools.

    Just to be clear, don't expect any "click to record" functionality ... but do expect to be able to automatically tile windows, send mouse clicks and keystrokes, and in general, automate those tasks that you would normally not be able to do from a console.
    https://archive.codeplex.com/?p=wasp
    'eddytechdotnet.wordpress.com/2016/02/24/using-wasp-and-powershell-for-powerful-windows-gui-automation'


    situscript
    Participant
    Topics: 5
    Replies: 7

    I am having a very specific issue with scheduling a PowerShell script to run with Task Scheduler in Windows 2012 server. The script works as expected from the PowerShell ISE console. The script is checking the size of C:\ and a particular log folder size and if the log folder size is more than 20 GB then it clears the logs of the folder with the help of application.

    The stop application stops 3 of the particular services and while starting the start application undergoes a interactive session with CMD and if we press y and enter , it will clear the logs and start those 3 services.

    Then it will send the mail the output.

    The issue is, if i start the script from powershell console it complete successfully as expected but if i do the same from task scheduler then only the start application is not executing and the task is getting completed with stop application and sending the mail. The middle part is not happening.

    $cdrive = $NULL
    $percentage = $NULL
    $freespace = $NULL
    $size = $NULL

    $cdrive = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size = [math]::Round($cdrive.Size/1GB,0)
    $freespace = [math]::Round($cdrive.FreeSpace/1GB,0)
    $percentage = [math]::Round($cdrive.FreeSpace/$cdrive.Size * 100,0)

    if($percentage -gt 50)
    {

    exit

    }
    else

    {
    $logsize = $NULL

    $logsize = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB,0)

    if($logsize -lt 10)

    {
    $cdrive1 = $NULL
    $percentage1 = $NULL
    $size1 = $NULL
    $freespace1 = $NULL
    $ID1 = $NULL
    Add-Type -AssemblyName 'System.Windows.Forms'
    $ID1 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Stop Services' -PassThru).Id
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID1)
    Sleep 90
    [System.Windows.Forms.SendKeys]::SendWait("~")

    sleep 20
    this below start function only not executing.
    #*****************************************************************************
    $ID2 = $NULL
    #Add-Type -AssemblyName 'System.Windows.Forms'
    $ID2 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Start Services' -PassThru).Id
    sleep 10
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID2)
    sleep 10
    [System.Windows.Forms.SendKeys]::SendWait("y~")
    sleep 30
    [System.Windows.Forms.SendKeys]::SendWait("~")
    #*********************************************************************************

    $cdrive1 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size1 = [math]::Round($cdrive1.Size/1GB,0)
    $freespace1 = [math]::Round($cdrive1.FreeSpace/1GB,0)

    $percentage1 = [math]::Round($cdrive1.FreeSpace/$cdrive1.Size * 100,0)

    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "abc@.com"
    $EmailTo ="abc@.com"
    $MyReport = @"

    Script has cleared the HP performance unused logs from the path C:\HPE\HPSS\pa\tomcat\logs and below is the output of C: drive.

    Before log deletion
    **************
    C: Total size in GB = $size
    C: Freespace in GB = $freespace
    C: Freespace in % = $percentage

    After Log Deletion
    **************
    C: Total size in GB = $size1
    C: Freespace in GB = $freespace1
    C: Freespace in % = $percentage1
    "@

    Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV

    }
    else

    {
    $cdrive2 = $NULL
    $percentage2 = $NULL
    $cdrive2 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"

    $percentage2 = [math]::Round($cdrive2.FreeSpace/$cdrive2.Size * 100,0)
    $logsize1 = $NULL

    $logsize1 = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB,0)
    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "xyz.abc.net"
    $EmailTo ="xyz.abc.net"
    $MyReport = @"

    C: drive freespace is < 50% but the HP Performance log folder "C:\HPE\HPSS\pa\tomcat\logs" is not occupied more than 10GB. Current size of the log folder is $logsize1 MB. "@ Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV } } Task Scheduler information tried: Progrm/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe Arguments : -ExecutionPolicy RemoteSigned/ByPass/Unrestricted -File D:\ClearDBlog.ps1 this is the exception i am getting while executing manually but script works as usual. exception calling : process '1990' is not found.

    #104285

    Participant
    Topics: 5
    Replies: 7
    Points: 0
    Rank: Member

    I am having a very specific issue with scheduling a PowerShell script to run with Task Scheduler in Windows 2012 server. The script works as expected from the PowerShell ISE console. The script is checking the size of C:\ and a particular log folder size and if the log folder size is more than 20 GB then it clears the logs of the folder with the help of application.

    The stop application stops 3 of the particular services and while starting the start application undergoes a interactive session with CMD and if we press y and enter , it will clear the logs and start those 3 services.

    Then it will send the mail the output.

    The issue is, if i start the script from powershell console it complete successfully as expected but if i do the same from task scheduler then only the start application is not executing and the task is getting completed with stop application and sending the mail. The middle part is not happening.

    $cdrive = $NULL
    $percentage = $NULL
    $freespace = $NULL
    $size = $NULL

    $cdrive = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size = [math]::Round($cdrive.Size/1GB,0)
    $freespace = [math]::Round($cdrive.FreeSpace/1GB,0)
    $percentage = [math]::Round($cdrive.FreeSpace/$cdrive.Size * 100,0)

    if($percentage -gt 50)
    {

    exit

    }
    else

    {
    $logsize = $NULL

    $logsize = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB,0)

    if($logsize -lt 10)

    {
    $cdrive1 = $NULL
    $percentage1 = $NULL
    $size1 = $NULL
    $freespace1 = $NULL
    $ID1 = $NULL
    Add-Type -AssemblyName 'System.Windows.Forms'
    $ID1 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Stop Services' -PassThru).Id
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID1)
    Sleep 90
    [System.Windows.Forms.SendKeys]::SendWait("~")

    sleep 20
    this below start function only not executing.
    #*****************************************************************************
    $ID2 = $NULL
    #Add-Type -AssemblyName 'System.Windows.Forms'
    $ID2 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Start Services' -PassThru).Id
    sleep 10
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID2)
    sleep 10
    [System.Windows.Forms.SendKeys]::SendWait("y~")
    sleep 30
    [System.Windows.Forms.SendKeys]::SendWait("~")
    #*********************************************************************************

    $cdrive1 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size1 = [math]::Round($cdrive1.Size/1GB,0)
    $freespace1 = [math]::Round($cdrive1.FreeSpace/1GB,0)

    $percentage1 = [math]::Round($cdrive1.FreeSpace/$cdrive1.Size * 100,0)

    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "abc@.com"
    $EmailTo ="abc@.com"
    $MyReport = @"

    Script has cleared the HP performance unused logs from the path C:\HPE\HPSS\pa\tomcat\logs and below is the output of C: drive.

    Before log deletion
    **************
    C: Total size in GB = $size
    C: Freespace in GB = $freespace
    C: Freespace in % = $percentage

    After Log Deletion
    **************
    C: Total size in GB = $size1
    C: Freespace in GB = $freespace1
    C: Freespace in % = $percentage1
    "@

    Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV

    }
    else

    {
    $cdrive2 = $NULL
    $percentage2 = $NULL
    $cdrive2 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"

    $percentage2 = [math]::Round($cdrive2.FreeSpace/$cdrive2.Size * 100,0)
    $logsize1 = $NULL

    $logsize1 = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB,0)
    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "xyz.abc.net"
    $EmailTo ="xyz.abc.net"
    $MyReport = @"

    C: drive freespace is < 50% but the HP Performance log folder "C:\HPE\HPSS\pa\tomcat\logs" is not occupied more than 10GB. Current size of the log folder is $logsize1 MB. "@ Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV } }

    #104105

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    As for...

    If I run this in Powershell ISE it will pop up to the front of the screen like I would expect.

    It should, because these are two different apps that are being ran. The ISE is of course PowerShell_ise.exe, the console window in the ISE is not a real ConsoleHost. When you run code in the ISE, it actually spawn a PowerShell.exe instance to run it and that is separate from the powershell_ise.exe instance all the while returning the output back to the ISE console. Hence why it can come to the front.

    In VSCode, the code is run as a child process. Hence not coming front. You can see this in Get-Process in both tools.

    When you do this in the ISE, you will see a single powershell_ise.exe process.
    When you run the code in the ISE, and do Get-Process again, you will see a new powershell.exe process.

    When you run VSCode, you will see several powershell.exe processes. One for the start of VSCode (default ConsolHost) and the other for when you start the Editor which triggers the 'PowerShell Integrated Console – Visual Studio Code Host'.

    # VSCode

     
    Get-Process -Name '*powershell*'
    
    Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
    -------  ------    -----      -----     ------     --  -- -----------
        590      28    83808      93452       1.09     32  26 powershell
        728      43   140340     139116       3.86   6840  26 powershell
    

    If you open TaskManager, you'll see only one VSC task, but expand that and you'll see double digit child processes, depending on what you loaded up.

    The VSCode console dropdown will show the number of powershell.exe process are running in the parent process. So, at the start and a blank editor / pane, there will be two. The moment you run this code in the Editor, it will spawn a third powershell.exe instance. If you open TaskManger you will see the VSC process until you expand it and see all the child processes.

     Get-Process -Name '*powershell*'
    
    Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
    -------  ------    -----      -----     ------     --  -- -----------
        584      28    83696      93408       1.19     32  26 powershell
        626      31    85092      95592       1.14   6544  26 powershell
       1246      71   328936     349968      16.95   6840  26 powershell
    

    Also, if you look at the bottom right of the VSC console, you will see the work PowerShell with a spinning icon to the left of it. This means that the parent editor (which itself seems to be model) is running the new PowerShell instance and in a model dialog box thus behind the parent. However, if you go back to TaskManager, you'll see a separate 'Windows PowerShell' task running.

    So, in order for you to bring this to the front, you have to minimize the VSCode window. You can do this in your code. Yet, this just means you have to click the taskbar icon (or ALT+TAB) to bring the VSCode window back up to work on your code again. Otherwise you are going to have to write additional code to try and grab that process and make it active. That is a bit more of a challenge, especially for model dialog boxes. Been there, done that, not successful.

    So, when I do this sort of thing like you are, I just minimize VSC...

        Function Get-FileName($initialDirectory)
        {   
            [system.reflection.assembly]::loadwithpartialname("System.Windows.Forms")
            [System.Windows.Forms.SendKeys]::Sendwait("% {n}")
    
            [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
            Out-Null
    
            $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog 
            $OpenFileDialog.initialDirectory = $initialDirectory
            $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
            $OpenFileDialog.ShowDialog() | Out-Null
            $OpenFileDialog.filename
            $OpenFileDialog.ShowHelp = $true
        } #end function Get-FileName
    
        Get-FileName -initialDirectory D:\Temp
    

    … and work with my dialogs, and ALT+TAB to maximize VSC when done.

    Even using the above, sometimes it will minimize to show the dialog behind, other times it will bring the dialog to the front, depending on what other screens / dialogs I had up at the time. I have a 4 monitor setup with many items up at once.

    Otherwise, I write my code, save the file and shell-out, so as to not have to minimize VSC. Both at not the best experience, but it is what it is. Well, unless someone else tells me I am smoking something, that is causing my in ability to accomplish this. 8^}

    I also spent a good bit of time VSC editor settings and PowerShellEditorServices for a fix, no luck.

    #96584
    js

    Participant
    Topics: 24
    Replies: 688
    Points: 1,689
    Helping Hand
    Rank: Community Hero

    After putting the missing spaces in:

    Function Set-Speaker($Volume){$wshShell=new-object -com wscript.shell;1..50|%{$wshShell.SendKeys([char]174)};
    1..$Volume|%{$wshShell.SendKeys([char]175)}}
    

    This seems to be the way to do it (https://stackoverflow.com/questions/15979445/run-a-local-function-on-a-remote-computer), but it didn't work for me. I even tried installing the script remotely.

    invoke-command comp001 ${function:set-speaker} -ArgumentList 10
    
    #96384

    rubi12
    Participant
    Topics: 1
    Replies: 1

    Hi,

    I would like to run the following power shell script on a remote computer

    FunctionSet-Speaker($Volume){$wshShell=new-object-comwscript.shell;1..50|%{$wshShell.SendKeys([char]174)};1..$Volume|%{$wshShell.SendKeys([char]175)}}

    Set-Speaker – Volume 10

    I have tried to use the Invoke command without success, any suggestions on how to make it work on a remote computer?

Viewing 15 results - 1 through 15 (of 41 total)