Set a variable and silence output in PowerShell - powershell

I have this program on POWERSHELL:
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.addargument('--kiosk-printing')
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
This last line return in the terminal many informations ( ChromeDriver was started successfully. DevTools listening on etc ...).
My problem is that I want to hide all of this message.
I have already tried :
1) ($driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions))|Out-Null
2) $driver = (New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions))|Out-Null
3) $driver = [void] (New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions))
4) [void] ($driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions))
5) $driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions) -InformationVariable 'Ignore'
6) $driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions) >$null
Any other ideas ? Thanks

The following will stop the console appearing entirely:
$ChromeService = [OpenQA.Selenium.Chrome.ChromeDriverService]::CreateDefaultService()
$ChromeService.HideCommandPromptWindow = $true
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.addargument('--kiosk-printing')
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeService,$ChromeOptions)

Related

Test connection and output in GUI screen in Powershell

With the below code, my goal is to ping a hostname and have it return if successful or unsuccessful, and project that on the GUI screen itself. At the moment I am getting errors on the "-TargetName".
Add-Type -assembly System.Windows.Forms
# Create window form
$main_form = New-Object System.Windows.Forms.Form
$main_form.Text = 'Device Info'
$main_form.Width = 600
$main_form.Height = 400
$main_form.AutoSize = $true
# Start of code
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Hostname"
$Label.Location = New-Object System.Drawing.Point(10, 30)
$Label.AutoSize = $true
$main_form.Controls.Add($Label)
# Adding textbox
$TextBox = New-Object System.Windows.Forms.TextBox
$TextBox.Location = New-Object System.Drawing.Point(90, 30)
$TextBox.Width = 300
$main_form.Controls.Add($TextBox)
# Adding check button
$CheckButton = New-Object System.Windows.Forms.Button
$CheckButton.Location = New-Object System.Drawing.Size(400, 30)
$CheckButton.Size = New-Object System.Drawing.Size(120, 23)
$CheckButton.Text = "Check"
$main_form.Controls.Add($CheckButton)
# Perform event when check button is clicked
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
# Show Window
$main_form.ShowDialog()
You need to grab the value from $TextBox.Text when the button is clicked, and then use the correct parameter name (-ComputerName rather than -TargetName)!
Change this:
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
To:
$CheckButton.Add_Click(
{
$ComputerName = $TextBox.Text
Test-Connection -ComputerName $ComputerName -IPv4
}
)

Powershell Winforms doesn't execute button_click action locally

I'm making winforms with powershell for the first time.
I was working hard on it. but I ran into a problem. I tried to solve it by myself, but I don't know..
When I run the below code in powershell ise, $button_click works.
In other words, it worked fine in ise.
However, after saving to the desktop, $button_click does not work when running through cmd.
# start.bat
C:\Users\User\Desktop> powershell -ExecutionPolicy Unrestricted %CD%\code.ps1
I wrote the following code:
# code.ps1
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
# form specs
$Form = New-object System.Windows.Forms.Form
$Form.Text = "Check Network Status"
$Form.Size = New-object System.Drawing.Size(700,700)
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = "None"
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.BackColor = "Lavender"
# form icon
$Icon = New-object system.drawing.icon ("icon.ico")
$Form.Icon = $Icon
# form image
$Image = [system.drawing.image]::FromFile("img.jpg")
$PictureBox = New-Object System.Windows.Forms.PictureBox
$PictureBox.Image = $Image
$PictureBox.Size = New-object System.Drawing.Size(700,550)
$PictureBox.SizeMode = "StretchImage"
$Form.Controls.Add($PictureBox)
# ok button
$ButtonSizeWidth = 200
$ButtonSizeHeight = 50
$Button = New-object System.Windows.Forms.Button
$Font = New-Object System.Drawing.Font("Arial",20)
$Button.Location = New-object System.Drawing.Size((350 - $ButtonSizeWidth / 2),(650 - $ButtonSizeHeight))
$Button.Size = New-object System.Drawing.Size($ButtonSizeWidth,$ButtonSizeHeight)
$Button.Text = "Okay"
$Button.BackColor = "PowderBlue"
$Button.FlatAppearance.BorderSize = 0
$Button.FlatStyle = "Flat"
$Button.Font = $Font
$Button.Add_Click($button_click)
$Form.Controls.Add($Button)
# action here
$button_click =
{
# netsh int set int admin=disable
$Form.Close()
}
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter"){& $button_click}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$Form.Close()}})
# modal
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
Obviously it works fine in powershell ise, but I want to know why it doesn't work when I save and run it.
Is there something I'm missing out on?

open a mailbox to which I have full access

I can open my mailbox in exchange online with EWS and Powershell
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $mail, $password
$service.URL = New-Object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView($numOfEmailsToRead, $index)
$folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10)
$folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
$folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
$folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
How do I change the code to open a mailbox to which I have full access?
In your example you need to use the Mailbox overload for Folder id so change
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
To
$MailboxToAccess = "blah#blah.com"
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxToAccess)
$folderfindResults = $service.FindFolders($folderid, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
Here is a simple example of connecting to a different mailbox
$MailboxName = New-Object Microsoft.Exchange.WebServices.Data.Mailbox("support#domain.com") #specifies which mailbox EWS should connect to
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
For more detailed info please read this blog: https://gsexdev.blogspot.com/2016/10/ews-basics-accessing-and-using-shared.html
Thank you for your support.
I was able to do it with the line
$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Mailbox);
Resolve.
I was getting a 401 error. The error was because I had overwritten the credentials. Now everything works.
In Exchange the executing user needs the role
"ApplicationImpersonation"

Array behaviour difference in PowerShell 2 to PowerShell 3

I have observed a difference in behavior between PowerShell 2.0 code and 3.0 code but can't seem to fix it. I am hoping I can get some help. Please see code below.
If you run this in V2 (please change ServerA and ServerB to a server on your network) you will see after selecting and clicking the button, write-host shows them as seperate names. In version 3 the listbox populates it as 1.
$Servers = #()
[array]$ServerstoPing = ("ServerA","ServerB")
# Generate the form
Add-Type -AssemblyName System.Windows.Forms
$Form1 = New-Object system.Windows.Forms.Form
$Form1.Text = "Ping Some Servers"
$Font = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::regular)
$Fontboxes = New-Object System.Drawing.Font("Lucida Sans",8,[System.Drawing.FontStyle]::regular)
$Fontdate = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$FontProgress = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$Form1.Font = $Font
$Serverlistbox = New-Object System.Windows.Forms.Listbox
$Serverlistbox.Location = New-Object System.Drawing.Size(11,137)
$Serverlistbox.Size = New-Object System.Drawing.Size(200,170)
$Serverlistbox.SelectionMode = "MultiExtended"
$Serverlistbox.font = $Fontboxes
foreach($item in $ServerstoPing){
[void] $Serverlistbox.Items.Add("$item")
}
$Form1.Controls.Add($Serverlistbox)
$SubmitButton = New-Object System.Windows.Forms.button
$SubmitButton.text = "Ping Servers"
$SubmitButton.Location = New-Object System.Drawing.Size(171,305)
$SubmitButton.AutoSize = $True
$Form1.Controls.Add($SubmitButton)
$Form1.StartPosition = "CenterScreen"
$OutputPing = New-Object System.Windows.Forms.TextBox
$OutputPing.MultiLine = $True
$OutputPing.ScrollBars = "Vertical"
$OutputPing.text = "Server ping status will be displayed here once done'."
$OutputPing.font = $Fontboxes
$OutputPing.Location = New-Object System.Drawing.Size(226,40)
$OutputPing.Size = New-Object System.Drawing.Size(200,255)
$Form1.Controls.Add($OutputPing)
$SubmitButton.add_click({
#foreach ($objItem in $ServerstoPing)
foreach ($objItem in $Serverlistbox.SelectedItems)
{
$Servers += $objItem
}
write-host $ServerstoPing
Foreach($server in $servers)
{
ping -n 1 -w 1000 $server | out-null
if($? -eq $true){
write-host ("$server ping success")
}
else
{
write-host ("$server did not respond to ping, not extracting events")
}
}
})
$Form1.ShowDialog()

powershell script.exe is disappearing

I have some ps script which is runs OK via PowerShell ISE env.
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(600,400)
$objForm.StartPosition = "CenterScreen"
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(50,50)
$objTextBox.Size = New-Object System.Drawing.Size(150,20)
$findLabel = New-Object System.Windows.Forms.Label
$findLabel.Location = New-Object System.Drawing.Size(50,100)
$findLabel.Size = New-Object System.Drawing.Size(300,20)
$findLabel.Text = "Nađi:"
$findBox = New-Object System.Windows.Forms.TextBox
$findBox.Location = New-Object System.Drawing.Size(50,120)
$findBox.Size = New-Object System.Drawing.Size(260,20)
$replaceLabel = New-Object System.Windows.Forms.Label
$replaceLabel.Location = New-Object System.Drawing.Size(50,180)
$replaceLabel.Size = New-Object System.Drawing.Size(300,20)
$replaceLabel.Text = "Zameni sa:"
$replaceBox = New-Object System.Windows.Forms.TextBox
$replaceBox.Location = New-Object System.Drawing.Size(50,200)
$replaceBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($startButton)
$objForm.Controls.Add($findBox)
$objForm.Controls.Add($replaceBox)
$objForm.Controls.Add($objTextBox)
$objForm.Controls.Add($beginScriptButton)
$objForm.Controls.Add($findLabel)
$objForm.Controls.Add($replaceLabel)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$startButton = New-Object System.Windows.Forms.Button
$startButton.Location = New-Object System.Drawing.Size(220,50)
$startButton.Size = New-Object System.Drawing.Size(75,23)
$startButton.Text = "Browse!"
$startButton.Add_Click({
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.Location = New-Object System.Drawing.Size(60,60)
$null = $browser.ShowDialog()
$path = $browser.SelectedPath
$objTextBox.Text = $path
})
$beginScriptButton = New-Object System.Windows.Forms.Button
$beginScriptButton.Location = New-Object System.Drawing.Size(350,130)
$beginScriptButton.Size = New-Object System.Drawing.Size(350,180)
$beginScriptButton.Text = "Begin"
$beginScriptButton.Add_Click({
$a = $objTextBox.Text
if(($a) -and ($findBox.Text) -and ($replaceBox.Text)){
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $false
$list = Get-ChildItem "c:\users\stefan\test\*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($item.FullName,$true)
$objSelection = $objWord.Selection
$wdFindContinue = 1
$FindText = $findBox.Text
$MatchCase = $false
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = $replaceBox.Text
$wdFindContinue = 1
$ReplaceAll = 2
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$ReplaceAll)
$objDoc.Save()
$objDoc.Close()
}
$objWord.Quit()
[System.Windows.Forms.MessageBox]::Show("Uspešno ste izvršili izmenu!")
}
else{
[System.Windows.Forms.MessageBox]::Show("Please fill in all fields.")
}
})
Then, I compile it via PowerGUI as .exe
And I run it, first, it opens a cmd and after a second it disappear, I can't even see my powershell form that I've created through the code.
I've tried different options through PowerGui (I want to not be displayed a cmd window, just my form). Do you know some way how to compile it to .exe and to see only form and logic behind it?
Thanks!
Compiling the script as an exe in Powershell runs it in a new instance, where you'll need to load the form components. Try adding this to the start of your script:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")