My PowerShell script function:
function Click {
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(10,150)
$outputBox.Size = New-Object System.Drawing.Size(565,200)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
$userid = $Emailid.text;
$uid=[bool]($userid -as [Net.Mail.MailAddress])
if($uid -eq "True")
{
$outputBox.Text = "Email id exists"
}
else
{
$outputBox.Text = "Email id not exists"
}
$owa = [bool](Get-CasMailbox $userid | fl owaenabled)
if($owa -eq "True")
{
$outputBox.AppendText = " your email id has owa access"
}
else
{
$outputBox.AppendText = "sorry... your email id has not owa access"
}
}
When my button is pressed above function is called, but I am only able to see last result into the $outputBox, but I want both the output in textbox. Also ForegroundColor is not working with it. It gives error, so how to use ForegroundColor with it?
AppendText() is a method. You're using it like a property. Change this:
if($owa -eq "True")
{
$outputBox.AppendText = " your email id has owa access"
}
else
{
$outputBox.AppendText = "sorry... your email id has not owa access"
}
into this:
if($owa -eq "True")
{
$outputBox.AppendText(" your email id has owa access")
}
else
{
$outputBox.AppendText("sorry... your email id has not owa access")
}
As for the foreground color: you don't set that anywhere, and the property is named ForeColor, not ForegroundColor.
$outputBox.ForeColor = 'Red'
Related
An array returned from a function has an unexpected element appended to it, and I cannot understand how to fix it. A help will be so much appreciated.
The array in function A, for some unknown reason is different to the array in function B that calls the function A.
function functionA(...)
{
[...]
$status = (,#("reserved",$proj,$id));
Write-Host "Status in FunctionA to FunctionB: "$status
[...]
return $status
}
I get from the Write-Host above: Status in FunctionA to FunctionB: reserved B hfuhfkhec8u8b7hf4smeu43gn4
function functionB(...)
{
[...]
$funcA = functionA
Write-Host "Status in FunctionB from FunctionA: "$funcA
[...]
}
I get from the Write-Host above: Status in FunctionB from FunctionA: 1 reserved B hfuhfkhec8u8b7hf4smeu43gn4. You can observe the $status in functionA has not the value 1, so why I get the value 1 appended in the array? What may I do to fix it?
Please check the complete code bellow, where FunctionA is CheckReservation and FunctionB is PeriodicCheckIn
PS: I noted that if I comment the function InformationMsgBox to do not call if in CheckReservation, then the code works.
function CheckReservation($headers){
$events = GetCalendarEvents($headers)
$users = Get-IniFile ..\ini\Users.ini
$user = $users.$env:UserName.email
$error = "There is not any confirmed reservation for this machine."; $status = (,#("NoReservations",$error));
$calendarId = Get-IniFile ..\ini\Computers.ini
$calendarId = $calendarId.$env:Computername.calendarId
foreach($item in $events.items)
{
if($item.status -match "confirmed")
{
$attender = $item.attendees.email |
Where-Object {$_ -contains $user}
$calendar = $item.attendees |
Where-Object {$_.email -contains $calendarId}
$calendarEmail = $calendar.email
$calendarStatus = $calendar.responseStatus
$organizer = $item.organizer.email | Where-Object {$_ -contains $user}
if(($attender -match $user) -or ($item.organizer.email -match $user))
{
if(($calendarStatus -match "accepted") -or ($item.organizer.email -match $calendarId))
{
$current = [Xml.XmlConvert]::ToString((get-date),[Xml.XmlDateTimeSerializationMode]::Local)
if(((get-date $current) -ge (get-date $item.start.dateTime)) -and ((get-date
$current) -lt (get-date $item.end.dateTime)))
{
$timespan = NEW-TIMESPAN –Start (get-date $current) –End (get-date $item.end.dateTime);
$timeexpire = [int]$timespan.TotalMinutes;
Write-Host "Minutes to expire reservation: "$timeexpire;
$Timers = Get-IniFile ..\ini\Timers.ini;
$WarningBeforeExp = $Timers.Timers.WarningBeforeExp_min;
if($timeexpire -le $WarningBeforeExp)
{
$msg = message(21);
Write-Host $msg;
InformationMsgBox $msg 10;
}
$proj=$item.summary
$id=$item.id
$status = (,#("reserved",$proj,$id));
Write-Host "Status in FunctionA to FunctionB: "$status
} else { $msg = "Reservation expired or schedule time mismatch."; $status = (,#("outOfTime",$msg)); }
}
} else { $msg = "You are not an attender for the current reservation for this machine."; $status = (,#("IsNotAttender",$msg));}
} else { $msg = "There is not any confirmed reservation for this machine. You can use it until someone makes a reservation."; $status = (,#("NoReservations",$msg));}
}
return $status
}
function PeriodicCheckIn ($OAuth2){
$checkin = $false
$Timers = Get-IniFile ..\ini\Timers.ini
$CheckInPeriodicity = $Timers.Timers.CheckInPeriodicity_min
for($i=1;;$i++)
{
$timeout = IdleTimeout
if(-not $timeout)
{
$funcA = CheckReservation $OAuth2
Write-Host "Status in FunctionB from FunctionA: "$funcA
$reservation = $funcA
if ($reservation[0] -match "reserved")
{
$project = $reservation[1]
$id = $reservation[2]
Write-Host "Reservation found"
Write-Host "Project: "$project
Write-Host "Id: "$id
if(-not $checkin)
{
storageData "CheckInOut" $OAuth2 "CheckIn" $project "" $false
$checkin = $true
$msg = message(15)
Write-Host $msg
InformationMsgBox $msg -1
}
else
{
storageData "updatetime" $OAuth2 "LastUpdate" $project "" $false
}
}
elseif($i -eq 1)
{
Write-Host "Reservation not found"
$Availability = CheckAvailability $OAuth2 "10"
Write-Host "Availability for now: "$Availability
if($Availability -match "Yes")
{
$msg = message(16)
$msgBoxInput = QuestionMsgBox $msg 30
if($msgBoxInput -eq 6)
{
$project = GetProject "FromUser"
CreateReservation $OAuth2 $project "10"
storageData "CheckInOut" $OAuth2 "CheckIn" $project "" $false
$checkin = $true
$msg = message(15)
Write-Host $msg
InformationMsgBox $msg -1
}
else
{
$leave = $true;
}
} else
{
$leave = $true;
}
}
else
{
Write-Host "O pau é aqui?1 $reservation[1]"
$msg = message(18, $reservation[1]);
Write-Host "O pau é aqui?2 $reservation[1]"
StopMsgBox $msg -60
$leave = $true;
}
} else {$leave = $true;}
if($leave -eq $true){ return $true}
Write-Host "CheckIn $i"
start-sleep -Seconds ([double]$CheckInPeriodicity*60)
}
}
function message($index,$txt){
$LastWarning_min = Get-IniFile ..\ini\Timers.ini
$LastWarning_min = $LastWarning_min.Timers.LastWarning_min/60
$ManualAuthTimeout_min = $LastWarning_min.Timers.ManualAuthTimeout_min
Write-Host "Next message index: $index"
$arrMessage =
"[MSG000] It is not possible to identify if this current PC is Workstation or Buildstation machine.",
"[MSG001] Shutting down the system.",
"[MSG002] You do not have approriate access to this function. Get in contact with lab support.",
"[MSG003] An error occurred. Verify if there are at least two not empty .txt file, if the path is correct or if you have write permission to the path $txt.",
"[MSG004] Attempt to delete a folder that does not exist: $txt.",
"[MSG005] Mapping failed. Make sure your connection can reach the networking that remote path ""$txt"" belongs.",
"[MSG006] Team not specified for the user $env:UserName. Please make sure the user is registered.",
"[MSG007] Connection failed. Make sure the PC can reach FIATAUTO networking then try again.",
"[MSG008] Error while Import-Module.",
"[MSG009] Error on OAuth 2.0 for Google APIs Authorization.",
"[MSG010] Error on Method: spreadsheets.values.get (writing) for Google Sheets API request.",
"[MSG011] Error on Method: spreadsheets.values.get (reading) for Google Sheets API request.",
"[MSG012] Error on Method: scripts.run for Google App Script API request.",
"[MSG013] Error on Events: get for Google Calendar API request.",
"[MSG014] Error on Events: list for Google Calendar API request.",
"[MSG015] Your access has been granted to work on the project: $global:project.",
"[MSG016] No reservation was found. Would you like to make a short reservation?",
"[MSG017] Permission to shared drives mismatch. Select OK to proceed for manual authorization within $ManualAuthTimeout_min minutes or select CANCEL for Windows logoff now.",
"[MSG018] No valid reservation found. $txt",
"[MSG019] Inactive time exceeded the inactivity limit. Select OK within 60 seconds to avoid the current Windows session logoff.",
"[MSG020] Save your files now. Shutting down the system within $LastWarning_min seconds.",
"[MSG021] Your reservation is close to expire!"
return $arrMessage[$index]
}
function InformationMsgBox($msg, $msg_timeout){
$sh = New-Object -ComObject "Wscript.Shell"
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64)
}
As you have noted yourself, the InformationMsgBox is to blame. Every command returning output gets added to the pipeline.
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64) returns the 1 you see added to your array. You can suppress it's output by sending it to Out-Null.
function InformationMsgBox($msg, $msg_timeout){
$sh = New-Object -ComObject "Wscript.Shell"
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64) | Out-Null
}
giving the following PowerShell Studio Code, how can I call and disable the 'David Checkbox' under the 'Checkit' button. I know I am messing up on the checkbox declaration somehow because powershell does not recognize my checkbox as an object:
The property 'Enabled' cannot be found on this object. Verify that the property exists and can be set.
$accounts = "David", "Dave"
$buttonLoadLabels_Click = {
$CheckBoxCounter = 1
$accounts = 'didier','david'
foreach ($account in $accounts)
{
$label = New-Object System.Windows.Forms.Label
$label.Text = $account
$label.TextAlign = 'MiddleCenter'
$label.Font = $label1.Font
$flowlayoutpanel1.Controls.Add($label)
$CB = New-Object System.Windows.Forms.CheckBox
$CB.Name = $account
Write-Host $CB.Name
$flowlayoutpanel1.Controls.Add($CB)
}
}
$buttonCheckIt_Click = {
$checkbox_David.Enabled = $false
}
I am creating an admin tool for our helpdesk and I want the option to allow the tool to stay on top of other windows via a checkbox. This is the inital setup of the checkbox:
$cbx_OnTop = New-Object system.Windows.Forms.CheckBox
$cbx_OnTop.text = "Keep On Top"
$cbx_OnTop.AutoSize = $false
$cbx_OnTop.width = 175
$cbx_OnTop.height = 20
$cbx_OnTop.location = New-Object System.Drawing.Point(24,290)
$cbx_OnTop.Font = 'Microsoft Sans Serif,8'
$cbx_OnTop.Checked = $false
I then have the following function:
function KeepOnTop {
if ($cbx_OnTop.Checked = $True) {
$AdminTool.TopMost = $True
} else {
$AdminTool.TopMost = $false
}
}
How do I add the function to this checkbox?
The Add_CheckStateChanged event is the command you are looking for.
$cbx_OnTop.Add_CheckStateChanged({
If ($cbx_OnTop.Checked) {
$AdminTool.TopMost = $True
} Else {
$AdminTool.TopMost = $false
}
)}
Afternoon all,
I wanna believe this one is pretty easy but hitting a wall and can't figure out why.
I have a PowerShell winform that's going to create a new user account from a template. One of the fields I'm working on now is the line manager; once a template account has been found, auto-fill the line manager field, but allow it to be overwritten if this is incorrect.
For the pre-populated stuff I've been using:
$FORMCONTROL.Add_TextChanged( {
However once the template has been found and the line manager field written too, I can't overwrite it. Is there another Event I should be using to populate the box but allow me to delete the content and add something else?
The code below is a much cut down version of what I'm using. The functions allow for finding a user account and populating the ReadOnly box.
Function FindUser {
IF ( $SEARCHUSER -like $NULL -or $SEARCHUSER -like " *" )
{ }
ELSEIF ( $ACCOUNT = dsquery user -samid $SEARCHUSER )
{ $ACCOUNT = Get-ADUser $SEARCHUSER -Property * }
ELSEIF ( $ACCOUNT = Get-ADUser -Filter { mail -eq $SEARCHUSER } -ea sil )
{ $ACCOUNT = Get-ADUser -Filter { mail -eq $SEARCHUSER } -Property * }
ELSEIF ( dsquery user -name $SEARCHUSER )
{ $ACCOUNT = Get-ADUser -Filter { name -eq $SEARCHUSER } -Property * }
ELSE
{ $( foreach ( $SEARCHUSER in ( Get-ADUser -Filter { ( Surname -like $SEARCHUSER ) -and ( Enabled -eq $TRUE )
} -Properties Mail, Department, Office | sort Name ) )
{ $SEARCHUSER | Select Name, #{ N = "Username" ; E = { $_.SamAccountName } }, Mail, Department, Office
} ) | Out-GridView -Title 'Select the user account' -OutputMode Single | %{
TRY
{ $ACCOUNT = Get-ADUser $_.UserName -Property * }
CATCH
{ } } }
IF ( ( $ACCOUNT.SamAccountName ).count -eq 1 )
{ $Script:ACCOUNT = $ACCOUNT }
ELSE
{ $Script:ACCOUNT = $NULL } }
Function TemplateUser {
IF ( $ACCOUNT -ne $NULL )
{ $TAB1TEMPLATE_5.Text = ( $ACCOUNT.Name ) }
ELSEIF ( $TAB1TEMPLATE_3.Text.Length -lt 4 )
{ $TAB1TEMPLATE_5.Text = $NULL } }
# Creates the parent form and controls
$SDC = New-Object System.Windows.Forms.Form
$SDC.Location = New-Object System.Drawing.Size( 270,175 )
$SDC.Size = New-Object System.Drawing.Size( 900,600 )
$SDC.StartPosition = "CenterScreen"
$SDC.BackColor = "Lavender"
$SDC.Font = "Calibri, 8.5"
$SDC.FormBorderStyle = "Fixed3D"
#Tab 1 Template Account Label
$TAB1TEMPLATE_2 = New-Object System.Windows.Forms.Label
$TAB1TEMPLATE_2.Location = '35,90'
$TAB1TEMPLATE_2.Size = '200,20'
$TAB1TEMPLATE_2.Font = New-Object System.Drawing.Font( "Calibri",10,[System.Drawing.FontStyle]::Bold )
$TAB1TEMPLATE_2.Text = "Who are we using as a template?"
$SDC.Controls.Add( $TAB1TEMPLATE_2 )
#Tab 1 Template Textbox
$TAB1TEMPLATE_3 = New-Object System.Windows.Forms.TextBox
$TAB1TEMPLATE_3.Location = '20,115'
$TAB1TEMPLATE_3.Size = '200,20'
$TAB1TEMPLATE_3.Font = New-Object System.Drawing.Font( "Calibri",9 )
$SDC.Controls.Add( $TAB1TEMPLATE_3 )
#Tab 1 Template Textbox - When hit Return
$TAB1TEMPLATE_3.Add_KeyDown( {
IF ( $_.KeyCode -eq 'Enter' )
{ $SEARCHUSER = $TAB1TEMPLATE_3.Text ; FindUser ; TemplateUser } } )
#Tab 1 Template Account's Full Name
$TAB1TEMPLATE_5 = New-Object System.Windows.Forms.TextBox
$TAB1TEMPLATE_5.Location = '20,150'
$TAB1TEMPLATE_5.Size = '200,20'
$TAB1TEMPLATE_5.ReadOnly = $TRUE
$TAB1TEMPLATE_5.Font = New-Object System.Drawing.Font( "Calibri",9 )
$SDC.Controls.Add( $TAB1TEMPLATE_5 )
#Tab 1 Line Manager Label
$TAB1MANAGER_2 = New-Object System.Windows.Forms.Label
$TAB1MANAGER_2.Location = '35,400'
$TAB1MANAGER_2.Name = "Manager"
$TAB1MANAGER_2.Size = '245,20'
$TAB1MANAGER_2.Font = New-Object System.Drawing.Font( "Calibri",10,[System.Drawing.FontStyle]::Bold )
$TAB1MANAGER_2.Text = "Line Manager"
$SDC.Controls.Add( $TAB1MANAGER_2 )
#Tab 1 Line Manager Textbox
$TAB1MANAGER_3 = New-Object System.Windows.Forms.TextBox
$TAB1MANAGER_3.Location = '20,420'
$TAB1MANAGER_3.Size = '245,20'
$TAB1MANAGER_3.Name = "Manager"
$TAB1MANAGER_3.Font = New-Object System.Drawing.Font( "Calibri",9 )
$SDC.Controls.Add( $TAB1MANAGER_3 )
$TAB1MANAGER_3.Text = $( If ( $TAB1TEMPLATE_3.text -eq $NULL ) { "hi" } )
$SDC.ShowDialog()
I appear to have fixed it by editing the Function TemplateUser:
Function TemplateUser {
IF ( $ACCOUNT -ne $NULL )
{ $TAB1TEMPLATE_5.Text = ( $ACCOUNT.Name )
$TAB1MANAGER_3.Text = ( Get-ADUser $ACCOUNT.Manager ).Name
}
ELSEIF ( $TAB1TEMPLATE_3.Text.Length -lt 4 )
{ $TAB1TEMPLATE_5.Text = $NULL } }
Lord knows what I was doing wrong in the first place as didn't save the changes.
#TheIncorrigible1 - Curious to know what you mean by the formatting. Genuinely. Is there a more efficient way of writing? I'm aware that when complete this script is going to be pretty big so if I'm using unnecessary code I'm all ears.
I have a ListView on a form built in PowerShell which I just can't get sorted.
If I call $LV.Sort() from the command line (while the form is not shown) it works perfectly fine. However if I try to call it in an OnClick event on anything on the form it doesn't. I've put flags in and I know that section of code is running, it's just not doing anything or flagging any errors.
Obviously $LV.Sorting = "Ascending" is set otherwise it wouldn't be sorting at all, and I can change the items so the reference to the ListView is fine. Also tried invoking in case of a threading issue but no different.
Annoyingly this is a tricky subject to research due to so many people forgetting to set the Sorting property.
EDIT: Not sure if relevant but the form is called with ShowDialog()
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = New-Object System.Windows.Forms.Form
$LVserverlist = New-Object System.Windows.Forms.ListView
$form.Controls.Add($LVserverlist)
$LVserverlist.Dock = "Fill"
$LVserverlist.View = "Details"
$LVserverlist.Sorting = "Ascending"
$LVserverlist.Add_ColumnClick({ $LVserverlist.sort(); $LVserverlist.Items[0].Text = "Working?" })
$LVserverlist.Columns.Add("Name", 200, "Left") | Out-Null
0..10 | Foreach-Object {
$LVItem = New-Object System.Windows.Forms.ListViewItem
$LVItem.Text = (Get-Random -Maximum 1000).ToString()
$LVserverlist.Items.Add($LVItem) | Out-Null
}
$form.ShowDialog()
You can try with custom function Sort-ListViewColumn
$MyListView.Add_ColumnClick({
param($sender,$e)
# Sort as Text String (not [int])
Sort-ListViewColumn -ListView $this -ColumnIndex $e.column
})
full function code :
function Sort-ListViewColumn
{
<#
.SYNOPSIS
Sort the ListView's item using the specified column.
.DESCRIPTION
Sort the ListView's item using the specified column.
This function uses Add-Type to define a class that sort the items.
The ListView's Tag property is used to keep track of the sorting.
.PARAMETER ListView
The ListView control to sort.
.PARAMETER ColumnIndex
The index of the column to use for sorting.
.PARAMETER SortOrder
The direction to sort the items. If not specified or set to None, it will toggle.
.EXAMPLE
Sort-ListViewColumn -ListView $listview1 -ColumnIndex 0
.NOTES
SAPIEN Technologies, Inc.
http://www.sapien.com/
#>
param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Forms.ListView]$ListView,
[Parameter(Mandatory = $true)]
[int]$ColumnIndex,
[System.Windows.Forms.SortOrder]$SortOrder = 'None')
if (($ListView.Items.Count -eq 0) -or ($ColumnIndex -lt 0) -or ($ColumnIndex -ge $ListView.Columns.Count))
{
return;
}
#region Define ListViewItemComparer
try
{
$local:type = [ListViewItemComparer]
}
catch
{
Add-Type -ReferencedAssemblies ('System.Windows.Forms') -TypeDefinition #"
using System;
using System.Windows.Forms;
using System.Collections;
public class ListViewItemComparer : IComparer
{
public int column;
public SortOrder sortOrder;
public ListViewItemComparer()
{
column = 0;
sortOrder = SortOrder.Ascending;
}
public ListViewItemComparer(int column, SortOrder sort)
{
this.column = column;
sortOrder = sort;
}
public int Compare(object x, object y)
{
if(column >= ((ListViewItem)x).SubItems.Count)
return sortOrder == SortOrder.Ascending ? -1 : 1;
if(column >= ((ListViewItem)y).SubItems.Count)
return sortOrder == SortOrder.Ascending ? 1 : -1;
if(sortOrder == SortOrder.Ascending)
return String.Compare(((ListViewItem)x).SubItems[column].Text, ((ListViewItem)y).SubItems[column].Text);
else
return String.Compare(((ListViewItem)y).SubItems[column].Text, ((ListViewItem)x).SubItems[column].Text);
}
}
"# | Out-Null
}
#endregion
if ($ListView.Tag -is [ListViewItemComparer])
{
#Toggle the Sort Order
if ($SortOrder -eq [System.Windows.Forms.SortOrder]::None)
{
if ($ListView.Tag.column -eq $ColumnIndex -and $ListView.Tag.sortOrder -eq 'Ascending')
{
$ListView.Tag.sortOrder = 'Descending'
}
else
{
$ListView.Tag.sortOrder = 'Ascending'
}
}
else
{
$ListView.Tag.sortOrder = $SortOrder
}
$ListView.Tag.column = $ColumnIndex
$ListView.Sort()#Sort the items
}
else
{
if ($Sort -eq [System.Windows.Forms.SortOrder]::None)
{
$Sort = [System.Windows.Forms.SortOrder]::Ascending
}
#Set to Tag because for some reason in PowerShell ListViewItemSorter prop returns null
$ListView.Tag = New-Object ListViewItemComparer ($ColumnIndex, $SortOrder)
$ListView.ListViewItemSorter = $ListView.Tag #Automatically sorts
}
}
Never did find a solution to getting Sort() to work, ended up with this workaround (which is a bit more flexible anyway):
Param
(
[System.Windows.Forms.ListView]$sender,
$column
)
$temp = $sender.Items | Foreach-Object { $_ }
$sender.Items.Clear()
$sender.Items.AddRange(($temp | Sort-Object -Property #{ Expression={ $_.SubItems[$column].Text } }))
Note that on the ListView the Sorting property needs to be set to None otherwise the items will be added back alphabetically.
coller event
$MyListView.add_ColumnClick({SortListView $this $_.Column})
Sort function whit memorize the lastest Order :
function SortListView {
Param(
[System.Windows.Forms.ListView]$sender,
$column
)
$temp = $sender.Items | Foreach-Object { $_ }
$Script:SortingDescending = !$Script:SortingDescending
$sender.Items.Clear()
$sender.ShowGroups = $false
$sender.Sorting = 'none'
$sender.Items.AddRange(($temp | Sort-Object -Descending:$script:SortingDescending -Property #{ Expression={ $_.SubItems[$column].Text } }))
}