PowerShell – Get Computer name

Background

Wanted to highlight a couple of APIs for retrieving the computer name in Powershell.

Platform

Linux/Cent OS.

 

Outline

  1. Environment Variable
    • Get-ChildItem Env:HOSTNAME
  2. system.environment
    • machineName
  3. system.net.Dns
    • GetHostName
  4. Get-WmiObject ( only works on MS Windows )
    • Win32_ComputerSystem
      • Name

 

Environment Variables

Get-ChildItem Env:

Syntax


pwsh -Command "Get-Childitem Env:"

Output

Get-ChildItem.Env.20181112.0729PM

 

Get-ChildItem Env:HOSTNAME

Syntax


pwsh -Command "Write-Host( (Get-ChildItem Env:HOSTNAME).Value )"

Output

Get-ChildItem.Env.HostName.20181112.0723PM

system.environment

machineName

Syntax


pwsh -Command "Write-Host([system.environment]::machineName)"

Output

system.environment.machineName.20181112.0708PM

system.net.Dns

GetHostName

Syntax


pwsh -Command "Write-Host([system.net.Dns]::GetHostName())

Output

system.net.Dns.GetHostName.20181112.0706PM

 

Get-WmiObject.Win32_ComputerSystem.Name.20181113.0159AM.PNG

Win32_ComputerSystem

Syntax


powershell -Command "Write-Host((Get-WmiObject Win32_ComputerSystem).Name)"

Output

OS – MS Windows

Get-WmiObject.Win32_ComputerSystem.Name.20181113.0159AM.PNG

OS – Linux

Image

Get-WmiObject.Win32_ComputerSystem.Name.Linux.20181113.0203AM

Textual


>pwsh -Command "Write-Host( Write-Host((Get-WmiObject Win32_ComputerSystem).Name))"
Get-WmiObject : The term 'Get-WmiObject' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:25
+ Write-Host( Write-Host((Get-WmiObject Win32_ComputerSystem).Name))
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-WmiObject:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

PowerShell Install On Linux / CentOS

Background

Still preparing our CentOS computer.

Our current step is to Install Microsoft’s PowerShell.

Guide

Our guide is :-

Installing PowerShell Core on Linux
Link

Outline

  1. Install
    • yum
      • Install
        • Install Powershell
      • Registered Repositories – Review
        • yum repolist
        • ls /etc/yum.repos.d
      • Registered Repositories – Update
        • Curl/tee
      • Install
        • Install Powershell
  2. Run Sample Powershell Scripts

Install

Install Powershell

yum install powershell

Syntax


yum install powershell

Output

Output – Image

yum.install.powershell.20181112.1030AM.PNG

Output – Text

>sudo yum install powershell
[sudo] password for dadeniji:
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.hostduplex.com
* extras: mirror.keystealth.org
* updates: mirror.keystealth.org
No package powershell available.
Error: Nothing to do
>

Explanation

Microsoft’s repository not registered on machine.

Registered Repositories – Review

Let us review the yum repositories that we have registered.

yum repolist

Syntax


yum repolist

Output

Output – Image

yum.repolist.20181112.1028AM.PNG

Output – Textual

>yum repolist
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirrors.sonic.net
* extras: mirrors.usc.edu
* updates: sjc.edge.kernel.org
repo id repo name status
base/7/x86_64 CentOS-7 - Base 9,911
extras/7/x86_64 CentOS-7 - Extras 434
updates/7/x86_64 CentOS-7 - Updates 1,614
repolist: 11,959

 

/etc/yum.repos.d :- List Files

Syntax


ls -la /etc/yum.repos.d

Output

Output – Image

ls.etc.yum.repos.d.20181112.1033AM.PNG

Explanation

  1. The only repositories registered are CentOS

 

Registered Repositories – Update

Create File /etc/yum.repos.d/Microsoft.repo

Let us add Microsoft’s Redhat repository to the list of registered repositories.

Syntax


curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo

Output

Output – Image

curl.tee.20181112.1035AM.PNG

Output – Textual

>curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum .repos.d/microsoft.repo
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 193 100 193 0 0 504 0 --:--:-- --:--:-- --:--:-- 505
[packages-microsoft-com-prod]
name=packages-microsoft-com-prod
baseurl=https://packages.microsoft.com/rhel/7/prod/
enabled=1
gpgcheck=1
gpgkey=https://packages.microsoft.com/keys/microsoft.asc
>

 

yum install

Using yum, let us install powershell.

yum install powershell

Syntax


sudo yum install -y powershell

Output

Output – Image
Output – Image – #1

yum.install.powershell.20181112.1037AM.PNG

Output – Image – #2

yum.install.powershell.20181112.1039AM.PNG

Output – Image – #3

yum.install.powershell.20181112.1041AM.PNG

Output – Image – #4

yum.install.powershell.20181112.1043AM.PNG

Output – Image – #5

yum.install.powershell.20181112.1045AM.PNG

 

 

Sample

Run Sample Scripts

Sample #1

Get PowerShell Version Number

Syntax


pwsh -Command "Write-Host((Get-Host).version) "

Output

Output – Image

powerShell.version.20181112.1218PM

Sample #2

Get Username for current user.

Syntax


pwsh -Command "Write-Host( 'Hello ' +  [Environment]::Username) "

Output

Output – Image

helloWorld.20181112.1137AM

 

Summary

Couple of quick points :-

  1. Installation Errors
    • Error :- Repository not available
      • Message
        • No package powershell available.
          Error: Nothing to do
      • Remediation
        • Update Repository – Add Microsoft
  2. In MS Windows, the Powershell executable is powershell.
    In Linux, is is pwsh.

 

 

Echo Data to Powershell

Background

Trying to automate a little app.

As Powershell is a modern development tool and I do not need to compile the source code wanted to try it out first.

Exercise

Our need is very narrow.

The app is requesting that we enter our full name.

Really did not want to engage with the app so intimately and will rather feed its input through another channel.

Code

Powershell


$fullname = Read-Host -Prompt 'Please enter first and last name'

$line = "The name you entered is {0}" -f $fullname

Write-Host $line

CommandShell


@echo off

setlocal

    set "_fullname=Daniel Adeniji"

    set "_app=acceptKeyStroke.ps1"

    echo %_fullname% | powershell -f %_app%

endlocal

Output

echoToPowershell_20181025_0810AM.PNG

List Registered DB Providers using PowerShell

Background

As we prepare some of our machines for Database Application Server work, wanted to see how to programmatically discover which Database Providers are installed.

 

Code

Outline

  1. .Net Class
    • DbProviderFactories
      • Methods
        • GetFactoryClasses
          • Returns DataTable

Powershell

Script


Set-StrictMode -Version Latest;

function listProviders()
{
	Param(

			  [parameter(Mandatory=$true)]
			  [Object]
			  $objDBFactories

    )
	[int] $iPropertyIndex = 0;

	foreach($objDBFactory in $objDBFactories)
	{

	   # increment property counter
	   $iPropertyIndex = $iPropertyIndex + 1;

	   $strLog = $objDBFactory;

	   # display data
	   $strLog;			

	} 

}	

#Get Database Provider Factory
$objDBFactories = [System.Data.Common.DbProviderFactories]::GetFactoryClasses();

#listProviders $objDBFactories

$objDBFactories | Out-GridView;

"Please press any key to continue"

#Wait
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL;
$HOST.UI.RawUI.Flushinputbuffer();

Output

Output – Sample

listDBProviders_20181019_0525PM

References

  1. Microsoft
    • DbProviderFactories
      • Docs / NET / .NET API Browser / System.Data.Common / DbProviderFactories / Methods / GetFactoryClasses
        • GetFactoryClasses
          Link

 

PowerShell – Error – “Cannot process argument transformation on parameter ”. Reference type is expected in argument.

Error

Error – Text

readConfigurationFile : Cannot process argument transformation on parameter 'loadDuration'. Reference type is expected in argument.

Error – Image

PowerShell_Error_20181018_0558PM

Reproduce

Code


function readConfigurationFile
{

	Param(

			  [parameter(Mandatory=$true)]
			  [String]
			  $scriptName

			, [parameter(Mandatory=$true)]
			  [Object]
			  $cstrbld		

			, [parameter(Mandatory=$true)]
			  [ref] [int]
			  $loadDuration
    )

	###########################################################
	# Get Current Folder
	###########################################################
	$currentFolder=Convert-Path .

	###########################################################
	# Ini - Get Current File
	###########################################################
	$fileIni = "dbsettings.ini"

}

Remediation

Outline

  1. The third argument is an int and for changes to persists it needs to be passed as ref
  2. Current Entry
    • [ref] [int]
      • We are defining it as both ref and int
  3. Revision
    • [ref]
      • Please remove [int] and have system pass along as reference
      • reference obviously means a pre-recorded address in memory

Code



function readConfigurationFile
{

	Param(
	
			  [parameter(Mandatory=$true)]
			  [String]
			  $scriptName
			  
			, [parameter(Mandatory=$true)]
			  [Object]
			  $cstrbld		
			  
			, [parameter(Mandatory=$true)]
			  [ref] #[int]
			  $loadDuration
    )
	
	###########################################################
	# Get Current Folder
	###########################################################
	$currentFolder=Convert-Path .
}

PowerShell – By Reference

Background

It is always so easy to talk about things we know so little of.

Code

Outline

  1. Calling Routine
    • Each variable to pass by ref
      • Syntax
        • argument-in-called function ([ref] $local-variable)
      • Sample
        • strNew ([ref] $newCompanyName)
  2. Called Routine
    • Add Param Clause
      • Syntax
        • [ref] $variable-name
      • Example
        • [ref] $companyName
    • Explicitly state that value is being changed
      • Syntax
        • $variable.Value=[new-value]
      •  Example
        •   $strNew.Value=”Inprise Corp”

PowerShell


Set-StrictMode -Version Latest

function passByRef
{

    Param($str, [ref] $strNew, [ref] $loadDuration, [ref] $ratio)
    $str="Inprise Corp"
    $strNew.Value="Inprise Corp"
    $loadDuration.Value=100
    $ratio.Value=10

    $result = $loadDuration.Value / $ratio.Value
}

$company = "Borland"
$companyNameChange = ""
$loadDuration=0
$ratioLocal=-1

passByRef $company -strNew ([ref]$companyNameChange) -loadDuration ([ref]$loadDuration) -ratio ([ref]$ratioLocal)

"Company is $company"
"Company Name Change is $companyNameChange"
"loadDuration is $loadDuration"
"ratioLocal is $ratioLocal"

"Press Enter to complete"

#Wait
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL;
$HOST.UI.RawUI.Flushinputbuffer();

Output

passByRef_20181015_0721PM

Listening

Listening to Paul Simon..

Something so right
Link

Lyrics

When the fever runs high
You’ve got the look of love light
In your eyes
And I was in crazy motion
‘Til you calmed me down
It took a little time
But you calmed me down
When something goes wrong
I’m the first to admit it
I’m the first to admit it
But the last one to know
When something goes right
Well it’s likely to lose me
It’s apt to confuse me
It’s such an unusual sight
I can’t get used to something so right
Something so right

 

Oliver Lipkau :- Get Ini File Contents in PowerShell

Background

In a previous post ended up hard coding database connectivity information in the the actual PowerShell code.

Not a good look.

Let us move that into an INI File.

Oliver Lipkau

BTW, here is the link to the previous post :

Db/2 – PowerShell – Lab Exercises – 01
Link

Oliver Lipkau

Ini File Management

PowerShell

Outline

  1. PowerShell
    • PowerShell Function File
      • Get-IniContent.ps1
    • Powershell PSM1
      • PSIni.psm1
    • Sample Invocation
      • readIniFile.ps1

PowerShell Function File

Get-IniContent.ps1
Set-StrictMode -Version Latest
Function Get-IniContent {

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;#

<span id="mce_SELREST_end" style="overflow:hidden;line-height:0;"></span>$FileContent["Section"]["Key"]
        -----------
        Description
        Returns the key "Key" of the section "Section" from the C:\settings.ini file  

    .Link
        Out-IniFile
#&gt;  

    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [ValidateScript({(Test-Path $_) -and ( ( (Get-Item $_).Extension -eq ".ini") -or ( (Get-Item $_).Extension -eq ".txt") ) })]
        [Parameter(ValueFromPipeline=$True,Mandatory=$True)]
        [string]$FilePath
    )  

    Begin
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}  

    Process
    {
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"  

        $ini = @{}
        switch -regex -file $FilePath
        {
            "^\[(.+)\]$" # Section
            {
                $section = $matches[1]
                $ini[$section] = @{}
                $CommentCount = 0
            }
            "^(;.*)$" # Comment
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $value = $matches[1]
                $CommentCount = $CommentCount + 1
                $name = "Comment" + $CommentCount
                $ini[$section][$name] = $value
            }
            "(.+?)\s*=\s*(.*)" # Key
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $name,$value = $matches[1..2]
                $ini[$section][$name] = $value
            }
        }
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"
        Return $ini
    }  

    End
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
} 

PowerShell Application File

PSIni.psm1

$PsIniModuleHome = Split-Path -Path $MyInvocation.MyCommand.Path -Parent

# Name of the Section, in case the ini file had none
# Available in the scope of the module as `$script:NoSection`
$script:NoSection = "_"

# public functions
. "$PsIniModuleHome\Functions\Get-IniContent.ps1"

readIniFile.ps1

Set-StrictMode -Version Latest

###########################################################
# Import Module
###########################################################
Import-Module .\PSIni.psm1  -NoClobber -ErrorAction Stop

###########################################################
# Get Current Folder
###########################################################
$currentFolder=Convert-Path .

###########################################################
# Ini - Get Current File
###########################################################
$fileIni = "dbsettings.ini"

###########################################################
# Ini - Get Current File ( fullname)
###########################################################
$fileIniFullname = $currentFolder + [IO.Path]::DirectorySeparatorChar + $fileIni;

$fileContent = Get-IniContent ($fileIniFullname);

###########################################################
# Ini File - Read
###########################################################
$section="Database";

$key="server";
$dbServerHost = $fileContent[$section][$key]

$key="port";
$dbServerPort = $fileContent[$section][$key]

$key="database";
$dbDatabase = $fileContent[$section][$key]

$key="userid";
$dbUserID = $fileContent[$section][$key]

$key="password";
$dbUserPassword = $fileContent[$section][$key]

###########################################################
# Ini File - Display
###########################################################
"Database Server :- $dbServerHost"

"Database Server Port :- $dbServerPort"

"Database :- $dbDatabase"

"Database UserId :- $dbUserID"

"Database User Password :- $dbUserPassword"

Configuration Files

Outline

  1. Configuration Files
    • Ini File
      • dbsettings.ini

Configuration File

dbsettings.ini

[Database]
server=localhost
port=50000
database=WIDEWRLD
userid=db2user
password=simplepassword

Control Files

Outline

  1. Invoke
    • PowerShell
      • pass file name to Powershell file

Powershell

Invoke

powershell -file ./readIniFile.ps1
Output

invoke_2018104_0447PM

Dedicated

Dedicated to Oliver Lipkau :-

Work with INI files in PowerShell using hashtables
Link