Monthly Archive

Modifying text

I needed to modify some text somewhere in a file. The file looks like this

##  start file
This is some text.

 

I want to change something.

 

But not this.
##  end file

 

I was playing around with various options.  The simplest I found was this:

£> $txt = Get-Content .\test.txt
£> $txt = $txt.Replace("I want", "I need")
£> Set-Content -Value $txt -Path C:\Test\test.txt
£> Get-Content .\test.txt
##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

You could simplify to

£> $txt = (Get-Content .\test.txt).Replace("I want", "I need")
£> Set-Content -Value $txt -Path C:\Test\test.txt -PassThru

##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

The passthru parameter displays the file contents you’ve set.

 

Or if you are a fan of convoluted one liners

£> Set-Content -Value ((Get-Content .\test.txt).Replace("I want", "I need")) -Path C:\Test\test.txt -PassThru
##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

If you take this approach just make sure your text is uniquely identified otherwise you may change more than you thought.

Testing for a hotfix

KB3000850 – the November roll up for Windows 2012 R2 contains some very useful updates.

I’ve installed it on some machines in my lab but not all. The update is huge so I’m installing it manually rather than through WSUS.

 

I need to test a remote machine to determine if the update  is installed.

If it is installed you get a this back

£> Get-HotFix -Id KB3000850 -ComputerName w12r2dsc

Source        Description             HotFixID         InstalledBy      
------          -----------                --------          -----------      
W12R2DSC      Update           KB3000850      MANTICORE\Richard

 

But if its not installed you get this

£> Get-HotFix -Id KB3000850 -ComputerName w12r2od01
Get-HotFix : Cannot find the requested hotfix on the 'w12r2od01' computer. Verify the input and run the command again.
At line:1 char:1
+ Get-HotFix -Id KB3000850 -ComputerName w12r2od01
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-HotFix], ArgumentException
    + FullyQualifiedErrorId : GetHotFixNoEntriesFound,Microsoft.PowerShell.Commands.GetHotFixCommand

Get-Hotfix actually uses the Win32_QuickFixEngineering CIM class so you need to have DCOM open on the remote system otherwise you get a

Get-HotFix : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

error.

 

You need to wrap the call to Get-Hotfix in a try catch. You only need to know if the update is installed so creating a specialised output object manages that for you

Get-VM |
where State -eq 'Running' |
foreach {
 
$props = @{
   Machine = $($psitem.Name)
   Present = $false
}
 
try {
   $hf = Get-HotFix -Id KB3000850 -ComputerName $psitem.Name -ErrorAction Stop
   $props.Present = $true
}
catch {
   $props.Present = $false
}
 
New-Object -TypeName PSObject -Property $props
 
}

 

Substitute any other method of getting a list of computer names, for my call to Get-VM, to match your environment.

Variable select

I was working on some code that  accesses a SQL database this afternoon. I only needed to pull back a single column from a single row but which column to pull back is variable depending on other data.

That’s OK

$query = “SELECT $colname FROM tablename WHERE x = ‘y’”

Invoke-SQLcmd –server <server> –database <database> –query $query

 

Now the problem hit me as I need to get the actual value from the object that invoke-sqlcmd returns

I normally do this:

Invoke-SQLcmd –server <server> –database <database> –query $query | select –expandproperty <columnname>

 

And then it dawned on me that I have the column name in $colname so this works

Invoke-SQLcmd –server <server> –database <database> –query $query | select –expandproperty $colname

 

I got so used to explicitly stating the properties I need that I forgot you could use a variable.  If you want an example to try on any system

Get-Service | select -First 1 | select -ExpandProperty $p1

 

or you could try

$p1 = 'Status'
Get-Service | select Name, $p1

 

and change to

$p1 = 'DisplayName'
Get-Service | select Name, $p1

 

Not something you want to do every day but a useful trick when you need it

WMI errors

Most PowerShell users will have done something like this:

£> Get-WmiObject -ClassName Win32_ComputerSystem
Domain              : WORKGROUP
Manufacturer        : Microsoft Corporation
Model               : Surface Pro 2
Name                : RSSURFACEPRO2
PrimaryOwnerName    :
TotalPhysicalMemory : 8506093568

 

Or you can use a computername to access a remote system

£> $computer = $env:COMPUTERNAME
£> Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer

Domain              : WORKGROUP
Manufacturer        : Microsoft Corporation
Model               : Surface Pro 2
Name                : RSSURFACEPRO2
PrimaryOwnerName    :
TotalPhysicalMemory : 8506093568

 

But if you try to access a remote machine that doesn’t exist

£> $computer = 'WillNotBeFound'
£> Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

You’ve heard of try – catch  so you do something like this

$computer = 'WillNotBeFound'

try {
  Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop
}
catch {
  Write-Warning "An error occurred"
}

 

OR your catch may do something to record the error.

$computer = 'WillNotBeFound'

try {
  Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop
}
catch {
  Write-Warning "An error occurred for machine: $computer"
}

 

If you make the warning message specific

$computer = 'WillNotBeFound'

try {
  Get-WmiObject -ClassName Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop
}
catch {
  Write-Warning "The RPC server is unavailable for machine: $computer"
}

 

What happens if you have a different error. Lets say you copy the code and change the class. You test the code

$computer = $env:COMPUTERNAME

try {
  Get-WmiObject -ClassName Win32_LogicalDsik -ComputerName $computer -ErrorAction Stop
}
catch {
  Write-Warning "The RPC server is unavailable for machine: $computer"
}

 

And get a message

WARNING: The RPC server is unavailable for machine: RSSURFACEPRO2

 

What you should see is

Get-WmiObject : Invalid class "Win32_LogicalDsik"
At line:1 char:1
+ Get-WmiObject -ClassName Win32_LogicalDsik -ComputerName $computer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

Because the class is mistyped.

 

You could try and create a number of catch statements – one for each error type.  Good luck with that. Its a lot of work.  A better approach, in my mind is to extract the error information you need

$computer = $env:COMPUTERNAME

try {
  Get-WmiObject -ClassName Win32_LogicalDsik -ComputerName $computer -ErrorAction Stop
}
catch {
$errordata = @"
  Computer = $computer
  Exception = $($error[0].Exception)
  ErrorId = $($error[0].FullyQualifiedErrorId)
"@
 
  Write-Warning $errordata
}

 

If you look in the PowerShell automatic variable $error – you’ll find its a collection of error messages.  $error[0] contains the last error.  So now you get

£> $computer = $env:COMPUTERNAME

try {
  Get-WmiObject -ClassName Win32_LogicalDsik -ComputerName $computer -ErrorAction Stop
}
catch {
$errordata = @"
  Computer = $computer
  Exception = $($error[0].Exception)
  ErrorId = $($error[0].FullyQualifiedErrorId)
"@
 
  Write-Warning $errordata
}

WARNING:   Computer = RSSURFACEPRO2
  Exception = System.Management.ManagementException: Invalid class "Win32_LogicalDsik"
  ErrorId = GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

For a set of computers

$computers = $env:COMPUTERNAME, 'WillNotBefound'

foreach ($computer in $computers){
try {
  Get-WmiObject -ClassName Win32_computersystem -ComputerName $computer -ErrorAction Stop
}
catch {
$errordata = @"
  Computer = $computer
  Exception = $($error[0].Exception)
  ErrorId = $($error[0].FullyQualifiedErrorId)
"@
 
  Write-Warning $errordata
}
}

 

You get the data where you can contact the machine – otherwise a warning message that the server is unavailable.  Rather than outputting a warning message create an object from the error data and save to a CSV file

Unravelling lists of distinguished names

There are a number of AD properties such as MemberOf and directrports that consist of a collection of distinguisednames.  Sometimes you need the  name  of the object rather than the distinguished name:

function getname {
[CmdletBinding()]
param (
[string]$dn
)

$name = Get-ADObject $dn | select -ExpandProperty Name

return $name
}

Get-ADUser -Filter * -SearchBase "OU=Testing,DC=Manticore,DC=org" -Properties MemberOf |
foreach {
 
$name = $psitem.Name

foreach ($member in $psitem.MemberOf) {
   $props = [ordered]@{
     User = $name
     Group = getname -dn $member
   }

   New-Object -Property $props -TypeName PSObject

}
}

 

In this example I’m looking at the MemberOf property.  Pull back the set of users and foreach look at each member in the MemberOf list. I pass that to a function that returns the name – I can reuse the function in other scripts.

 

Don’t make the mistake of looking at group membership in this way though. You can get the names of group members much more simply

Get-ADGroupMember -Identity tg1 | select name

Filtering on if an AD property exists

There are times when you want to filter the results based on whether a user has an AD property set.  You could do this:

Get-ADUser -Filter * -Properties Title | Where Title  | select Name, Title

 

However, that involves pulling back all of the users and then filtering. Not very efficient especially across the network in a big domain.

A better solution would be to use an LDAP filter

Get-ADUser -LDAPFilter "(Title=*)" -Properties Title  | select Name, Title

 

Get-ADUser does the checking to see if the user has a title set so only those objects with that property are retrieved. If you want to see the value of the property you need to include it by using the –Properties parameter.

Awkward file and folder names

Spent some time today dealing with a situation where there were special characters – namely [ ] in folder a file names

£> Get-ChildItem -Path C:\Test

    Directory: C:\Test

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        21/01/2015     17:58            Awkward [One]
d----        21/01/2015     17:59            Simple One

 

Each folder has 3 files:

File 1.txt
File 2.txt
File 3.txt

 

Get-ChildItem -Path 'C:\Test\Simple One'

will work and show you the contents. When I’m typing paths like this I let Tab completion do the work. Type c:\test\ and use the Tab key to cycle round the available folders.

 

This gives

£> Get-ChildItem -Path 'C:\Test\Awkward `[One`]'
Get-ChildItem : Cannot find path 'C:\Test\Awkward `[One`]' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path 'C:\Test\Awkward `[One`]'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Test\Awkward `[One`]:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

 

Unfortunately, the construct produced by Tab completion doesn’t work.  You need to double up on the back ticks so that it functions as an escape character.

Get-ChildItem -Path 'C:\Test\Awkward ``[One``]'

 

But that only shows you the folder not the contents.

Get-ChildItem -Path 'C:\Test\Awkward ``[One``]\*'

OR

Get-ChildItem -Path 'C:\Test\Awkward ``[One``]' -Include *

 

Will show you the contents of the folder.

 

But bizarrely

Get-Content -Path 'C:\Test\Awkward `[One`]\File 1.txt'

Works. As does

Copy-Item -Path 'C:\Test\Awkward `[One`]\File 1.txt' -Destination c:\test2

 

By using back ticks and quotes you can get round most problems like this. Other characters that cause similar problems are commas and quote marks.

Best advice of all – don’t use those awkward characters in your file names if you can possibly avoid it.

PowerShell Summit NA 2015 Agenda changes

We’ve had to make some minor changes to the Summit agenda – the revised schedule is shown on the event web site - http://eventmgr.azurewebsites.net/event/home/PSNA15

PowerShell Heroes 2015

Powershell.org has announced the 2015 list of PowerShell Heroes- http://powershell.org/wp/2015/01/17/announcing-our-2015-powershell-heroes/

 

These are people who have made an outstanding contribution to the PowerShell community but have not been recognised in other ways (such as an MVP award)

 

Please join me in congratulating them

Event log dates

You can use Get-EventLog to query the event logs on you system

Get-EventLog -LogName System

 

One frequent task is to check if events occurred during a specific timespan. You may feel that you need to use a where-object filter to do this but there is a simple method.

Get-EventLog -LogName System -After (Get-Date -Date '1/1/2015')

 

Will return all events after the given date. if you don’t give a time your results start at midnight.

Get-EventLog -LogName System  -Before (Get-Date -Date '10/1/2015')

 

Will return all events before 10 January 2015.

You ususally use –Before in conjunction with –After to specify a data range

Get-EventLog -LogName System -After (Get-Date -Date '1/1/2015') -Before (Get-Date -Date '10/1/2015')

 

You can make these ranges quite specific

Get-EventLog -LogName System -After (Get-Date -Date '10/1/2015 14:31:00') -Before (Get-Date -Date '10/1/2015 15:00:00')