RSS

Tag Archives: Powershell

PowerShell – PowerShell generated batch file results in error þ is not recognized as an internal or external command

PowerShell – PowerShell generated batch file results in error þ is not recognized as an internal or external command

Some time ago, a colleague told me he was having trouble generating a batch file using PowerShell. The batch file as generated, but when he tried to run the batch file, it resulted in an error containing:
þ is not recognized as an internal or external command

In the batch file, the character þ was nowhere to be found.

The code he used to generate the batch file was as follows:

$Batscript = ‘D:\batscript.cmd’

IF(Test-Path -path $Batscript)

{

Remove-Item $Batscript

}

$SSIDImport = Get-Content ‘D:\SSID.txt’

Foreach($SSID in $SSIDImport)

{

“nsrmm.exe -d -S $SSID -y $SSID | Out-File -filepath $Batscript -Force -Append

}

‘nsrim.exe -X’ | Out-File -FilePath $Batscript –Append

After Googling a bit I stumbled across a similar issue: http://powershell.org/wp/forums/topic/strange-character-error-when-running-native-cmdline-app/

Thanks to Dave Wyatt I learned that the default encoding for Out-Filepath is Unicode which many command line tools cannot handle. With this knowledge, the solution was to simply specify the encoding for Out-File as shown below.

$Batscript = ‘D:\batscript.cmd’

IF(Test-Path -path $Batscript)

{

Remove-Item $Batscript

}

$SSIDImport = Get-Content ‘D:\SSID.txt’

Foreach($SSID in $SSIDImport)

{

“nsrmm.exe -d -S $SSID -y $SSID | Out-File -filepath $Batscript -Force -Append -Encoding ascii

}

‘nsrim.exe -X’ | Out-File -FilePath $Batscript –Append -encoding ascii

After this change, everything worked perfectly.

 

 
Leave a comment

Posted by on March 31, 2016 in ICT, Microsoft, Powershell

 

Tags: , , , , , , , , ,

PowerShell – WMF5 (including PowerShell) 5 can be deployed using WSUS again, but there is a catch …

A couple of weeks ago I was thinking that I should blog that it’s a pity that Windows Management Framework (including PowerShell) could be not distributed through WSUS anymore. In the past it was available on through WSUS, but it was removed (expired) at some point due to some issues.

This meant to deploy PowerShell you could not deploy it through regular WSUS, but you had to either:

  • Include it in your base image
  • Install it manually
  • Install it using scripting
  • Install it using GPO
  • Install it using WSUS add-on solutions to deploy 3rd party packages. Example solutions include, but are not limited to Local Update Publisher (LUP), WSUS package publisher, SolarWinds patch manager.
  • Install it using enterprise systems management software. Example solutions include, but are not limited to System Center Configuration Manager (SCCM), Altiris, Landesk Management Suite, Tivoli Endpoint Manager (BigFix)
  • Install it using Intune

At many customers of ours this meant that PowerShell was left at version 2.0 for older operating systems unfortunately. For newer operating systems luckily version 3.0 was shipped by default. Still the version would never be updated in most cases.

Apparently the PowerShell team also thought something had to be done about that, because they made the Windows Management Framework (WMF) 5.0 RTM available via the Microsoft Update Catalog. Since it is published to the Microsoft Update Catalog, you have to manually import it to your WSUS environment. Also as the blog post states, before installing ensure you have reviewed known product incompatibilities (Exchange, SharePoint and System Center Virtual Machine Manager) and that the prerequisites are met.

I hope this will mean I will be seeing more up-to-date versions of PowerShell on systems of customers from now on.

One of the disadvantages however is that for operating systems before Windows 8.1/2012, a prerequisite is that WMF4 is installed, which cannot easily be deployed using WSUS unfortunately.

 

 

 

 

 

 

 

 
 

Tags: , , , ,

PowerShell – easily posting scripts to a website while maintaining syntax highlighting by copying as HTML

PowerShell – easily posting scripts to a website while maintaining syntax highlighting by copying as HTML

 

 

 

When sharing PowerShell scripts on the Internet there are a couple of options:

  1. Simply post it as plain text, which means syntax highlighting will not be included.
  2. Use available syntax highlighting for the platform you use. Sample platforms include:
    Microsoft ScriptCenter and a syntax highlighting example from a script of mine: https://gallery.technet.microsoft.com/scriptcenter/Determine-possible-values-eaf48782
    Wordpress : https://en.support.wordpress.com/code/posting-source-code/
  3. Copy code to HTML including syntax highlighting.

Option 2 and 3 are preferred, especially sharing to Microsoft ScriptCenter because others can then more easily find and use your scripts and maybe even improve them or give you tips on how to make better script.

Option 2 however requires that you have to accept whatever the platform provider has chosen with regards to syntax highlighting, which might differ between platforms. With option 3 you have more freedom with regards to the output and you are in control. Basically it means copying code to HTML including syntax highlighting. The solution I use mostly for this is the Windows PowerShell V3 ISE: Copy As HTML Add-On which adds a simple “Copy As HTML” option in the menu and which can also be used using the shortcut CTRL+SHIFT+C.

I don’t have experience with it, but you could take a look at the script that Lee Holmes from the PowerShell team provided: http://www.leeholmes.com/blog/2009/02/03/more-powershell-syntax-highlighting/
In the comments someone apparently also implemented it as a PowerGUI add-on.

For more PowerShell ISE Add-ons be sure to visit: http://social.technet.microsoft.com/wiki/contents/articles/2969.windows-powershell-ise-add-on-tools.aspx

 
Leave a comment

Posted by on March 14, 2016 in ICT, Microsoft, Powershell

 

Tags: , , , , , , , , , , ,

PowerShell – Get-EnumValue function to get possible values of properties / attributes

PowerShell – Get-EnumValue function to get possible values of properties / attributes

In my previous blog post I blogged about how to get the possible values of an attribute or property like by example the service starttype using enumerators.

For future use I’ve created this function called Get-EnumValue. The function (and any updated future versions) can be found on ScriptCenter: https://gallery.technet.microsoft.com/scriptcenter/Determine-possible-values-eaf48782

But for those that don’t want to click and just want to see the current version, here it is:

Function Get-EnumValue

{

    <#

    .SYNOPSIS

        Determine possible values of a property / attribute of the [system.enum] type

        By example the possible values of startup type of a service.

    .DESCRIPTION

        Determine possible values of a property / attribute of the [system.enum] type

        By example the possible values of startup type of a service

 

        In some cases this can easily be determined if there is a “set-” version of the cmdlet.

        By example with Get-Service, there is also a Set-Service where the StartUpType values can be determined using “Get-Help Set-Service -Full” or by simply typing: Set-Service -StartupType and using auto completion.

 

        In some cases this is however not possible and this function can be used.

    .PARAMETER EnumProperty

        Input a property of the [System.enum] type. By example: (Get-Date)[0].DayOfWeek or (Get-Service)[0].StartType’)    

    .EXAMPLE

        $FormatEnumerationLimit=-1

        $Property1 = (Get-Date)[0].DayOfWeek

        $Property2 = (Get-Service)[0].StartType

        Get-EnumValue -EnumProperty $Property1,$Property2

            

        Description

    

        ———–

    

        Set $FormatEnumerationLimit to -1 to prevent cutoff of the results.

        Store 2 properties in variables and use the Get-EnumValue function with the named parameter -EnumProperty to enumerate their values.

    .EXAMPLE

        $FormatEnumerationLimit=-1

        Get-EnumValue -EnumProperty (Get-Date)[0].DayOfWeek,(Get-Service)[0].StartType

            

        Description

    

        ———–

    

        Set $FormatEnumerationLimit to -1 to prevent cutoff of the results.

        Use the Get-EnumValue function with the named parameter -EnumProperty to enumerate their values without first storing them in variables.

    .EXAMPLE

        $FormatEnumerationLimit=-1

        $Properties = @((Get-Date)[0].DayOfWeek,(Get-Service)[0].StartType)

        Get-EnumValue -EnumProperty $Properties

            

        Description

    

        ———–

    

        Set $FormatEnumerationLimit to -1 to prevent cutoff of the results.

        Store 2 properties in a single array and use the Get-EnumValue function with the named parameter -EnumProperty to enumerate the values of the properties in the array.

    .EXAMPLE

        $FormatEnumerationLimit=-1

        (Get-Date)[0].DayOfWeek,(Get-Service)[0].StartType | Get-EnumValue | Format-Table    

    

        Description

    

        ———–

    

        Set $FormatEnumerationLimit to -1 to prevent cutoff of the results.

        Put 2 properties in the pipeline and pipe them to Get-EnumValue to get their values.

    .NOTES

        1) By default, the EnumValues are truncated like this for format-list, format-table, etc:

 

        For Format-List:

 

        TypeName   : System.DayOfWeek

        EnumValues : {Sunday, Monday, Tuesday, Wednesday…}

 

        TypeName   : System.ServiceProcess.ServiceStartMode

        EnumValues : {Boot, System, Automatic, Manual…}

 

        For Format-Table:

 

        TypeName                               EnumValues                            

        ——–                               ———-                            

        System.DayOfWeek                       {Sunday, Monday, Tuesday, Wednesday…}

        System.ServiceProcess.ServiceStartMode {Boot, System, Automatic, Manual…}

 

        By setting $FormatEnumerationLimit to -1 all values will be shown (https://blogs.technet.microsoft.com/heyscriptingguy/2011/11/20/change-a-powershell-preference-variable-to-reveal-hidden-data/):

        $FormatEnumerationLimit=-1

 

        2) This example uses [Enum]::GetValues but it can easily be modified to use [Enum]::GetNames

 

        3) Additional information and resources:

        http://social.technet.microsoft.com/wiki/contents/articles/26436.how-to-create-and-use-enums-in-powershell.aspx#UsingEnumsWiithFunction

        https://msdn.microsoft.com/en-us/library/system.enum.getnames(v=vs.110).aspx

        https://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx

#>

    [CmdletBinding()] #Provides advanced functionality. For more details see “What does PowerShell’s [CmdletBinding()] Do?” : http://www.windowsitpro.com/blog/powershell-with-a-purpose-blog-36/windows-powershell/powershells-%5Bcmdletbinding%5D-142114

    Param

    (

        [Parameter(Mandatory=$true, #Parameter is mandatory.

                   ValueFromPipeline=$True, #Allows pipeline input.

                   Position=0, #Allows function to be called without explicitly specifying parameters, but instead using positional parameters in the correct order

                   HelpMessage=‘Input an object of the [System.enum] type. By example: (Get-Date)[0].DayOfWeek or (Get-Service)[0].StartType’)] #Enter a help message to be shown when no parameter value is provided.

        [ValidateNotNullOrEmpty()] #Validate the input is not NULL or empty

        [ValidateScript({$_ -is [System.Enum]})] #Validate whether or not the input is actually of the [System.enum] type.

        [System.enum[]]$EnumProperty

    )

    BEGIN

    {

    }

    PROCESS

    {

        $Output = @()

        Foreach($object in $EnumProperty)

        {

            TRY

            {

                $TypeName = ($object | Get-Member)[0].TypeName

                $EnumValues = [Enum]::GetValues($TypeName) #Pre-PowerShell 3.0

                $ObjectEnumResult = New-Object PSCustomObject -Property @{

                ‘TypeName’ = $TypeName

                ‘EnumValues’ = $EnumValues

                }

                $Output += $ObjectEnumResult

            }

            CATCH

            {

                Write-Verbose “Error occurred processing $object

            }

            FINALLY

            {

            }

        }

 

        #Send output to the pipeline

        $Output

    }

    END

    {

    }

}

 

 
1 Comment

Posted by on March 11, 2016 in Automation, ICT, Microsoft, Powershell

 

Tags: , , , , , , , , , , , , , ,

PowerShell – Determine possible values for an attribute

While working on a script for XenApp 6.5 I wanted to perform actions based on the session state. To me however, the possible state values were not clear.

Without knowing these states, I would have to make assumptions which could lead to unexpected behavior and results.

Generic example

Since not everyone is using Citrix, here’s a more generic sample using Get-EventLog to determine the possible values for attribute EntryType

1. Get-EventLog -LogName System | Select EntryType -First 1 | Get-Member

This resulted in:

   TypeName: Selected.System.Diagnostics.EventLogEntry

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
EntryType   NoteProperty System.Diagnostics.EventLogEntryType EntryType=Information

2.  Enumerate the values using:
[Enum]::GetValues(‘System.Diagnostics.EventLogEntryType‘)

This results in the following possible values:

Error
Warning
Information
SuccessAudit
FailureAudit

XenApp 6.5 example

To determine the possible states, I did the following:

1. Get-XASession | Select State | Get-Member

This resulted in:

TypeName: Selected.Citrix.XenApp.Commands.XASession

        Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
State       NoteProperty Citrix.XenApp.Commands.SessionConnectionState State=Disconnected

2.  Enumerate the values using:
[Enum]::GetValues(‘Citrix.XenApp.Commands.SessionConnectionState‘)

This results in the following possible values:

Unknown
Active
Connected
Connecting
Shadowing
Disconnected
Idle
Listening
Resetting
Down
Initializing
Stale
Licensed
Unlicensed
Reconnected

Alternative method for PowerShell 3.0 / .NET Framework 4.0 and later

After writing this blog post I came across this post http://www.powershellmagazine.com/2013/03/15/pstip-getting-enum-values-in-powershell-3-0/ explaining an alternative method that is available for PowerShell 3.0 / .NET Framework 4.0 and later :

[System.Diagnostics.EventLogEntryType ].GetEnumValues()

[System.Diagnostics.EventLogEntryType].GetEnumNames()

 

 

 
2 Comments

Posted by on March 9, 2016 in Citrix, Microsoft, Powershell, XenApp

 

Tags: , , , , ,

Free PowerShell Desired State Configuration (DSC) training on February 25th and 26th

Microsoft Virtual Academy (MVA) is hosting 2 PowerShell Desired State Configuration (DSC) training classes on February 25th and February 26th:

  1. Getting Started with PowerShell Desired State Configuration (DSC)
  2. Advanced PowerShell Desired State Configuration (DSC) and Custom Resources

The links above provide include a course outline and a link to register for the Jump Start. And even if you can’t join live, the recordings will always be made available at a later time so you can watch whenever it suits you better.

PowerShell DSC is becoming increasingly important and I personally also still need to learn more about it and look forward to it.

I hope it’s useful to you as well.

 

Tags: , , , , , , , , , , , , ,

PowerShell – Book review of : Windows PowerShell Best Practices

Windows PowerShell Best Practices

Last week I completed PowerShell Deep Dives which got me excited again to read more about PowerShell. As such, I continued reading the next book on my reading list: Windows PowerShell Best Practices by Microsoft Scripting Guy Ed Wilson.

The book was released late January 2014 and is the most recent book about PowerShell that has been released to my knowledge. This means it includes PowerShell 4.0, Desired State Configuration DSC and references to Windows 8.1 and Windows Server 2012 R2.

In my opinion the book was very well written and contains a good mix of theory, sample scripts and “notes from the field” from many PowerShell specialists. The sample scripts are available for download at Technet Script Center.

The best practices that are described in the book are very recognizable and I had already adopted many of them based on the many great blog posts by the community. In the book they are all bundled and well explained including examples. Where the book really shines though in my opinion is that it describes how PowerShell is used in real-life, how it relates to many other processes within a company and what you need to consider.

I think this book is a must-have for anyone working with PowerShell. For those starting with PowerShell, I recommend first reading the books “Learn Windows PowerShell In A Month Of Lunches” and “Learn PowerShell Toolmaking In A Month Of Lunches” and then read this book.

Notes:

 
 

Tags: , , , , ,

 
Follow

Get every new post delivered to your Inbox.

Join 1,635 other followers

%d bloggers like this: