Archive for the ‘PowerShell’ Category

Replace a character in a string

Friday, October 10th, 2014

I had a script where I needed to change a character in a string.

Simple task as I found on the Net.

$str = $str.replace(‘\’,’_’)

Scriptblock doesn’t work with variables.

Friday, October 10th, 2014

Powershell is a fun experience which I wish I had started awhile ago.  It’s features seem endless and it greatly eases system management.

The recent scare over Shellshock caused us to evaluate our Cygwin installations.  We didn’t know the exact number of installations and the version of Bash in use.

The question of the number of Cygwin installations was easy to solve. A script to review the organization units and scan each computer for Cygwin.

After a list was generated; a script was written and three results files were created: Found, System Down, and Not Found.

Cygwin due to it’s open source nature does not follow Microsoft design standards.  It has it’s own way of doing things. Good for the user but not always good for system management purposes.

I didn’t find a “Quick and Dirty” way to get the version number of the Bash executable.   Nothing in the registry and file information lacked details.

Redhat (we use them for support) advised using the “–version” option to identify the version.  A rather tedious task if done through remote desktop or nagging the users to send the information.

What would be nice if there was way to run a command remote and get the information.

Powershell has a nice option called “invoke-command.” It’s a one use option for such things.

The command is rather simply to use:

Invoke-Command -scriptblock { c:\cygwin\bin\bash –version }  -computername <hostname>

This gave the following output:

GNU bash, version 4.1.15(1)-release (i686-pc-cygwin)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

A little too much detail for a version number.  This was quickly addressed by using Select-String command.

Invoke-Command -scriptblock { c:\cygwin\bin\bash –version }  -computername <hostname> | Select-String -pattern “GNU bash, version”

This in turn gave:

GNU bash, version 4.1.15(1)-release (i686-pc-cygwin)

This was usable.  It also helped with simple errors.  If you don’t get the expected result, add an error message. This became evident when trying to run the command on Windows 2003 which lacked Powershell 2.0 and systems which did not have remote management configured.

Invoke-Command is great.  It gave me the information I needed without visiting each system.

I wrote a script and quickly found two problems:

  1. There are flavors of Cygwin and unless there was a conscious effort during install; you could end up with different directories (ie: C:\cygwin, C:\cygwin64, C:\rhcygwin).
  2. Running the command for several systems.  Invoke-Command can take up to five systems.  Great for a small number but not so great when you have hundreads or more.

Both of these issues required the use of variables and it was quickly discovered that -scriptblock option couldn’t use variables. For example:  $cygwinPath\bash.exe –version resulted as \bash.exe –version

The dynamic nature of scanning several computers was not something the command could do.  Rather then use another approach; I looked around the Net and found there was a way to use dynamic scriptblocks by using the NewScriptBlock command.

A quick change:

$scriptblock = $ExecutionContent.InvokeCommand.NewScriptBlock( “$cygwinPath\bash.exe –version”)
$versionResult = Invoke-Command -scriptblock $scriptblock -computername $server | Select-String -pattern “GNU bash, version”

This gave the needed results and we had an understanding of the work needed to be done.

If you would like to read more about Invoke-Command, Ed Wilson did a nice little writeup on his blog.

How to skip the first line with import-csv

Wednesday, September 3rd, 2014

I had a “quick and dirty” script to examine a list of hosts from a CSV.

There was a header with the data and I didn’t want the error that would pop up at the end of the foreach loop.

To get around the first line; I used a pipe and the select statement:

Import-Csv $file -header(“Hostname”, “OldIP”, “NewIP”) | select -Skip 1 | foreach {

Simple and it avoids a comparison check in the code.

The only thing to be concerned is if there are times there will be files without a header.

An extended error has occurred

Thursday, July 10th, 2014

New operating systems always bring new error messages. Such was a recent incident for a Windows 2012 server trying to access a share on a Network Appliance Filer:

An extended error has occurred

A quick test of my Windows 8.1 laptop produced the same error.

We have been playing around with SMBv3 on the Netapp filers and this was thought to have been an issue as the new OS is more SMBv3 “friendly.”

The filer people said they configured the filer to use smbv2 but the error continued.

Originally, I wrote about this a year ago with this post but you can review the support article.

I suspected either signed support was not configured or can’t be used so I opted to disable it via Powershell and the command(start it in admin mode):

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" RequireSecureNegotiate -Value 0 -Force

A reboot of the server (just because) and we had access to the share.

For those that want to get some features information on SMBv3 and 2012, you can look at this article.

Powershell editor

Wednesday, January 1st, 2014

I sometimes get asked for suggestions for a Powershell editor.   Probably the biggest and best  is Sapiens Primalscript.  But with all the abilities and power; this means a bigger price tag. There is also an expectation of upgrades.  I let mine go too long and was told I had to purchase new.  😦

I also find many people are looking for a free editor.  Microsoft has a page of suggested editors on Technet.

As mentioned I have used Primalscript and recommend it if you have the money to invest.

I have used the one that comes with Powershell and it’s ok if you are starting out.

I have used the GUI version and found it’s ok for most things.

I am now starting to “play around” with Admin Script Editor.  The page shows it’s a purchased package but this is no longer the case.  The company closed shop but they made the last version free to people who use the itninja site.

 

 

 

Admin Script Editor is no more

Wednesday, January 1st, 2014

I was looking at upgrading my editor for powershell.

Normally, I use Sapien but I had not upgraded it for several years and they said I basically had to purchase it new.   I thought maybe with the New Years Eve deal but it appears they stopped doing that.  😦

I had a look at the old ASE and found the company had closed its doors last September but they made the last version free to people who join the itninja site.

It’s the enterprise version and so far it runs on 8.1.

Time will tell.

 

 

Powershell: Direct output to a variable.

Thursday, July 25th, 2013

I was asked if there was a way to capture output of a specific program to a variable.

Basically, the person wanted to get a version number from the program.

Played around and had a way to accomplish this  but I found a simpler approach.

$scriptOutput = & "c:\path\program.exe" -V 2&1

Obviously, the -V works with the program in question.

I am liking powershell

The account used is a computer account. Use your global….

Thursday, July 25th, 2013

While scripting a report; I noticed a bogus error about a file version being wrong.

I examined the server in question and found the server service was not running.

I tried to start it but it stopped right away with the following message in the system event log.

The Server service terminated with the following error:
The account used is a computer account. Use your global user account or local user account to access this server.

Another server with the same problem would give this message:

Windows could not start the Server service on Local Computer Error: 1808: The account used is a computer account. Use your Global user account or local user account to access this server.

The service was configured correctly.

An odd problem and it’s cause was the fact a couple users placed URLs in the system Path variable (ie \\server\mount\dir).

Removing the entries and a reboot of the server corrected the issue.

set-executionpolicy unrestricted is denied.

Sunday, February 3rd, 2013

One of the steps we have for setting up a new LSF server is to run a powershell script which does a survey of the machine. The first step is to un-restrict the execution policy via this command:

set-executionpolicy unrestricted

The command was entered and it returned this nice little error:

Execution Policy Change
The execution policy helps protect you from scripts that you do not 
trust. Changing the execution policy might expose you to the security 
risks described in the about_Execution_Policies help topic. Do you 
want to change the execution policy?

[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\
SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft .PowerShell' is 
denied.

At line:1 char:20
+ set-executionpolicy <<<<  unrestricted
    + CategoryInfo          : NotSpecified: (:) [Set-ExecutionPolicy], 
      UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,
      Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

Rather odd since all security was correct.

Two obvious ideas are to upgrade powershell or reinstall it. Neither was an option is this situation.

I did a quick look around Microsoft and found this.

I decided to try the registry option and added the login.

* Run: regedt32
* Goto HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell
* Right-Click > Permissions
* Select, and add your account, grant it “Full Control” privileges
I re-entered the set-executionpolicy command and this time it worked.

 

Could not start PsExec service on host

Saturday, February 2nd, 2013

I have a script which uses psexec to check a few things on new servers. I ran the script and received the following message.

Couldn’t access *hosta*:
The handle is invalid.
Could not start PsExec service on *hosta*:
Access is denied.
Starting PsExec service on *hosta*…

Rather an odd message because another server with the same configuration didn’t have a problem. I checked a few things but did not find anything obvious. Server pings, remote desktop works, etc., etc…..

From the other box I tried to see if I could remote access the C drive via \\hosta\C$ and received this error:

\\hosta\C$

Logon Failure: The target account name is incorrect

The AD account looked ok but when I checked the host; I found a typo.  Instead of *hosta* there was *hosa* (obviously not the real name but you get the idea).

I deleted the domain account and simply renamed the server.  The domain prompted for an admin level account to do this and rebooted.

Don’t forget to move the host to the proper AD group if you use them.

Moral of the story: DNS/AD is both a friend and enemy. DNS pointed to the correct server but simple things would not work while other things like remote desktop did.  Well? Only because a previous problem prompted for a change in the negotiation level of RD.

It’s funny but I look back to my first AD design course and I remember the teacher repeating most AD problems are DNS related.