This is how to quickly check an xml file for specific content:
[xml]$a = get-content D:\Path\To\File\DailyPaper.xml
$a.SelectNodes(“//Language[@iso=’de’]/Byline”)
Random outpourings of a software developer
This is how to quickly check an xml file for specific content:
[xml]$a = get-content D:\Path\To\File\DailyPaper.xml
$a.SelectNodes(“//Language[@iso=’de’]/Byline”)
From:
mkdir "~\Desktop\AzureFriday" | |
cd "~\Desktop\AzureFriday" | |
[Environment]::CurrentDirectory=(Get-Location –PSProvider FileSystem).ProviderPath | |
$a = ([xml](new-object net.webclient).downloadstring("http://channel9.msdn.com/Shows/Azure-Friday/feed/mp4high")) | |
$a.rss.channel.item | foreach{ | |
$url = New-Object System.Uri($_.enclosure.url) | |
$file = $url.Segments[-1] | |
"Downloading: " + $file | |
if (!(test-path $file)) | |
{ | |
(New-Object System.Net.WebClient).DownloadFile($url, $file) | |
} | |
} |
mkdir “~\Desktop\AzureFriday”cd “~\Desktop\AzureFriday”[Environment]::CurrentDirectory=(Get-Location –PSProvider FileSystem).ProviderPath$a = ([xml](new-object net.webclient).downloadstring(“http://channel9.msdn.com/Shows/Azure-Friday/feed/mp4high”))$a.rss.channel.item | foreach{$url = New-Object System.Uri($_.enclosure.url)$file = $url.Segments[–1]“Downloading: “ + $fileif (!(test-path $file)){(New-Object System.Net.WebClient).DownloadFile($url, $file)}}
This is the first in a series of articles that I am going to write about an introduction to powershell.
However to start with I’ll give a useful option for the Powershell Integrated Scripting Environment (ISE – pronounced ICE).
$psISE.Options.FontSize = 20
This allows the editor to be seen in a presentation room.
This is a good example of powershell being embedded in another application.
Now the question is how did I find out about this property?
First I started up the ISE
Then I wanted to find out what variables existed.
That required querying the variables virtual drive:
However I can’t remember the name of this drive.
So the starting point was:
get-psdrive
This returned a list that looks like:
Name | Provider | Root |
---|---|---|
Alias | Microsoft.PowerShell.Core\Alias | |
C | Microsoft.PowerShell.Core\FileSystem | C:\ |
Cert | Microsoft.PowerShell.Security\Certificate | \ |
D | Microsoft.PowerShell.Core\FileSystem | D:\ |
E | Microsoft.PowerShell.Core\FileSystem | E:\ |
Env | Microsoft.PowerShell.Core\Environment | |
F | Microsoft.PowerShell.Core\FileSystem | F:\ |
Function | Microsoft.PowerShell.Core\Function | |
HKCU | Microsoft.PowerShell.Core\Registry | HKEY_CURRENT_USER |
HKLM | Microsoft.PowerShell.Core\Registry | HKEY_LOCAL_MACHINE |
Variable | Microsoft.PowerShell.Core\Variable | |
WSMan | Microsoft.WSMan.Management\WSMan |
From this I was able to identify the Variable PSDrive.
I was then able to change directory to the variable drive and then list the contents
cd variable:
dir
This showed the following:
Name | Value |
---|---|
$ | dir |
? | True |
^ | dir |
args | System.Object[] |
ConfirmPreference | High |
ConsoleFileName | |
DebugPreference | SilentlyContinue |
Error | System.Collections.ArrayList |
ErrorActionPreference | Continue |
ErrorView | NormalView |
ExecutionContext | System.Management.Automation.EngineIntrinsics |
false | False |
FormatEnumerationLimit | 4 |
HOME | C:\Users\Chris |
Host | System.Management.Automation.Internal.Host.InternalHost |
input | System.Collections.ArrayList+ArrayListEnumeratorSimple |
MaximumAliasCount | 4096 |
MaximumDriveCount | 4096 |
MaximumErrorCount | 256 |
MaximumFunctionCount | 4096 |
MaximumHistoryCount | 4096 |
MaximumVariableCount | 4096 |
my7digitalKey | 7dvtxrfd7pm5 |
my7digitalsecret | gek57mdmmqvk85cn |
MyInvocation | System.Management.Automation.InvocationInfo |
NestedPromptLevel | 0 |
null | |
OutputEncoding | System.Text.SBCSCodePageEncoding |
PID | 26208 |
profile | C:\Users\Chris\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile. ps1 |
ProgressPreference | Continue |
PSBoundParameters | System.Management.Automation.PSBoundParametersDictionary |
PSCommandPath | |
PSCulture | en-GB |
PSDefaultParameterValues | System.Management.Automation.DefaultParameterDictionary |
PSEmailServer | |
PSHOME | C:\Windows\System32\WindowsPowerShell\v1.0 |
psISE | Microsoft.PowerShell.Host.ISE.ObjectModelRoot |
PSScriptRoot | |
PSSessionApplicationName | wsman |
PSSessionConfigurationName | http://schemas.microsoft.com/powershell/Microsoft.PowerS hell |
PSSessionOption | System.Management.Automation.Remoting.PSSessionOption |
PSUICulture | en-US |
psUnsupportedConsoleApplications | Microsoft.PowerShell.Host.ISE.UICollection`1[Syste m.String] |
PSVersionTable | System.Management.Automation.PSVersionHashTable |
PWD | Variable:\ |
ShellId | Microsoft.PowerShell |
StackTrace | at System.Management.Automation.Internal.PipelineProcessor.Synchronou sExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumerate) at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, Co mmandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] c ommandRedirections, FunctionContext funcContext) at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) |
true | True |
VerbosePreference | SilentlyContinue |
WarningPreference | Continue |
WhatIfPreference | False |
From this the psISE looks to be the thing that I am looking for.
The next step is to inspect the object to see what I can find to use.
$psISE | gm
Name | MemberType | Definition |
---|---|---|
Equals | Method | bool Equals(System.Object obj) |
GetHashCode | Method | int GetHashCode() |
GetType | Method | type GetType() |
ToString | Method | string ToString() |
CurrentFile | Property | Microsoft.PowerShell.Host.ISE.ISEFile CurrentFile {get ;} |
CurrentPowerShellTab | Property | Microsoft.PowerShell.Host.ISE.PowerShellTab C urrentPowerShellTab {get;} |
CurrentVisibleHorizontalTool | Property | Microsoft.PowerShell.Host.ISE.ISEAddO nTool CurrentVisibleHorizontalTool {get;} |
CurrentVisibleVerticalTool | Property | Microsoft.PowerShell.Host.ISE.ISEAddOnT ool CurrentVisibleVerticalTool {get;} |
Options | Property | Microsoft.PowerShell.Host.ISE.ISEOptions Options {get;} |
PowerShellTabs | Property | Microsoft.PowerShell.Host.ISE.PowerShellTabCollecti on PowerShellTabs {get;} |
Options look promising.
$psISE.Options | gm
Name | MemberType | Definition |
---|---|---|
PropertyChanged | Event | System.ComponentModel.PropertyChangedEventHandler PropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs) |
Equals | Method | bool Equals(System.Object obj) |
GetHashCode | Method | int GetHashCode() |
GetType | Method | type GetType() |
RestoreDefaultConsoleTokenColors | Method | void RestoreDefaultConsoleTokenColors() |
RestoreDefaults | Method | void RestoreDefaults() |
RestoreDefaultTokenColors | Method | void RestoreDefaultTokenColors() |
RestoreDefaultXmlTokenColors | Method | void RestoreDefaultXmlTokenColors() |
ToString | Method | string ToString() |
AutoSaveMinuteInterval | Property | int16 AutoSaveMinuteInterval {get;set;} |
ConsolePaneBackgroundColor | Property | System.Windows.Media.Color ConsolePaneBackgroundColor {get;set;} |
ConsolePaneForegroundColor | Property | System.Windows.Media.Color ConsolePaneForegroundColor {get;set;} |
ConsolePaneTextBackgroundColor | Property | System.Windows.Media.Color ConsolePaneTextBackgroundColor {get;set;} |
ConsoleTokenColors | Property | System.Collections.Generic.IDictionary[System.Management.Automation.PSTokenType,System.Windows.Media.Color] ConsoleTokenColors {get;} |
DebugBackgroundColor | Property | System.Windows.Media.Color DebugBackgroundColor {get;set;} |
DebugForegroundColor | Property | System.Windows.Media.Color DebugForegroundColor {get;set;} |
DefaultOptions | Property | Microsoft.PowerShell.Host.ISE.ISEOptions DefaultOptions {get;} |
ErrorBackgroundColor | Property | System.Windows.Media.Color ErrorBackgroundColor {get;set;} |
ErrorForegroundColor | Property | System.Windows.Media.Color ErrorForegroundColor {get;set;} |
FontName | Property | string FontName {get;set;} |
FontSize | Property | int FontSize {get;set;} |
IntellisenseTimeoutInSeconds | Property | int IntellisenseTimeoutInSeconds {get;set;} |
MruCount | Property | int MruCount {get;set;} |
ScriptPaneBackgroundColor | Property | System.Windows.Media.Color ScriptPaneBackgroundColor {get;set;} |
ScriptPaneForegroundColor | Property | System.Windows.Media.Color ScriptPaneForegroundColor {get;set;} |
SelectedScriptPaneState | Property | Microsoft.PowerShell.Host.ISE.SelectedScriptPaneState SelectedScriptPaneState {get;set;} |
ShowDefaultSnippets | Property | bool ShowDefaultSnippets {get;set;} |
ShowIntellisenseInConsolePane | Property | bool ShowIntellisenseInConsolePane {get;set;} |
ShowIntellisenseInScriptPane | Property | bool ShowIntellisenseInScriptPane {get;set;} |
ShowLineNumbers | Property | bool ShowLineNumbers {get;set;} |
ShowOutlining | Property | bool ShowOutlining {get;set;} |
ShowToolBar | Property | bool ShowToolBar {get;set;} |
ShowWarningBeforeSavingOnRun | Property | bool ShowWarningBeforeSavingOnRun {get;set;} |
ShowWarningForDuplicateFiles | Property | bool ShowWarningForDuplicateFiles {get;set;} |
TokenColors | Property | System.Collections.Generic.IDictionary[System.Management.Automation.PSTokenType,System.Windows.Media.Color] TokenColors {get;} |
UseEnterToSelectInConsolePaneIntellisense | Property | bool UseEnterToSelectInConsolePaneIntellisense {get;set;} |
UseEnterToSelectInScriptPaneIntellisense | Property | bool UseEnterToSelectInScriptPaneIntellisense {get;set;} |
UseLocalHelp | Property | bool UseLocalHelp {get;set;} |
VerboseBackgroundColor | Property | System.Windows.Media.Color VerboseBackgroundColor {get;set;} |
VerboseForegroundColor | Property | System.Windows.Media.Color VerboseForegroundColor {get;set;} |
WarningBackgroundColor | Property | System.Windows.Media.Color WarningBackgroundColor {get;set;} |
WarningForegroundColor | Property | System.Windows.Media.Color WarningForegroundColor {get;set;} |
XmlTokenColors | Property | System.Collections.Generic.IDictionary[Microsoft.PowerShell.Host.ISE.PSXmlTokenType,System.Windows.Media.Color] XmlTokenColors {get;} |
Zoom | Property | double Zoom {get;set;} |
And here we find fontsize
This gives the command that I demonstrated at the start.
The following commands were used in the construction of this article:
get-psdrive | select Name,Provider,Root | ConvertTo-Html -Fragment
dir | select Name,Value | ConvertTo-Html -Fragment
$psISE.Options | gm | select Name, MemberType, Definition | convertto-html -Fragment | clip
This is how to get a list of wmi providers:
Get-WmiObject -Namespace “root/cimv2” -List
These can be queried as follows:
Get-WmiObject -query “select * from win32_processor”
This is effectively granting you sql style queries against features on your machine.
The following shows how to query the 7digital api from powershell.
[xml]$data = (invoke-webrequest -uri http://api.7digital.com/1.2/release/details?releaseid=951886`&country=gb`&oauth_consumer_key=$my7digitalKey | select -ExpandProperty Content)
This provides an in memory object that you can walk the tree.
This is how I investiagate most xml/json feeds.
I am not publishing my key so get your own and set it in your profile:
ii $profile
This is a great article on how to include an event id in the WADLogs table.
The trick is to use a custom trace source as follows
TraceSource ts = new TraceSource(“My Custom Event Source Name”, SourceLevels.Information);
ts.TraceEvent(TraceEventType.Warning, 102, “This is a test log using trace source”);
and then to configure the azure listener to get this into the appropriate log file:
This gets added to the appropriate system.diagonstics section:
<sources>
<source name=”MyTraceSource” switchName=”sourceSwitch” switchType=”System.Diagnostics.SourceSwitch”>
<listeners>
<add type=”Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ name=”AzureDiagnostics”>
<filter type=”” />
</add>
</listeners>
</source>
</sources>
<switches>
<add name=”sourceSwitch” value=”Warning”/>
</switches>
The big advantage of this is that you get to assign your own error codes to the messages.
Practically all of the default Azure stuff will be coded as zero.
This means that you can assign defined ranges of code to indicate that these are for example:
Timing Messages.
Notification for information.
Notification for action.
These make analysing the logs much easier.
Btw are you aware of the WADLogs powershell trick:
“0” + [DateTime]::UtcNow.AddHours(-1).Ticks
This gives a partition key of an hour ago.
This is great for getting extracted logs.
Extract the logs into csv and use the powershell import-csv command.
This is an amazingly fast way of analysing logs.
https://github.com/chriseyre2000/Powershell/tree/master/Generator
This is a universal scaffolder.
It can be used to generate anything and is highly scriptable.
#Multiline powershell regex with variable extraction.
$data = @”
first
second
third
“@
$data | Select-string -Pattern “(?s)first(?.*)third” | select -ExpandProperty Matches | foreach { $_.Groups[“name”].Value}