#PowerShell, #PowerWiseScripting, #ProjectWise, PWPS_DAB

HowTo: Use New-MyPWLogin to Log Into ProjectWise within PowerShell

Be sure to check out my Scripting4Crypto initiative. It’s a fun way to get into using cryptocurrencies all while getting your PowerShell needs met.

In this post, I will be demonstrating a function (New-MyPWLogin) I have created to consolidate the available methods to log into a ProjectWise datasource.  We currently have multiple methods to log into a ProjectWise datasource such as logging in using a logical account, which requires you supply the datasource and user credentials to include the user name and a secure password string. We have the ability to sign on using single sign-on, which requires you pass the datasource and user name. Finally, we can use a Federated or Bentley IMS account, which only requires you provide the ProjectWise datasource. We will be using the following cmdlets to accomplish this task. All of the ProjectWise related cmdlets are available using the PWPS_DAB module. At the time of this post, I am using version 1.15.2.0. Take a look at the help for each of the cmdlets to become familiar with their functionality, available parameters, etc.
  • New-PWLogin
  • Save-SecureStringFromEncryptedFile
  • Get-SecureStringFromEncryptedFile
  • Get-PWCurrentDatasource
  • Get-PWCurrentUser
  • Get-PWUsersByMatch
  • Get-PWError

FUNCTION Definition

The following is the function wrapper which will contain the remainder of the code.
FUNCTION New-MyPWLogin {
    <#
        .Synopsis
        Log into a ProjectWise datasource.
        .DESCRIPTION
        Log into a ProjectWise datasource using one of the various methods.
        .EXAMPLE
        Example of Logging into a ProjectWise datasource using BentleyIMS.
        $DatasourceName = 'BMF-WS2016-PWDI:PWPowerShell'
        New-MyPWLogin -DatasourceName $DatasourceName -BentleyIMS
        .EXAMPLE
        Example of Logging into a ProjectWise datasource using Single Sign-On.
        $DatasourceName = 'BMF-WS2016-PWDI:PWPowerShell'
        $PWUser = 'brian.flaherty'
        New-MyPWLogin -DatasourceName $DatasourceName -UserName $PWUser
        .EXAMPLE
        Example of Logging into a ProjectWise datasource using a Logical Account.
        $DatasourceName = 'BMF-WS2016-PWDI:PWPowerShell'  
        $PWUser = 'pwadmin'
        $PasswordFile = 'D:\PowerShell\!aTesting\myps.txt'
        New-MyPWLogin -DatasourceName $DatasourceName -PasswordFilePathName $PasswordFile
        .OUTPUTS
        Returns a Boolean value ($true / $false)
    #>
    #Requires -Version 5.0
    #Requires -Modules @{ModuleName="PWPS_DAB";ModuleVersion='1.15.2.0'}

    [CmdletBinding()]
    param (...) # end param...

    BEGIN {...} # end BEGIN...

    PROCESS {...} # end PROCESS...

    END{...} # end END...
} # end FUNCTION New-MyPWLogin...
Export-ModuleMember -Function New-MyPWLogin

Parameters

First thing we need to do is create our parameters. The help messages will explain the purpose for each parameter. I am also going to include a few requires statements to ensure the correct version of PowerShell and the PWPS_DAB module are used. Pay attention to the validation methods I am using. I add ValidateNotNullOrEmpty to every parameter which is a string data type. Also, I use the ValidePattern to ensure the datasource passed is in the correct format (<SERVER>:<DATASOURCENAME>).   Also, I’ve used ValidateScript to ensure the password file exists.   If any of these validation tests fail, an error will be generated and the script will error out.
#Requires -Version 5.0
#Requires -Modules @{ModuleName="PWPS_DAB";ModuleVersion='1.15.2.0'}

[CmdletBinding()]
param ( 
    [ValidateNotNullOrEmpty()] 
    [ValidatePattern(":")]
    [Parameter(
        HelpMessage = "Datasource server / name combination. Required.",
        Mandatory = $true,
        Position = 0)]
    [string] $DatasourceName,

    [ValidateNotNullOrEmpty()]
    [Parameter(
        HelpMessage = "User name required when attempting to use single sign-on or logical account.")]
    [string] $UserName,

    [ValidateNotNullOrEmpty()]
    [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] 
    [Parameter(
        HelpMessage = "Path to text file on local system containing the encrypted user password. Use Save-SecureStringToEncryptedFile to create.")]
    [string] $PasswordFilePathName,

    [Parameter(
        HelpMessage = "Will log in using Bentley IMS when included. Username and password will be ignored.")]
    [switch] $BentleyIMS
) # end param...

Begin

In the begin section, I am going to create a flag variable to track the parameters which have been included. Basically, each parameter corresponds to a flag value. All flag values are added together.  This value is then used to determine which method to use to log into the specified ProjectWise datasource. There are other ways to accomplish this, however, I thought it worked well in this situation.
BEGIN { 
    <# The following flag variable will be used to contain a summation
        value. Each parameter corresponds to a value. If a parameter is
        included, the corresponding value will be added to the flag
        variable.These values will be added together and used to specify
        the method used to log into the specified ProjectWise datasource. 
        $Datasource is required and will not have a value.
        UserName = 1
        PasswordFilePathName = 2
        BentleyIMS = 4 
    #>
    $Flag = 0
    if($UserName){ $Flag = $Flag + 1 }
    if($PasswordFilePathName){ $Flag = $Flag + 2 }
    if($BentleyIMS){ $Flag = $Flag + 4 }
} # end BEGIN...

PROCESS

Now, we will proceed to the PROCESS code block.
PROCESS {
    # Splat containing login information.
    $Splat_Login = @{
        DatasourceName = $DatasourceName
    }
    
    <# Splat_Login hashtable will be populated based on the flag value.
         I use regex to add multiple values into one test. #>
    switch -regex ($Flag)
    {
       1  {  
            # Log in using Single Sign-On.
            $Splat_Login.UserName = $UserName
            break      
        }
        2  {
            <# If the password is provided by itself, 
                a message is returned and the script exists. #>
            Write-Warning -Message "User name required."                
            break
        }            
        3  {
            # Log in using username and password.
            $Splat_Login.UserName = $UserName
            $Splat_Login.Password = $(Get-SecureStringFromEncryptedFile -FileName $PasswordFilePathName)
            break
        }
        "^[0; 4-7]$"  {
            <# If the only the datasource name is provided, or the 
                 BentleyIMS parameter is provided, BentleyIMS will
                 be used to log in. #>
            $Splat_Login.BentleyIMS = $true
            break
        }
    } # end switch ($Flag...
    # Attempt to log into ProjectWise datasource.
    $Result = New-PWLogin @Splat_Login
} # end PROCESS...

END

Lastly, we will proceed to the END block of code. Here we will return the value of the $Result variable.  This will be either $true or $false.
END {
    Write-Output -InputObject $Result
} # end END...

Using the Function

Now that the function is created, let’s give it a try. I will run each one of the examples provided in the help.

EXAMPLE 1:

First example demonstrates logging into a ProjectWise datasource using BentleyIMS. After logging into ProjectWise, we will get the current datasource and user information. The following will result in a $flag value of 4.
$DatasourceName = 'BMF-WS2016-PWDI:PWPowerShell'
New-MyPWLogin -DatasourceName $DatasourceName -BentleyIMS 

# Returns the current datasource information.
Get-PWCurrentDatasource
# Get the currently logged in user id. Then user that id to get the user information.
$pwCurrentUserID = Get-PWCurrentUser | Select-Object -Property ID
Get-PWUsersByMatch -UserId $pwCurrentUserID.ID
The following shows the output within PowerShell. ims

EXAMPLE 2:

The second example demonstrates logging into a ProjectWise datasource using single sign-on. Again, once logged into ProjectWise we will get the current datasource and user information. The following will result in a $flag value of 1.
$DatasourceName = 'BMF-WS2016-PWDI:PowerShell'
$PWUser = 'brian.flaherty'
New-MyPWLogin -DatasourceName $DatasourceName -UserName $PWUser
If the log in fails, a warning message will be displayed with an error id. Use Get-PWError to get the error information. In the following example, the error id is 58063. error The following shows the current datasource and user information after a successful login to the ProjectWise datasource. singlesignon

EXAMPLE 3:

Finally, we will demonstrate logging into a datasource using a logical account. A user name and password must be supplied.  In this example, we will create a text file containing the password.

Create SecureString File

<# Create text file to store encrypted password.
    This file must be created on the computer which will be used to run PowerShell. #>
$PasswordFile = 'd:\powershell\mypassword.txt'
Save-SecureStringToEncryptedFile -FileName $PasswordFile -Prompt 'Enter password:'
The following will result in a $flag value of 3.
$DatasourceName = 'BMF-WS2016-PWDI:PWPowerShell'
$PWUser = 'pwadmin'
$PasswordFile = 'D:\PowerShell\!aTesting\myps.txt'
New-MyPWLogin -DatasourceName $DatasourceName -UserName $PWUser -PasswordFilePathName $PasswordFile
The following shows the current datasource and user information. logical

Summary

The main objective of this post is first, obviously to show you how to setup and use the New-MyPWLogin function, but also to demonstrate how you can use functions to improve / enhance your user experience within PowerShell. Oh, and to demonstrate how to use a few of the cmdlets available with the PWPS_DAB module.
The following is a link to the full PowerShell script. HowTo_Use New-MyPWLogin to Log Into ProjectWise within PowerShell Experiment with it and have fun. Hopefully, you find this useful. Please let me know if you have any questions or comments.  If you like this post, please click the Like button at the bottom of the page.

1 thought on “HowTo: Use New-MyPWLogin to Log Into ProjectWise within PowerShell”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.