BlackBerry and Powershell
Interesting post: http://www.blackberryforums.com/bes-admin-corner/178896-powershell-bes.html
Something that might be useful to anyone that uses poweshell alot. I wrote this so I could quickly look up a users information instead of having to go the BES Admin console. I put this in my profile.ps1 along with my other custom functions so it loads when i open powershell.
Requirements:
1. Install Quest Powershell Cmdlets “http://www.quest.com/powershell/activeroles-server.aspx” and make sure the snapin is loaded in powershell. I usually load it in my profile.ps1 file.
2. To use the new functions you need to follow the following install instructions. Install these components in the following order from this web site “http://www.microsoft.com/downloads/details.aspx?FamilyId=228DE03F-3B5A-428A-923F-58A033D316E1&displaylang=en” <This allows you to take advantage of the SQL 2008 cmdlets from Microsoft>
• Microsoft SQL Server System CLR Types
• Microsoft Core XML Services (MSXML) 6.0 (Note: This component is already part of SQL Server 2005, it will likely not need to be installed. I provide it here for completeness of prerequisites).
• Microsoft SQL Server 2008 Native Client (Note: I only installed the client. I did not install the SDK as well.)
Microsoft SQL Server 2008 Management Objects
• Microsoft Windows PowerShell Extensions for SQL Server
Run this from powershell.
set-alias installutil $env:windir\microsoft.net\framework\v2.0.50727\ins tallutil
installutil -i “C:\Program Files\Microsoft SQL Server\100\Tools\Binn\Redist\Microsoft.SqlServer.M anagement.PSProvider.dll”
installutil -i “C:\Program Files\Microsoft SQL Server\100\Tools\Binn\Redist\Microsoft.SqlServer.M anagement.PSSnapins.dll”
Usuage : gbesuser “samaccountname”
function gbesuser ($user){ function devicetype ($type){ switch ($type){ "3"{"GSM"} "4"{"CDMA"} default{"Unknown"} } } function vendor($vendorID){ switch ($buser.VendorID){ "102"{"Cingular"} "103"{"NEXTEL"} "104"{"SprintPCS"} "105"{"Verizon"} "107"{"Rogers"} "109"{"Bell Mobility"} "120"{"Vodafone-UK"} "126"{"TELUS"} "138"{"Vodafone-AU"} "220"{"NNT DoCoMo"} default{"Unknown"} } } $server="<enter sql server name>" $database = "<enter database name>" $mdn = get-Qaduser $user -includeallproperties | select legacyExchangeDN,AccountIsDisabled $bsql1 = "Select UserConfig.DisplayName,MachineName,PIN,DeviceType,ModelName,PhoneNumber,AppsVer` ,VendorID,IMEI,ICCID,MsgsForwarded,MsgsSent,MsgsPending,MsgsExpired,MsgsFiltered,MsgsFailed` ,Status,LastFwdTime,LastSentTime from UserConfig,SyncDeviceMgmtSummary` ,UserStats,ServerConfig where UserConfig.ID=SyncDeviceMgmtSummary.UserConfigID ` and UserConfig.ID=UserStats.UserConfigID and UserConfig.MailboxDN = '"+$mdn.legacyexchangedn+"' ` and Serverconfig.ID=UserConfig.ServerConfigID" $buser = Invoke-Sqlcmd -query $bsql1 -serverinstance $server -database $database $buser | select displayname,machinename,pin,@{Name="DeviceType";expression={devicetype $buser.devicetype}}` ,modelname,phonenumber,appsver,@{name="VendorID";expression={vendor $buser.vendorID}}` ,imei,iccid,MsgsForwarded,msgssent,msgspending,msgsexpired,msgsfiltered,msgsfailed,status,lastfwdtime,` lastsenttime,@{name="AccountStatus";expression={if($mdn.accountisdisabled -eq $true){"Disabled Account"}else{"Normal Account"}}} }
DisplayName : ***********
MachineName : **********
PIN : ***********
DeviceType : GSM
ModelName : 8310
PhoneNumber : ***********
AppsVer : 4.5.0.110
VendorID : Cingular
IMEI : **********
ICCID : **********
MsgsForwarded : 14268
MsgsSent : 452
MsgsPending : 0
MsgsExpired : 0
MsgsFiltered : 0
MsgsFailed : 1
Status : 12
LastFwdTime : 3/1/2009 4:49:27 PM
LastSentTime : 3/1/2009 1:45:04 PM
AccountStatus : Normal Account
Powershell – UI Automation
source: http://msdn.microsoft.com/en-us/magazine/cc163301.aspx
Code download available at: TestRun2007_12.exe (164 KB)
PS C:\UIautomationWithPowerShell> get-childitem t* | select-object Name | format-table -auto
this.Controls.Add(this.listBox1); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.comboBox1); this.Controls.Add(this.label2); this.Controls.Add(this.label1);
public class Product { public readonly string ID, Name, Price; public Product(string id, string name, string price) { ID = id; Name = name; Price = price; } }
private List<Product> list = new List<Product>(); private void Form1_Load(object sender, System.EventArgs e) { list.Add(new Product("111", "Widget", "$11.11")); list.Add(new Product("222", "Gadget", "$22.22")); list.Add(new Product("333", "Thingy", "$33.33")); }
if (comboBox1.Text == "" || textBox1.Text == "") { MessageBox.Show("Please enter search criteria and term", "Error"); } listBox1.Items.Clear();
string target = textBox1.Text, criterion = comboBox1.Text; foreach (Product p in list) { if (criterion == "Product ID") { if (p.ID.IndexOf(target) >= 0) { listBox1.Items.Add(p.ID + " " + p.Name + " " + p.Price); } } else if (criterion == "Product Name") { // search for by product name similarly } }
using System; using System.Management.Automation; using System.ComponentModel; using System.Configuration.Install; using System.Runtime.InteropServices; namespace CustomUICmdletsLib { [Cmdlet(VerbsCommon.Get, "Window")] public class GetWindowCommand : Cmdlet { . . . } [Cmdlet(VerbsCommon.Get, "Control")] public class GetControlCommand : Cmdlet { . . . } [Cmdlet(VerbsCommon.Get, "ControlByIndex")] public class GetControlByIndexCommand : Cmdlet { . . . } [Cmdlet(VerbsCommunications.Send, "Chars")] public class SetCharsCommand : Cmdlet { . . . } [Cmdlet(VerbsCommunications.Send, "Click")] public class SetClickCommand : Cmdlet { . . . } [Cmdlet(VerbsCommon.Get, "ListBox")] public class GetListBoxCommand : Cmdlet { . . . } [Cmdlet(VerbsCommon.Get, "TextBox")] public class GetTextBoxCommand : Cmdlet { . . . } [Cmdlet(VerbsCommunications.Send, "Menu")] public class SetMenuCommand : Cmdlet { . . . } [RunInstaller(true)] public class LibPSSnapIn : PSSnapIn { . . . } }
[Cmdlet(VerbsCommon.Get, "Window")] public class GetWindowCommand : Cmdlet { [DllImport("user32.dll", CharSet=CharSet.Auto)] static extern IntPtr FindWindow( string lpClassName, string lpWindowName); private string windowName; [Parameter(Position = 0)] public string WindowName { get { return windowName; } set { windowName = value; } } protected override void ProcessRecord() { IntPtr wh = FindWindow(null, windowName); WriteObject(wh); } }
[Cmdlet(VerbsCommon.Get, "ControlByIndex")] public class GetControlByIndexCommand : Cmdlet { [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); private IntPtr handleParent; private int index; [Parameter(Position = 0)] public IntPtr HandleParent { get { return handleParent; } set { handleParent = value; } } [Parameter(Position = 1)] public int Index { get { return index; } set { index = value; } } protected override void ProcessRecord() { if (index == 0) { WriteObject(handleParent); } else { int ct = 0; IntPtr result = IntPtr.Zero; do { result = FindWindowEx(handleParent, result, null, null); if (result != IntPtr.Zero) ++ct; } while (ct < index && result != IntPtr.Zero); WriteObject(result); } } } // class
Cmdlet Name | Input Parameters | Return Value / Effect |
---|---|---|
get-window | windowName | Handle to a top-level window. |
get-control | handleParent, controlName | Handle to a named control. |
get-controlByIndex | handleParent, index | Handle to a non-named control. |
send-chars | handleControl, s | Sends string s to a control. |
send-click | handleControl | Clicks a control. |
get-listBox | handleControl, target | Zero-based location of target or -1. |
get-textBox | handleControl | Contents of TextBox as a string. |
send-menu | mainIndex, subIndex | Fires application menu command. |
[RunInstaller(true)] public class LibPSSnapIn : PSSnapIn { public LibPSSnapIn() : base() { } public override string Name { get { return "LibPSSnapIn"; } } public override string Vendor { get { return "James McCaffrey"; } } public override string Description { get { return " Provides cmdlets for lightweight UI automation"; } } }
# file: Microsoft.PowerShell_profile.ps1 function RegisterUILib { write-host "registering custom cmdlets for UI automation`n" $env:path = $env:path += ";C:\Windows\Microsoft.NET\Framework\v2.0.50727" sl 'C:\UIautomationWithPowerShell\CustomUICmdletsLib\bin\Debug' installutil.exe CustomUICmdletsLib.dll | out-null add-pssnapin LibPSSnapin write-host "get-window, get-control, get-controlByIndex, send-chars, send-click" write-host "get-listBox, send-menu, and get-textBox custom cmdlets are enabled `n" } RegisterUILib # invoke function set-location C:\UIautomationWithPowerShell # end startup script
# testScenario.ps1 write-host "`nBegin UI automation with PowerShell test" $pass = $true write-host "`nLaunching application to automate" invoke-item '.\TheAppToTest\bin\Debug\TheAppToTest.exe' [System.Threading.Thread]::Sleep(2000)
$app = get-window "Form1" $cb = get-controlByIndex $app 4 $btn = get-control $app "Search" $tb = get-controlByIndex $app 3
write-host "`nHandle to Application is " $app write-host "Handle to ComboBox is" $cb write-host "Handle to Button is " $btn write-host "Handle to TextBox is " $tb write-host "`nClicking on search button" send-click $btn
write-host "Finding Error Message box" [System.Threading.Thread]::Sleep(2000) $mbox = get-window "Error" write-host "Clicking Message Box away" $ok = get-control $mbox "OK" send-click $ok
write-host "`nSending 'Product Name' to ComboBox" send-chars $cb "Product Name" write-host "Sending 'ad' to TextBox" send-chars $tb "ad" write-host "Re-clicking search button" send-click $btn
write-host "`nChecking contents of ListBox for '222'" [System.Threading.Thread]::Sleep(2000) $lb = get-controlByIndex $app 1 write-host "Handle to ListBox is " $lb $result = get-listBox $lb "222"
if ($result -ge 0) { write-host "Found '222' in ListBox!" } else { write-host "Did NOT find '222' in ListBox" $pass = $false }
write-host "Checking contents of TextBox for 'ad'" [System.Threading.Thread]::Sleep(2000) $text = get-textBox $tb
if ($text -eq "ad") { write-host "Found 'ad' in TextBox!" } else { write-host "Did NOT find 'ad' in TextBox" $pass = $false }
if ($pass) { write-host "`nTest scenario result = Pass" -foregroundcolor green } else { write-host "`nTest scenario result = * FAIL *" -foregroundcolor red }
write-host "`nClicking File -> Exit in 5 seconds . . ." [System.Threading.Thread]::Sleep(5000) send-menu $app 0 0 write-host "`nEnd UI automation with PowerShell test`n" # end script
Send your questions and comments for James to testrun@microsoft.com.
Powershell – How to use a config file (ini, conf,…) with a Powershell Script ? Is it possible ?
Hi
Is it possible to use a configuration file with a PowerShell script ?
for example, the configuration file:
#links
link1=http://www.google.com
link2=http://www.apple.com
link3=http://www.microsoft.com
and then call this information in the PS1 script:
start-process iexplore.exe $Link1
thanks in advance for your help!!
Your answers put me on the good track and I found this
SETTINGS.TXT
#from http://tlingenf.spaces.live.com/blog/cns!B1B09F516B5BAEBF!213.entry
#
[General]
MySetting1=value
[Locations]
InputFile="C:\Users.txt"
OutputFile="C:\output.log"
[Other]
WaitForTime=20
VerboseLogging=True
POWERSHELL COMMAND
#from http://tlingenf.spaces.live.com/blog/cns!B1B09F516B5BAEBF!213.entry
#
Get-Content "C:\settings.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }
then
After executing the code snippet, a variable ($h) will contain the values in a HashTable.
Name Value
---- -----
MySetting1 value
VerboseLogging True
WaitForTime 20
OutputFile "C:\output.log"
InputFile "C:\Users.txt"
*To get an item from the table use the command $h.Get_Item(“MySetting1”).*
Powershell – Finding Old Files
source:http://powershell.com/cs/blogs/tips/archive/2008/11/20/finding-old-files.aspx
filter FileAge($days) { if ( ($_.CreationTime -le (Get-Date).AddDays($days * -1) )) { $_ } }
Pipe the result of a Dir into FileAge filter, and it will only let those files pass that are at least the specified number of days old. The following line finds all PowerShell Script files in your personal folder that are at least 10 days old:
Dir $home\*.ps1 | FileAge 10
You could easily delete or backup the resulting files like this:
Dir $home\*.ps1 | FileAge 10 | Del -WhatIf
Powershell – A Task-Based Guide to Windows PowerShell Cmdlets
Source: http://technet.microsoft.com/en-us/scriptcenter/dd772285.aspx
A Task-Based Guide to Windows PowerShell Cmdlets
Cmdlets are the heart-and-soul of Windows PowerShell, Microsoft’s latest command shell/scripting language. This series provides a task-based introduction to Windows PowerShell cmdlets: Rather than focusing on the individual cmdlets themselves, the emphasis is on the tasks you can carry out using those cmdlets. These tasks include everything from reading and writing text files to managing event logs to sorting and filtering data.
As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.
Dates and TimesThese tasks include such things as retrieving the current date and time, and performing date arithmetic. Files and FoldersThese tasks include such things as creating, renaming, copying, and deleting files and folders. Help and InformationThese tasks include such things as listing Windows PowerShell version information and using the Get-Member cmdlet to retrieve property and method information for an object.
Saving and Importing DataThese tasks include such things as reading and writing to text files as well as saving data in HTML or XML format. Scripting TechniquesThese techniques include such things as sorting data, filtering data, and prompting a user to enter information. |
Security and Security DescriptorsThese tasks include such things as configuring the Windows PowerShell script execution policy and retrieving the digital signature or security descriptor from a file or folder. System Administration TasksThese tasks include such things as starting and stopping services, retrieving data using WMI, and managing event logs and event log events. Windows PowerShell AliasesThese tasks include such things as retrieving and remapping existing aliases as well as creating new aliases. Windows PowerShell SessionsThese tasks include such things as retrieving the Windows PowerShell history and re-invoking a command contained within that history. Scripts and ApplicationsThese tasks include such things as running scripts and/or applications as well as measuring how long it takes a Windows PowerShell task to complete. |