Powershell pattern matching to check if a string is hex

Hexadecimal-countingI’ve been playing with pattern matching in Powershell.

I was trying to use ‘-match‘ to ‘Check if the string is a hexadecimal number’ for the ‘Perl one-liners in Powershell’ page I’ve been working on.

I can’t pretend to entirely understand or explain pattern matching in Powershell, or in *nix, but this seems to work.

$X = "21e" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"

This says match the string against ‘any combination of the characters within the square brackets (i.e. the hex digits) to the same length as the original string’.

So, the square brackets contain the allowable characters.

The curly brackets give the number of characters.

I tried just doing:

$X = "21e" ; $X -match "[0123456789abcde]{$X.length}"

…but this didn’t seem to work.

Tests

I tried the following strings – they all seemed to come up with the right answer:

$ $X = "21e" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
True
$ $X = "21edjhsd" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
False
$ $X = "21e34782348237847832748723" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
True
$ $X = "21e34782348237847832748723f" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
False
$ $X = "21e34782348237847832748723acbdaaa" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
True
$ $X = " " ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
False

….although I’m not sure whether this is right or wrong:

$ $X = "" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
True

Picture: By mate2code (Own work) [Public domain], via Wikimedia Commons

Screenshot from 2014-02-20 22:13:47

Idiot’s guide to github

Screenshot from 2014-02-20 22:13:47I’ve been finding it difficult to get my head around github.

As is often the case in the end I found it easiest to do so through the command line.

I’d already created a repository which holds my firefox ‘New tab’ and home page.

To amend it I did the following. I think.

Set up my githubcredentials:

git config --global user.name mattypenny
git config --global user.email mattypenny@gmail.com
git config --global credential.helper 'cache --timeout=36000'

Clone the repository locally

git clone https://github.com/mattypenny/start_page.git

This creates a folder with all the repository files in it locally

cd start_page

Then I made all my changes to the start page.

Then I did a local commit:

git commit -m 'New pics and added in all the picture credits'

This shows that git was pointing to the github repository as ‘origin’. This seems to have been retained from the clone command.

$ git remote -v
origin	https://github.com/mattypenny/start_page.git (fetch)
origin	https://github.com/mattypenny/start_page.git (push)

Then I pushed it all back to github

$ git push origin master
Username for 'https://github.com': mattypenny
Password for 'https://mattypenny@github.com': 
Counting objects: 17, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (11/11), 1.05 MiB | 172 KiB/s, done.
Total 11 (delta 1), reused 0 (delta 0)
To https://github.com/mattypenny/start_page.git
   9f6e3d5..40431e1  master -> master

SSIS: Invalid access to memory location

Problem came up trying to connect to a remote Oracle source:

Started:  12:03:03
Error: 2013-10-09 12:03:03.84
   Code: 0xC0202009
   Source: <removed>
   Description: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x800703E6.
An OLE DB record is available.  Source: "Microsoft OLE DB Service Components"  Hresult: 0x800703E6  Description: "Invalid access to memory location.".
End Error
Error: 2013-10-09 12:03:03.84
   Code: 0xC020801C
   Source: Copy Data
   Description: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "xxx" failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.
End Error
Error: 2013-10-09 12:03:03.84
   Code: 0xC0047017
   Source: xxxx
   Description: component "xxx" (1) failed validation and returned error code 0xC020801C.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).

Fix was to go into job step properties, select the ‘Execution options’ tab and click on ‘Use 32-bit runtime’.

I’m wondering whether we had an Oracle 32-bit install, or a 32-bit install that wasn’t entirely removed

get-parameter – get a list of PowerShell standard parameter names

Windows_PowerShell_iconThis is a work in progress – I’ll turn it into a function at some stage.

Anyway, it’s a common and a good practice to use Powershell’s standard verbs when naming your functions. You can retrieve these by typing

get-verb

at the command line.

I think it’s good to also use Powershell’s standard parameter names when you’re naming your parameters.

I couldn’t find an easy way of retrieving the list of parameteres but this approximates it:

$PARAMETERS = get-command | where-object {$_.CommandType -eq "Cmdlet" } | select Parameters
$PARAMETER_KEYS = foreach ($P in $PARAMETERS)
{
  foreach ($K in $($P.Parameters | select keys))
  {
    $K.Keys
  }
}
$PARAMETER_KEYS | sort-object -unique

The result, on Powershell 2.0 with sqlps loaded, is:

AbortOnError
AclObject
Action
Activity
Add
AdHocPolicyEvaluationMode
Adjust
After
Alias
AliasesToExport
All
AllMatches
AllowClobber
AllowRedirection
Amended
Any
Append
AppendPath
ApplicationArguments
ApplicationBase
ApplicationName
ArgumentList
Arguments
As
AsBaseObject
AsCustomObject
AsHashTable
AsJob
AsPlainText
AsSecureString
Assembly
AssemblyName
Associations
AsString
Attachments
Audit
Authentication
Author
Authority
AutoSize
Average
BackgroundColor
BaseDirectory
BasePropertiesOnly
Bcc
Before
Begin
BinaryPathName
BindingVariable
Body
BodyAsHtml
Breakpoint
BufferSize
CancelTimeout
CaseSensitive
Category
CategoryActivity
CategoryReason
CategoryResourceFile
CategoryTargetName
CategoryTargetType
Cc
Certificate
CertificateThumbprint
Character
ChildPath
Circular
Class
ClrVersion
Cmdlet
CmdletsToExport
CodeDomProvider
Column
Command
CommandLine
CommandName
CommandType
ComObject
CompanyName
CompilerParameters
Completed
Component
ComputerName
ConfigurationName
ConfigurationTypeName
Confirm
ConnectionTimeout
ConnectionUri
Container
Content
Context
Continuous
Copyright
Count
Counter
Credential
CssUri
Culture
CurrentOperation
Database
Date
Day
Days
Debug
Debugger
DedicatedAdministratorConnection
Definition
Delay
DelegateComputer
Delimiter
DeliveryNotificationOption
DependentServices
DependsOn
Depth
Descending
Description
Destination
Detailed
Dialect
DifferenceObject
DirectRead
DisableCommands
DisableNameChecking
DisableVariables
DisplayError
DisplayHint
DisplayName
DomainName
DotNetFrameworkVersion
Drive
EnableAllPrivileges
Encoding
EncryptConnection
End
EndTime
EntryType
Enumerate
ErrorAction
ErrorId
ErrorLevel
ErrorRecord
ErrorVariable
EventArguments
EventId
EventIdentifier
EventName
Examples
Exception
Exclude
ExcludeDifferent
ExcludeProperty
ExecutionPolicy
Expand
ExpandProperty
Expression
FileFormat
FileList
FileName
FilePath
FileVersionInfo
Filter
FilterHashtable
FilterScript
FilterXml
FilterXPath
First
Force
ForegroundColor
Format
FormatsToProcess
FormatTypeName
Forward
Fragment
From
Full
Function
Functionality
FunctionsToExport
Global
GroupBy
Guid
HashAlgorithm
Head
Header
HideComputerName
HideTableHeaders
HostName
Hour
Hours
Id
IdleTimeout
IgnoreProviderContext
IgnoreWarnings
IgnoreWhiteSpace
Impersonation
Include
IncludeChain
IncludeEqual
IncludeScriptBlock
Independent
Index
InitializationScript
InputFile
InputObject
InstanceId
IsAbsolute
IsValid
ItemType
Job
JobName
Keep
Key
Language
Last
LastStatus
Leaf
Line
List
ListAvailable
ListenerOption
ListLog
ListProvider
ListSet
LiteralName
LiteralPath
LoadUserProfile
Locale
Location
LogName
MaxBinaryLength
MaxCharLength
MaxEvents
Maximum
MaximumReceivedDataSizePerCommand
MaximumReceivedDataSizePerCommandMB
MaximumReceivedObjectSize
MaximumReceivedObjectSizeMB
MaximumRedirection
MaximumSize
MaxSamples
MaxSize
MemberDefinition
MemberType
Message
MessageData
MessageResourceFile
Milliseconds
Minimum
Minute
Minutes
Mode
Module
ModuleInfo
ModuleList
ModuleToProcess
ModuleVersion
Month
Name
Namespace
NestedModules
Newest
NewName
NewPassword
NoClobber
NoCompression
NoElement
NoEncryption
NoMachineProfile
NoNewline
NoNewWindow
NoQualifier
NoRecurse
NoServiceRestart
NotMatch
NoTypeInformation
Noun
Object
Off
Oldest
Online
OnType
OpenTimeout
OperationTimeout
Option
OptionSet
OUPath
OutBuffer
OutputAssembly
OutputModule
OutputSqlErrors
OutputType
OutputXml
OutVariable
OverflowAction
Paging
Parameter
ParameterResourceFile
Parent
ParentId
PassThru
Password
Path
PathType
Pattern
PercentComplete
Policy
Port
PostContent
PowerShellHostName
PowerShellHostVersion
PowerShellVersion
PreContent
Prefix
PrependPath
Priority
PrivateData
Process
ProcessorArchitecture
Prompt
Property
PropertyType
ProviderName
ProxyAccessType
ProxyAuthentication
ProxyCredential
PSDrive
PSHost
PSProvider
PutType
Qualifier
Query
QueryTimeout
Quiet
RawData
ReadCount
RecommendedAction
Recurse
RedirectStandardError
RedirectStandardInput
RedirectStandardOutput
ReferencedAssemblies
ReferenceObject
Registered
Relative
Remove
RemoveFileListener
RemoveListener
Repair
Replace
RequiredAssemblies
RequiredModules
RequiredServices
Resolve
ResourceURI
RestorePoint
RestorePointType
RetentionDays
ReturnResult
ReturnType
Role
RollbackPreference
Root
RunAs32
SampleInterval
Scope
Script
ScriptBlock
ScriptsToProcess
Second
Seconds
SecondsRemaining
SecondValue
SecureKey
SecureString
SecurityDescriptorSddl
SelectorSet
Sender
Separator
Server
ServerInstance
Session
SessionOption
SetSeed
SeverityLevel
Shallow
ShowError
ShowSecurityDescriptorUI
SimpleMatch
Skip
SkipCACheck
SkipCNCheck
SkipRevocationCheck
SmtpServer
Source
SourceId
SourceIdentifier
SPNPort
SqlName
Stack
StackName
Start
StartTime
StartupScript
StartupType
State
Static
Status
Step
Stream
Strict
String
StringData
Subject
SubscriptionId
Sum
Summary
SupportedCommand
SupportEvent
SuppressProviderContextWarning
SyncWindow
Syntax
TargetExpression
TargetObject
TargetObjects
TargetServerName
ThreadApartmentState
ThreadOptions
ThrottleLimit
Timeout
TimestampServer
TimeToLive
Title
To
TotalCount
Trace
TransactedScript
Type
TypeDefinition
TypeName
TypesToProcess
UFormat
UICulture
Unique
UnSecure
Uri
Urn
UseCulture
UseDefaultCredential
UseNewEnvironment
UserName
UseSsl
UseTransaction
UseUTF16
UsingNamespace
Value
ValueOnly
ValueSet
Variable
VariablesToExport
Verb
Verbose
Version
View
Visibility
Wait
WarningAction
WarningVariable
WhatIf
Width
WindowStyle
Word
WorkGroupName
WorkingDirectory
Wrap
Xml
XPath
Year

Ubuntu netbook can’t see my nook

Ubuntu_cant_see_nookI had a problem yesterday getting my Ubuntu netbook (which is a Dell Inspiron 910 mini) to see my Nook.

After, mucking about with various unix commands, including:

mount
lsusb
dmesg | egrep -i connected
ls /dev/sd*

It turns out that Ubuntu couldn’t see the Nook, because the power was too low.

It *seems* that there was enough power to power the Nook on, but not enough for it to make itself visible to the netbook.

For future reference, the Nook shows in the above commands as follows:

mount

/dev/sdc on /media/matt/6663-3466 type vfat (rw,nosuid,nodev,uid=1000,gid=1000,shortname=mixed,dmask=0077,utf8=1,showexec,flush,uhelper=udisks2)
/dev/sdb on /media/matt/NOOK type vfat (rw,nosuid,nodev,uid=1000,gid=1000,shortname=mixed,dmask=0077,utf8=1,showexec,flush,uhelper=udisks2) 


lsusb

lsusb
Bus 001 Device 014: ID 2080:0003 Barnes & Noble NOOK Simple Touch

dmesg | egrep -i connected

nothing

ls /dev/sd*

diff with without
74,75d73
< sdb
< sdc
77,78d74
< sg1
< sg2
193d188
< vcs63
201d195
< vcsa63

Access is denied. [0x80070005] When Changing Sql Server Agent Login

Trying to change the sql server agent to run as a non-admin user, I couldn’t get Sql Server Agent To work without giving it administrator privileges. I got:

---------------------------
WMI Provider Error
---------------------------
Access is denied. [0x80070005]
---------------------------
OK   
---------------------------

You have to grant two privileges – both the Agent User and the MSSQL user.

  • SQLServerSQLAgentUser$bigserver$inst01
  • SQLServerMSSQLUser$bigserver$inst01

Mis-spelling in Powershell

ErrorThis was spectacularly incompetent even by my high standards of incompetence.

It illustrates that if you spell the name of a column incorrectly in Powershell, you don’t get an error, you just get a null column

get-wmiobject -class win32_operatingsystem -computer rdm016 | 
select __Server, ServicePackMajorVerstion

And got:

__SERVER                             ServicePackMajorVerstion 
--------                             ------------------------
RDM016

I thought that no service packs had been applied. This, as more attentive readers will have spotted, was not the case. The null under ServicePackMajorVerstion is because you don’t spell ‘version’ with a ‘t’. Two learnings from this:

  • one should test one’s code
  • if you put something invalid in a ‘select’ list in Powershell it won’t necessarily error

4 ways of breaking comment-based help in Powershell

Green ManA quick note on the different ways I’ve found of breaking the comment-based help in Powershell. I’ve only started playing with it today. It’s a great feature, but it does perhaps seem a little fussy. I’ve not verified all of these – I’ll do so when time allows

Leave the ‘.’ off of a label

If I leave out the full-stop on one of the labels:

SYNOPSIS
Lists services on specified server which are set as autostart but are currently stopped

.DESCRIPTION
Uses wmi to get services into�

It breaks the whole of the help:

PS C:\> help sstop

show-stoppedservices [[-MyServer]]

Have a function with the same name as a script

If my function name is kept in a ps1 file with the same name as the function, then the help subsytem just shows the different items. If I rename the .ps1 file as follows:

move function-show-stoppedservices.ps1 show-stoppedservices.ps1

And I try to get help on the function (using the full function name – the alias would be OK):  

PS C:\> help show-stoppedservices 
Name                     Category   Synopsis 
----                     --------   -------- 
show-stoppedservices     Function   Lists services on specified serv... show-stoppedservices.ps1 Extern...  show-stoppedservices.ps1 ...

Don’t name the parameter correctly

If you mis-spell the name of the parameter in the Help text, then you’ll lose any description that you add in, obviously enough:

.PARAMETER NotMyServer
Specify the remote server. If null tells you about wherever you are 
running

Code:
Param ( [String] $MyServer = "." ) 

Powershell will still give you the definition of the parameter but you lose the help text.

help show-stoppedservices -parameter MyServer

type                       name                       parameterValue
----                       ----                       --------------
@{name=String}             MyServer                   String 

Putting this right:

.PARAMETER MyServer 

Allows Powershell to use your help:

help show-stoppedservices -parameter MyServer

type                name                parameterValue      description
----                ----                --------------      -----------
@{name=String}      MyServer            String              {@{Text=Specify ...

Not (re-) sourcing the function! :)

To be completed

Using the REMARKS section

It may be I just got this wrong, but I thought I’d try using the ‘remarks’
section to keep track of what needs to be done to the script.

This seemed to naus it all up:

.REMARKS
Todo: Check the serverinstance exists and is running
Todo: Check the database exists

….although perhaps it was something else.

Reporting mp3 tags in Powershell

I’m slowly getting to grips with Powershell.

# ----------------------------------------------------------------- 
# Script - Catalog-MP3s.ps1 # 
# Gets mp3 tags from the mp3 file. 
# -----------------------------------------------------------------  
# Parameter is either a directory or an individual mp3 Param ( $P_DIR_OR_MP3 )  # -------------------------- 
# Function: get-mp3info 
# The function gets the tags  
# for the specified mp3 
# --------------------------  
Function get-mp3info ($P_MP3) 
{     
     # Get the tages into a variable
     $TAGS = [TagLib.File]::Create("$P_MP3")
     $TAGS_OBJECT = @{Filename = $TAGS.Name;
     
     Bitrate = $TAGS.Properties.AudioBitRate;
     Artist = $TAGS.tag.FirstArtist;
     Title =  $TAGS.tag.Title;
     Genre = $TAGS.tag.FirstGenre;
     LP = $TAGS.tag.Album}      

     # Output as an object
     New-Object PSObject -Property $TAGS_OBJECT 
}   

     # -------------------------- 
     # Main body 
     # --------------------------  
     # Store the location of the taglib dll 
     $TAGLIB="C:\Users\Matt\Downloads\taglib-sharp-2.1.0.0-windows\taglib-sharp-2.1.0.0-windows\Libraries\taglib-sharp.dll"  

     # Load the DLL 
     [System.Reflection.Assembly]::LoadFile($Taglib)   

     # Get a list of all the MP3s under the specified folder 
     # - exclude anything that's not an mp3 
     # - Fullname contains the full path and filename 
     $MP3_LIST = gci -recurse Filesystem::$DIR_OR_MP3 |
                     where {$_.Extension -eq '.mp3'} |
                     select FullName  

     # Walk through the list, and output the tags 
     foreach ($MP3 in $MP3_LIST) 
     {    
          get-mp3info $MP3.Fullname  
     }    

PowerShell – Automatically organizing your mp3-collection – Speaking of which… – Site Home – MSDN Blogs
Scripting Mp3 Tags through PowerShell | PowerShell.nu