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 – Manage DNS in a Windows Environment
Manage DNS in a Windows Environment by Using PowerShell
Summary: Manage DNS in a Windows environment by using Windows PowerShell. Guest Blogger Richard Siddaway shows how to do it in a simple and effective manner.
Hey, Scripting Guy! What can I do with Windows PowerShell to manage my DNS infrastructure?
— RS
Hello RS,
Microsoft Scripting Guy Ed Wilson here. I am happy to announce that this is Guest Blogger Week. I love to host these guest bloggers because they give our readers a glimpse into other professionals’ minds and knowledge. Today, we have Richard Siddaway. Richard is a technical architect for Serco in the United Kingdom. He works on transformation projects in the local government and commercial arena. With more than 20 years of experience in various aspects of information technology, Richard specializes in the Microsoft environment at an architectural level, especially around Active Directory, Exchange, SQL Server, and infrastructure optimization.
Richard is always looking for the opportunity to automate a process, preferably with Windows PowerShell. Richard founded and currently leads the UK Windows PowerShell User Group. Microsoft has recognized his technical expertise and community activities by presenting him with a Microsoft Most Valued Professional award. Richard has presented to the Directory Experts Conference, at various events at Microsoft in the UK and Europe, and for other UK User Groups. He has a number of articles and technical publications to his credit, and his first print book has recently been released. The subject? Windows PowerShell, of course.
Blog: http://msmvps.com/blogs/RichardSiddaway/Default.aspx
Book details: http://www.manning.com/siddaway
Take it away, Richard…
_______
RS, the short answer to the question about using Windows PowerShell to manage DNS is that you can do anything you want. The longer answer is that you have to work at it a bit. Some areas of working with DNS have already been blogged about by Ed Wilson of the Microsoft Scripting Guys. Here are links to his articles:
- http://blogs.technet.com/b/heyscriptingguy/archive/2009/02/26/how-do-i-query-and-retrieve-dns-information.aspx
- http://blogs.technet.com/b/heyscriptingguy/archive/2009/02/25/how-do-i-create-a-new-dns-zone.aspx
- http://blogs.technet.com/b/heyscriptingguy/archive/2009/02/24/how-can-i-create-dns-mail-exchanger-mx-records-and-have-a-text-file-generated-to-show-what-was-created.aspx
- http://blogs.technet.com/b/heyscriptingguy/archive/2009/02/23/how-do-i-check-host-name-records.aspx
Windows PowerShell doesn’t have any way of directly working with DNS. However, there is a great set of WMI classes. They are installed automatically when DNS is installed. At this point, you might be groaning “I don’t like WMI; it’s too hard”. It used to be. Windows PowerShell has brilliant WMI support that makes using it easy and well worth spending a bit of time learning, as you will see.
A new namespace is created for the DNS WMI classes: root\MicrosoftDNS. Because we are using WMI, we can access the DNS server remotely (which makes administration easier). The classes available to work with DNS can be found by using Windows PowerShell:
Get-WmiObject -Namespace root\MicrosoftDNS -List
The DNS classes from a remote DNS server running on a Windows Server 2008 domain controller are shown in the following image.
In a modern Windows environment, most machines will register their own addresses with DNS (we may need to set reverse lookup—PTR—records through DHCP). There is still a need to create DNS records from time to time, such as if you need to create an alias record. You have a number of WMI classes for working with different DNS record types, which you can see here:
Get-WmiObject -Namespace root\MicrosoftDNS -List *type | Format-Wide -Column 3
MicrosoftDNS_MGType MicrosoftDNS_X25Type MicrosoftDNS_AFSDBType
MicrosoftDNS_PTRType MicrosoftDNS_KEYType MicrosoftDNS_SRVType
MicrosoftDNS_MDType MicrosoftDNS_MBType MicrosoftDNS_AAAAType
MicrosoftDNS_ISDNType MicrosoftDNS_MINFOType MicrosoftDNS_RPType
MicrosoftDNS_SIGType MicrosoftDNS_MFType MicrosoftDNS_AType
MicrosoftDNS_WKSType MicrosoftDNS_WINSRType MicrosoftDNS_SOAType
MicrosoftDNS_MXType MicrosoftDNS_WINSType MicrosoftDNS_ATMAType
MicrosoftDNS_NSType MicrosoftDNS_NXTType MicrosoftDNS_RTType
MicrosoftDNS_CNAMEType MicrosoftDNS_TXTType MicrosoftDNS_HINFOType
MicrosoftDNS_MRType
I’ve written various scripts in the past to work with individual record types, and I’ve found that each class has slightly different syntax and requirements. This makes life awkward when you want to start automating this process, because you have to have a different script or function for each record type. I decided I wanted a universal script for creating records so that I could create multiple records at the same time from minimal information. The following script shows the function that I came up with to create A, PTR, MX, and CNAME records—these being the most common ones I have to deal with. We will be using the MicrosoftDNS_ResourceRecord class with varying inputs.
function new-dnsrecord {
param(
[string]$server,
[string]$fzone,
[string]$rzone,
[string]$computer,
[string]$address,
[string]$alias,
[string]$maildomain,
[int]$priority,
[switch]$arec,
[switch]$ptr,
[switch]$cname,
[switch]$mx
)
## check DNS server contactable
if (-not (Test-Connection -ComputerName $server)){Throw “DNS server not found”}
## split the server fqdn and address
$srvr = $server -split “\.”
$addr = $address -split “\.”$rec = [WmiClass]“\\$($srvr[0])\root\MicrosoftDNS:MicrosoftDNS_ResourceRecord”
##
## create records
##
## A
if ($arec){
$text = “$computer IN A $address”
$rec.CreateInstanceFromTextRepresentation($server, $fzone, $text)
}
## CNAME
if ($cname){
$text = “$alias IN CNAME $computer”
$rec.CreateInstanceFromTextRepresentation($server, $fzone, $text)
}
## PTR
if ($ptr){
$text = “$($addr[3]).$rzone IN PTR $computer”
$rec.CreateInstanceFromTextRepresentation($server, $rzone, $text)
}
## MX
if ($mx){
$text = “$maildomain IN MX $priority $computer”
$rec.CreateInstanceFromTextRepresentation($server, $fzone, $text)
}
}
The script was written using Windows PowerShell 2.0, but it is usable in Windows PowerShell1.0 with suitable modifications as detailed in the text. The first change is in the section where we test the connectivity to the DNS server (the Test-Connection cmdlet was introduced in version 2.0 of Windows PowerShell). We can overcome this problem by replacing that line with this one:
if ((Get-WmiObject -Query “Select * from Win32_PingStatus WHERE Address = ‘$server'”).StatusCode -ne 0){Throw “DNS server not found”}
More information about using Win32_PingStatus can be found on MSDN at http://msdn.microsoft.com/en-us/library/aa394350(VS.85).aspx#1
OK, let’s pick this function apart. I start out by defining a bunch of parameters. I haven’t used any of the advanced function capabilities here so as to ensure maximum usability of the script. A deliberate decision was made to avoid using parameter sets because this would cause additional complexity when I wanted to create multiple records. The parameters are as follows:
Parameter | Type | Meaning |
$server | String | DNS Server FQDN |
$fzone | String | Forward lookup zone |
$rzone | String | Reverse lookup zone |
$computer | String | Computer FQDN for which we are creating DNS entry |
$address | String | Address of the computer |
$alias | String | Alias of the computer |
$maildomain | String | Mail domain |
$priority | Int | Mail priority |
$arec | Switch | Create A record |
$ptr | Switch | Create PTR record |
$cname | Switch | Create Alias record |
$mx | Switch | Create MX (mail server) record |
I haven’t defined any defaults for the parameters. After the parameter definitions, you can check whether the DNS server is contactable as mentioned earlier. It is possible to test if the DNS service was actually running by using one or the other of these Get commands:
Get-Service (Windows PowerShell 2.0 has a computername parameter)Get-Service -Name DNS
WMI (computername parameter in Windows PowerShell versions 2.0 and 1.0)
Get-WmiObject -Class Win32_Service -Filter “Name = ‘DNS'”
The next task is to split the server and address into their separate parts. They both have a period (“.”) as the separator. Using the –split operator, you need to escape the dot using the back slash (“\”) character. An alternative, which will work in PowerShell 1.0 as well, is to use the Split() method of thestring class:
$server = “server02.manticore.org”
$address = “10.10.54.27”
$srvr = $server.Split(“.”)
$addr = $address.Split(“.”)
In this case, you don’t need the escape character.
The final preparatory step is to create an instance of the MicrosoftDNS_ResourceRecord class using the [wmiclass] type accelerator. A type accelerator is used as a shortcut to a .NET Framework class. In this case, we create an instance of the System.Management.ManagementClass. In other words, you are creating a WMI class. When you use Get-WmiObject, you are getting an instance of an existing class, and Windows PowerShell returns an object from the System.Management.ManagementObject class:
$rec = [WmiClass]\\server02\root\MicrosoftDNS:MicrosoftDNS_ResourceRecord$rec | gm
Using gm (an alias for Get-Member), we can view the class of object we have created:
TypeName: System.Management.ManagementClass#ROOT\MicrosoftDNS\MicrosoftDNS_ResourceRecord
You can also determine the methods that are available to this class:
CreateInstanceFromTextRepresentationGetObjectByTextRepresentation
You can use CreateInstanceFromTextRepresentation, which must be one of the longest method names I’ve come across. It’s not something I want to type on a regular basis, and at moments like this, I’m extremely grateful to the inventors of cut and paste.
The last step in the script is to create the DNS records:
if ($arec){$text = “$computer IN A $address”
$rec.CreateInstanceFromTextRepresentation($server, $fzone, $text)
}
Now test to see if the switch for that record type is set (remember that switch parameters default to false so you can just ignore them if you don’t need to create a record of a particular type). If it is set, you create the appropriate text for the record and call the CreateInstanceFromTextRepresentationmethod, which takes three parameters:
- DNS server
- DNS zone
- Text representation of DNS record.
Let’s create some records. There are a number of common parameters:
- Server name
- Computer name (host which new record points to) and its address
- A zone, usually the forward lookup zone.
A record
The only additional parameter is the switch to tell the script to create an A record:
new-dnsrecord -server server02 -fzone ‘manticore.org’ `-computer ‘test27.manticore.org’ -address 10.10.54.241 -arec
PTR Record
The reverse lookup zone needs to be supplied as well as the –prt switch:
new-dnsrecord -server server02 -rzone ‘54.10.10.in-addr.arpa’ `-computer ‘test27.manticore.org’ -address 10.10.54.241 -ptr
Alias Record
This adds the -alias parameter and uses the –cname switch rather than the –arec switch that we saw with the A record:
new-dnsrecord -server server02 -fzone ‘manticore.org’ -computer ‘test27.manticore.org’ `-alias ‘mydnstest.manticore.org’ -cname
MX record
This one is a bit different in that you add the mail domain along with a priority. The priority dictates which mail server is used; the lowest priority value wins. The example is completed by using an –mx switch:
new-dnsrecord -server server02 -fzone ‘manticore.org’ -computer ‘test27.manticore.org’ `-maildomain ‘manticore.org’ -priority 10 -mx
Multiple records
You can put several of the previous examples together to use this function to create a number of records at the same time:
new-dnsrecord -server server02 -fzone ‘manticore.org’ -rzone ‘54.10.10.in-addr.arpa’ `-computer ‘test27.manticore.org’ -address 10.10.54.241 -alias ‘mydnstest.manticore.org’ `
-arec -cname -ptr
This example creates an A record, a PTR record, and an alias, all in one pass. You have to supply the reverse lookup zone, although that could be calculated from the address parameter if required, as well as the alias.
The function can be easily extended if other record types are required. If your environment has a single forward zone and a single reverse zone, it would be possible to set those values as defaults for the relevant parameters. This would save some typing and make the script easier to use.
It is also possible to use this script for the bulk creation of DNS records. Put the data in a CSV file and pipe the contents into foreach with the function call within the foreach.
As well as showing how to use the DNS WMI classes, this script has a number of useful techniques that can be used in other places.
Further information about using Windows PowerShell to administer DNS can be found in chapter 9 of PowerShell in Practice and in a recording of a PowerShell User Group meeting.
RS, that is all there is to using Windows PowerShell to work with DNS. And thank you, Richard, for writing such an informative post. Guest Blogger Week will continue tomorrow when we will talk about SharePoint with Josh Gavant as our guest.
We would love for you to follow us on Twitter and Facebook. If you have any questions, send email to us at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
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