RSS

Category Archives: Powershell

Office 365 – Create PowerShell Session is failed using OAuth when trying to connect to Exchange Online PowerShell using Connect-ExoPSSession

For some time now I’ve been using the Microsoft Exchange Online Powershell Module that supports Azure multi-factor authentication (MFA)  , but for an unknown reason it stopped working

When trying to connect to Exchange Online PowerShell using the code below with a global administrator account, I was getting an access denied error:

Connect-EXOPSSession -UserPrincipalName admin.bjorn@mydomain.nl
New-ExoPSSession : Create PowerShell Session is failed using OAuth
At C:\users\admin\adppdata\local\Apps\2.0\84VE2AT5.PKO\HHYLAA32.DC7\micr..tion_c3bce3770c238a49_0010.0000_90fa60bba125a33a\CreateExoPSSession.ps1:179 char:22
+ ... PSSession = New-ExoPSSession -UserPrincipalName $UserPrincialName -C ...
+
    + CategoryInfo          : NotSpecified: (:) [New-ExoPSSession], Exception
    + FullyqualifiedErrorID : System.Exception,Microsoft.Exchange.Management.ExoPowerShellSnapin.NewExoPSSession

For me the solution was to install the Microsoft Exchange Online Powershell Module through Programs and then reinstalling it.

For more information about the new Exchange Online PowerShell module that supports Azure multi-factor authentication (MFA) see: https://technet.microsoft.com/en-US/library/ms.exch.eac.EXORPSMFAModuleLearnMore(EXCHG.150).aspx?v=15.1.860.4&l=1&s=BPOS_S_E15_0

Advertisements
 
 

Tags: , , , , , , , , ,

Office 365 – Access denied when trying to connect to Exchange Online PowerShell

When trying to connect to Exchange Online PowerShell using the code below with a global administrator account, I was getting an access denied error:

$usercredential = get-credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri<span class="Apple-converted-space"> </span>https://outlook.office3
65.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following
error message :
[ClientAccessServer=VI1PR08CA0018,BackEndServer=,RequestId=1c6b263f-08cf-4885-937c-e9c9808ddf89,TimeStamp=1/12/2017
2:46:41 PM] Access Denied For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $Session = New-PSSession -ConfigurationName Microsoft.Exchange -Conne ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : -2144108477,PSSessionOpenFailed

I was able to succesfully logon to https://login.microsoftonline.com/ so the credentials were correct.
Also I had not enabled Multi-factor authentication because I knew this could be a problem.
I tried clearing credentials / cookies in browsers and credential manager.

Since this did not solve the issue, I started to search online for answers. The first result was : https://support.microsoft.com/en-gb/kb/2905767 which suggested I entered the wrong username/password or that I didn’t have the correct permissions (organization administrator).

Both where not the case.

I then came across this post where someone apparently had to reset the password: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_o365admin-mso_manage/exchange-online-remote-powershell-access-denied/b91205bf-3419-4251-badc-4181af701d4f , but this was also not the case for me.

So I tried using the new Exchange Online PowerShell module that supports Azure multi-factor authentication (MFA) and the Connect-EXOPSSession cmdlet which did seem to work.

As it turns out, I accidentally tried to logon using <domain>\username instead of using my User Principal Name (UPN). When using my UPN it worked perfectly.

As a bonus though, now I have no excuse anymore to start testing with MFA

For more information about the new Exchange Online PowerShell module that supports Azure multi-factor authentication (MFA) see: https://technet.microsoft.com/en-US/library/ms.exch.eac.EXORPSMFAModuleLearnMore(EXCHG.150).aspx?v=15.1.860.4&l=1&s=BPOS_S_E15_0

 
Leave a comment

Posted by on January 16, 2017 in Microsoft, Office, Office 365, Powershell

 

Tags: , , , , , , , ,

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 – Auto generate PowerShell Functions from .NET Code using ISESteroids

PowerShell – Auto generate PowerShell Functions from .NET Code using ISESteroids

In my previous blog posts I described how to determine possible values for a property / attribute using .NET code and how to create a function to simplify this task in the future.

Shortly after, I saw a post on Twitter showing of functionality of ISESteroids to auto generate functions from .NET code. Since I hate to do unnecessary work and I know others think this way as well  wanted to share this. Even though in my case the time savings is not that big and the end result is not exactly what I was looking for, it saves me time and gives me is a very useful basis to build on.

For more information and a better example and explanation, see: http://www.powertheshell.com/net2powershell/.
You should also take a look at all the other great stuff that ISEsteroids can do to save you time and effort.

 
Leave a comment

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

 

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: , , , , , , , , , , , , , ,

 
%d bloggers like this: