Using PowerShell to automate and maintain PBCS with EPM Automate introduces significant optimization and communication. Kyle Goodfriend presented this at the Ohio Valley Oracle Application User Group.
2. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 2
Speaker Background
Welcome
• Love playing ice hockey
• Scuba dive as much as I can
• Work with dog rescues
• Have a beautiful wife that I drive nuts
• Raising a son that is a walking medical
deductable
• Earned a finance degree / BBA
• Was a college professor for 5 years
• Have worked with Hyperion since 1997
• Started consulting in 2008
• 100% self taught
• Worked with Huron since 2013 (via ADI
Strategies)
• Created In2Hyperion and the Essbase Excel
Ribbon (www.In2Hyperion.com)
• Started the Columbus Hyperion Customer
Community (CHCC.In2Hyperion.com)
• I am still learning PowerShell
6. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 6
Who Should Attend
Session Introduction
Those With Little to No Experience With PowerShell
• Application owners that investigating how
automation can improve their process and its
consistency
• Finance administrators with an aptitude for
technology
• Have some experience with a scripting language
• Technology expert not familiar with PowerShell
7. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 7
Session Rules
Session Introduction
Stay Interactive, Be Respectful, Have Fun
Be interactive, jump in,
ask questions
Tweet and share your
experiences
Take notes
Add value, share
experiences
Be respectful – none of
us know everything
Stand up, stretch, stay
awake
8. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 8
Session Objectives
Session Introduction
Leave With Knowledge
Share our collective
knowledge
Get exposed to
PowerShell
Leave with workable
examples you can
implement immediately
Read and edit
PowerShell examples
Setup an environment
to start building
PowerShell scripts
Have a basic
understanding of the
necessary skills to build
PowerShell scripts
9. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 9
Session Objectives
• How to use EPM Automate
• Specific parameters sent to EPM Automate
Session Introduction
What We Won’t Cover
10. POWERSHELL OVERVIEW
PowerShell is a powerful utility for all
kinds of functional purposes, including
system automation.
01 PowerShell Introduction
02 Installing PowerShell
03 Enabling Script Execution
04 Development Environment Options
05 Development UI Walkthrough
11. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 11
What Is PowerShell
PowerShell Overview
And What Can It Do
It is open sourced and can be installed on Linux,
Windows, VMWare, Mac, Ubuntu, Citrix, and
other operating systems.
It can be used interactively or executed as a
script
Tasks that take hundreds of lines of VBScript or
DOS can be accomplished in one line
It is an object oriented and has properties,
methods and events – everything has a noun
and verb
It is based on the .net framework
It can complete bulk operations
It can automate manual and repetitive tasks
It is platform independent
PowerShell is an interactive object-oriented command environment with scripting language features that
utilizes small programs called cmdlets to simplify configuration, administration, and management of
heterogeneous environments in both standalone and networked typologies by utilizing standards-based
remoting protocols.
12. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 12
Installing PowerShell
• Part of the Windows Management Framework
• Download from Microsoft
• Download install for Mac/Linux
PowerShell Overview
What You Need To Know
13. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 13
The Development Environment
• There are 2 environments available when installed on Windows (technically 4)
• 32 bit GUI
• 32 bit command line
• 64 bit GUI
• 64 bit command line
PowerShell Overview
GUI and Command Line
14. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 14
Enabling Execution
• By default, the security policy will not allow the execution of PowerShell scripts
• If you get an error that reads “execution of scripts is disabled on this system,” there are two
options
• Change the policy so all scripts are executed without this limitation
• Run PowerShell as Administrator. In most environments, right click on Powershell and select Run as
Administrator.
• Run this command
• Set-ExecutionPolicy RemoteSigned
• To set policies back to the default, run Set-ExecutionPolicy Restricted
• Bypass the policy with command line parameters when scripts are executed
• powershell -ExecutionPolicy ByPass -File YourScript.ps1
PowerShell Overview
Updating Policy to Execute Scripts
16. POWERSHELL KEY
CONCEPTS
PowerShell is a powerful utility for all
kinds of functional purposes, including
system automation.
01
Cmdlet Overview
Cmdlets are the
foundation of PowerShell.
Without an understanding
of these objects, becoming
efficient will be an uphill
battle
02
Verb-Noun Layout
Cmdlets are formatted in a
verb-noun format with
parameters. If you have a
child, you may say, Tommy,
stop. The cmdlet for that
would be
child-stop –child Tommy.
03
Aliases
Aliases are setup by
default to help developers
user their native
experience. These can be
altered, deleted, and new
ones can be created.
LS(Unix)=dir(DOS)
=get-childitem (PS)
04
Pipelines
Similar to inheritance,
piping command together
minimizes code and
confusion in both
development and
maintenance. This
minimizes variables to
hold results of Cmdlets to
be immediately used.
05
Code Organization
Organizing and
documenting code is
essential to ensuring
effective code
maintenance and making
sure those who come after
you don’t lose sleep
17. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 18
Cmdlets Overview
• A cmdlet is a lightweight command that is used in the Windows PowerShell environment.
The Windows PowerShell runtime invokes these cmdlets within the context of automation
scripts that are provided at the command line. The Windows PowerShell runtime also
invokes them programmatically through Windows PowerShell APIs.
• Cmdlets perform an action and typically return a Microsoft .NET Framework object to the
next command in the pipeline.
• Cmdlets are instances of .NET Framework classes; they are not stand-alone executables.
• Cmdlets can be created from as few as a dozen lines of code.
• Some examples of cmdlets
• Get-Location
• Copy-Item
• Rename-Item
Key Concepts
The Foundation of PowerShell
18. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 19
Verb-Noun Explanation
Key Concepts
All CmdLets are constructed of Verb Noun Methodology
Benefits of Scripting
• Very readable
• Object Oriented
• Verb – Noun Operations
• Known as a Cmdlet
• Parameters are adjectives that describe the noun
• Easily repeatable
• Complex tasks can be completed in simple code
Verb Noun Name Value
get-mailbox -server “mail.gmail.com”
Command Parameter
PS>
19. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 20
Aliases
• Explain them
• You may use aliases without even knowing it
• ls = dir = get-childitem
• Aliases can be identified easily
• Get-Alias will list all aliases
• Get-Alias -definition get-childitem will list all aliases for the identified cmdlet
• You can create custom aliases to help you perform tasks faster
• New-Alias show Get-ChildItem (adds an alias for get-childitem named show)
• create a PSConfiguration folder in your Windows PowerShell profile folder
• Get-Variable profile | Format-List will identify your profile folder and path
• Microsoft.PowerShell_profile.ps1
Key Concepts
What Are They, How Do I Know
20. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 21
Pipeline
• A pipeline is a series of commands connected by pipeline operators ‘ | ‘.
Each pipeline operator sends the results of the preceding command to the next
command.
• In a pipeline, the commands are processed from left to right in the order that they
appear. The processing is handled as a single operation and output is displayed as it is
generated.
• Piping works virtually everywhere in Windows PowerShell. Although you see text on the
screen, Windows PowerShell does not pipe text between commands. Instead, it pipes
objects.
• Objects, for those not familiar with the terminology, refers to items which contain multiple
attributes or properties; such as strings of characters, lists of information, and numerical
values. A good example of an object is a Windows process, retrieved using the Get-Process
cmdlet, which contains several properties indicating the executable name, priority, CPU
utilization, and memory usage.
• | symbol can take output from one command and used as input to next command strings
commands together
Key Concepts
Piping Commands
21. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 22
Pipeline
• get-service
• get-service s* | sort-object status –descending
• get-service s* | sort-object status –descending | out-file c:services.txt
• Get-ChildItem
• Get-ChildItem C:Test
• Get-ChildItem C:Test | Where-Object {$_.Extension -eq ".ps1"}
• Get-ChildItem C:Test | Where-Object {$_.Extension -eq ".ps1"} | where { ! $_.PSIsContainer }
• Get-ChildItem C:Test | Where-Object {$_.Extension -eq ".xml"} | where { ! $_.PSIsContainer } |
Sort-Object Length -descending
• Get-ChildItem C:Test | Where-Object {$_.Extension -eq ".xml"} | where { ! $_.PSIsContainer } |
Sort-Object Name
Key Concepts
Pipeline Examples
Get-Car Paint -Color Red Change -Part Tires 4 Add -Part Radio XM
Have a red car with 4
new tires and an XM
radio
22. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 23
Organizing Code
• Comments can be added and act as documentation
• Use # to comment out one line
• Prefix a multiline comment with <# and end the comment with #>
• Regions can be created to group code in logical sections
• Start the region with #region <region name>
• End the region with #endregion
Key Concepts
Regions and Comments
23. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 24
PowerShell Basics
Section Summary
Powershell Basics
1
Conditional Statements
An essential part of processes,
evaluating criteria is a foundation of
procedural code
2
Variables
An essential part of processes,
evaluating criteria is a foundation of
procedural code
3
Variable Types
An essential part of processes,
evaluating criteria is a foundation of
procedural code
4
CmdLet Output
An essential part of processes,
evaluating criteria is a foundation of
procedural code
5
If / Else If
An essential part of processes,
evaluating criteria is a foundation of
procedural code
6
Case / Switch
An essential part of processes,
evaluating criteria is a foundation of
procedural code
7
Dates
An essential part of processes,
evaluating criteria is a foundation of
procedural code
8
Strings
An essential part of processes,
evaluating criteria is a foundation of
procedural code
9
Files and Folders
An essential part of processes,
evaluating criteria is a foundation of
procedural code
10
Logging
An essential part of processes,
evaluating criteria is a foundation of
procedural code
11
Error Trapping
An essential part of processes,
evaluating criteria is a foundation of
procedural code
12
Cmd Line Execution
An essential part of processes,
evaluating criteria is a foundation of
procedural code
13
Functions
An essential part of processes,
evaluating criteria is a foundation of
procedural code
14
Script Includes
An essential part of processes,
evaluating criteria is a foundation of
procedural code
15
WhatIf
An essential part of processes,
evaluating criteria is a foundation of
procedural code
16
Cmd Line Switches
An essential part of processes,
evaluating criteria is a foundation of
procedural code
17
Brackets
An essential part of processes,
evaluating criteria is a foundation of
procedural code
18
Looping
An essential part of processes,
evaluating criteria is a foundation of
procedural code
24. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 25
Conditional Statements
• Statements can be concatenated together with
• -And,
• -Equal
• -Or
• See Appendix for full list of conditional and comparative evaluation options.
• List files with an extension of txt and are greater than 1MB in size
• Get-ChildItem C:Test | Where-Object {($_.Extension -eq ".ps1”) –And ($_.Length -gt 1MB}
• List processes that are related to internet browsing
• Get-Process | Where-Object {($_.Name -eq "iexplore") -or ($_.Name -eq "chrome") -or ($_.Name -eq
"firefox")}
Powershell Basics
Evaluating and Comparing
25. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 26
Variables
• Scope
• Global is public
• Script is internal
• Private is private
• Local is current stack level
• Numbered scopes are from 0..N where each step is up to stack level (and 0 is Local)
• Example
$test = 'Global Scope’
Function Foo {
$test = 'Function Scope'
Write-Host $Global:test # Global Scope
Write-Host $Local:test # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 0) # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 1) # Global Scope
}
Foo
Powershell Basics
Defining, Scope, and Use
26. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 27
Variable Data Types
Data Type Name Description
[Array] Array
[Bool] Value is TRUE or FALSE
[DateTime] Date and time
[Guid] Globally unique 32-byte identifier
[HashTable] Hash table, collection of key-value pairs
[Int32], [Int] 32-bit integers
[PsObject] PowerShell object
[Regex] Regular expression
[ScriptBlock] PowerShell script block
[Single], [Float] Floating point number
[String] String
[Switch] PowerShell switch parameter
[TimeSpan] Time interval
[XmlDocument] XML document
Powershell Basics
Data Type Explanation
• You don’t have to explicitly
declare the data type of a
variable.
• PowerShell automatically
chooses the data type for you
when you initialize the variable.
• The assignment isn’t always
correct
• Data type assignments can be
set systematically
• Example
• [Int]$Number
27. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 28
Variables
• No Data Type
• $Number = Read-Host "Please enter a number"
• $Square=$Number*$Number
• Write-Host "The square of the number $Number is $Square.”
• Result = 22
• Int Data Type
• [Int]$Number = Read-Host "Please enter a number"
• $Square=$Number*$Number
• Write-Host "The square of the number $Number is $Square.”
• Result = 4
• What is my data type?
• $Number.GetType().Name
Powershell Basics
Data Type Examples
28. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 29
Viewing Results
• Results of Cmdlets can be sent to other function, but also can be output to the screen, a grid,
a printer and a file
• Common Options are
• Output to screen
• Output to file
• Output to grid
• Examples will output the files in the c:test folder in alphabetical order.
• Output to Screen example
Get-ChildItem -Path C:test | Sort-Object -property name | Out-Host
• Output to File example
Get-ChildItem -Path C:test | Sort-Object -property name | Out-File -FilePath c:output.txt
• Output to File example
Get-ChildItem -Path C:test | Sort-Object -property name | Out-GridView
Powershell Basics
Screen, File, and GridView
29. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 30
If Else ElseIf
Syntax
if (condition)
{
commands_to_execute
}
elseif (condition2)
{
commands_to_execute
}
else
{
commands_to_execute
}
get-service | foreach-object
{
if ($_.status -eq "stopped")
{
write-host -f red $_.name $_.status
}`
else
{
write-host -f green $_.name $_.status
}
}
Powershell Basics
The Same Old If, ElseIf Statement
30. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 31
Switch Statements
Switch Example
Switch ($item)
{
value { expression }
value { expression }
}
Switch Parameters
-regex Treat the match clause, if a string, as a Regex
-wildcard Treat the match clause, if a string, as a wildcard string (?,*, [a-b], [ab])
-exact Match strings exactly
-casesensitive Modify the match clause, if a string, to be case sensitive
Powershell Basics
Switch = Case
31. Supercharge PBCS with PowerShell Slide 32Powershell Basics
Working With Date/Time
Although simple, the use of time and dates, and the
manipulation of the format, is something used
extremely frequently. From simple date time format,
to calculating effective week of the year and setting
substitution variables, the use of this can be
invaluable.
32. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 33
Working With Dates
Powershell Basics
Overview
Key
-date DateTime
By default, Get-Date returns the current system date and time.
The -date parameter allows you to specify
(usually via the pipeline) a specific date and time.
-displayHint DisplayHintType
Display only the Date, only the Time or the DateTime.
This does not affect the DateTime object that is retrieved.
-format string
Display the date and time in the .NET format
as indicated by String representing a format specifier.
-uFormat string
Display the date and time in Unix format.
-year -month -day -hour -minute –second
These allow you to set individual items to be displayed in place
of the current date/time. e.g. you could set the time to 12:00
CommonParameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction,
-WarningVariable, -OutBuffer -OutVariable.
Syntax
Get-Date [[-date] DateTime]
[-displayHint {Date | Time | DateTime}]
{[-format string] | [-uFormat string]}
[-year int] [-month int] [-day int] [-hour int]
[-minute int] [-second int] [CommonParameters]
33. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 34
Working With Dates
Powershell Basics
Get-Date Summary
• Get-Date returns the date
• -format provides formatting similar to excel
or any other programming language
Running
1. Get-Date
2. Get-Date -format yyyy_MM_dd_hh_mm_ss
3. Get-Date (Get-Date).AddDays(-1) -format d
4. Get-Date -format T
5. (Get-Date).Hour
6. (Get-Date).Day.Equals(15)
Produces
1. December 13, 2016 2:22:19 PM
2. 2016_12_13_02_22_19
3. 12/12/16
4. 2:22:19 PM
5. 14
6. False
34. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 35
Working With Dates
Date Time Stamping Files
$Logfile = "Z:OneDriveMacWorkReusable StuffPowershellSelect ColumnsResult_FilesLog_" +
(Get-Date (Get-Date).AddDays($Offset) -format yyyy_MM_dd_hh_mm_ss)
+ ".log”
Get Current Year
$Date = Get-Date (Get-Date).AddDays(-1) -format yy
"FY$Date"
Delete Files Older Than
function RemoveOldFiles{
param([string[]]$strFolders,[string]$Wildcard = "*",[int]$KeepDays = 15)
Foreach($s in $strFolders)
{
$FileCount = 0
$now = Get-Date
Get-ChildItem $s -include $Wildcard |
Where-Object {-not $_.PSIsContainer -and $now.Subtract($_.CreationTime).Days -gt $KeepDays -and
$_.CreationTime.day -ne 1 } | Remove-Item | LogLine $_.Name + " was deleted"
}
}
RemoveOldFiles @(path1,path2,path3) "*" 30
RemoveOldFiles –strFolders @(path1,path2,path3) --Wildcard "*" -KeepDays 30
Powershell Basics
Examples
36. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 37
Working with Files and Folders
Powershell Basics
Introduction
Regardless of the challenge, when working with
Planning, there is always a need to work with
files and folders. Whether it be loading data,
managing logs, or executing utilities, they all
integrate the use of folder structures and the
files in them. There are unlimited options and
a few concepts will be discussed to get you to
think about possible applications.
▪ Manipulating files ▪
▪ Renaming files ▪
▪ Searching files ▪
▪ Deleting and moving files ▪
▪ Dynamic references to folder structures ▪
37. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 38
Working with Files and Folders
• Listing Files
• Relative Paths
• Get-ChildItem $PSScriptRootsomedirectory
• If you are stuck on PowerShell 2 or below, you can use the following snippet instead, to get the same behavior:
• $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
• Renaming With Dates
• Getting file name only
• Get file extension only
• Get path without name
• Archiving and Purging Archives/Logs
• $script_path = $myinvocation.mycommand.path
$script_folder = Split-Path $script_path -Parent
$project_path = Split-Path $script_folder -Parent
$bindebug_path = Join-Path $project_path "bin/Debug"
$localdll = Join-Path $bindebug_path "MyProject.dll”
• $folderPath = Split-Path $file.fullname -parent
• $folder = Split-Path $folderPath -leaf
• Join-Path $MyInvocation.MyCommand.Path "../../bin/Debug"
• . ./
Powershell Basics
38. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 39
Logging Results
• PowerShell can record all or part of a PowerShell session to a text file using the Start-
Transcript CmdLet
• The transcript includes all command that the user types and all output that appears on the
console.
• Syntax
• Start-Transcript [[-Path] <String>] [-Append] [-Force] [-NoClobber] [-IncludeInvocationHeader] [-
WhatIf] [-Confirm] [<CommonParameters>]
• Start-Transcript [[-LiteralPath] <String>] [-Append] [-Force] [-NoClobber] [-
IncludeInvocationHeader] [-WhatIf] [-Confirm] [<CommonParameters>]
• Start-Transcript [[-OutputDirectory] <String>] [-Append] [-Force] [-NoClobber] [-
IncludeInvocationHeader] [-WhatIf] [-Confirm] [<CommonParameters>]
Powershell Basics
PowerShell Transcript Functions
39. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 40
Logging Results
• -Append
• Indicates that this cmdlet adds the new transcript to the end of an existing file. Use the Path parameter
to specify the file.
• -Confirm
• Prompts you for confirmation before running the cmdlet.
• -IncludeInvocationHeader
• Indicates that this cmdlet logs the time stamp when commands are run.
• -LiteralPath
• Specifies a location to the transcript file. Unlike the Path parameter, the value of the LiteralPath
parameter is used exactly as it is typed. No characters are interpreted as wildcards.
• -NoClobber
• Indicates that this cmdlet will not overwrite of an existing file. By default, if a transcript file exists in the
specified path, Start-Transcript overwrites the file without warning.
• -OutputDirectory
• Specifies a specific path and folder in which to save a transcript. Windows PowerShell automatically
assigns the transcript name.
• -Path
• Specifies a location to the transcript file. Enter a path to a .txt file. Wildcards are not permitted.
Powershell Basics
PowerShell Transcript Parameters
40. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 41
Logging Results
• If the results of the transcript cmdlet don’t meet the needs, custom logging can be created.
• Benefits of custom logging
• Produce more descriptive results
• Results are easier to read
• Results are easier to isolate errors
• Results are less technical and require very no expertise to digest
• Custom logging code
• There are an unlimited possibilities when implementing custom logging, but they typically consist
of
• A file with functions that can be referenced in any PowerShell script
• Functions like create file, write to the log file, log errors differently than success, email results/notify
administrator
Powershell Basics
Custom Logging
41. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 42
Logging Results
• Functions
• Example/usable functions file for logging
• Referencing functions file
• Setting parameters
• $directorypath = Split-Path $MyInvocation.MyCommand.Path
$incFunctions = $directorypath + "Logging_Functions.ps1"
logfile = $directorypath + "myoutput.log"
• Including functions into script
• use the . syntax to include the functions file
• . $incFunctions
• Function Example
• Log-Write -LogPath $logfile -LineValue "Why is everyone obsessed with hybrid! "
Powershell Basics
Custom Logging
Microsoft Word
Document
42. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 43
Error Trapping
There are several ways to manage errors, but the most effective is using the try/catch/finally functionality that exists in PowerShell
Try
{
active code
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-Output $ErrorMessage
Write-Output $FailedItem
Break
}
Finally
{
Write-Output “Finished”
}
Powershell Basics
Active code is executed in the try area
Error trapping exists in the catch area. Any error is handled here. Catch or i
43. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 44
Executing Command Line / Applications
As with other needs, there are a number of ways to execute external applications
• Preface the command with an ampersand
& <path> <args>
• Use the Start-Process cmdlet and gain some critical functionality
• Gain access to return codes
• Have the option to run multiple processes or wait to run asynchronously
• Control whether the window is visible or hidden
• Redirect results and errors to predefined files
• Have access to file type verbs (print a text file)
Start-Process cmdlet
• $p = Start-Process -FilePath <path> -ArgumentList <args> -Wait -NoNewWindow –PassThru
• $p.ExitCode
Powershell Basics
44. Supercharge PBCS with PowerShell Slide 45Powershell Basics
Looping
PowerShell maintains the usual looping functions.
Understanding how they work and their parameters
will improve the efficiency and use of these objects.
45. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 46
Functions
• Functions is as group of code that can be executed in a group by calling the name of the function.
• Reusable code is a great opportunity to create a function
• Functions can accept parameters
• Functions can return values
function CheckFileExistance{
param(string[]$strPath,
[string[]]$strFiles)
Foreach($s in $strFiles)
{
if(!(Test-Path -Path $strPath$s ))
{
Write-Host "$s is not available"
$ReturnValue = 1
}
else
{
$ReturnValue = 0
}
}
Return $ReturnValue
}
Powershell Basics
Overview
Parameters – one path and an
array of files
Function name
If file does NOT exist
If file exists
46. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 47
Referencing External PowerShell Scripts
• Why
• Migration
• Common Functions
• Environment Specific Variables
• How
• Any reference to an external PowerShell script file should be prefixed with a period
• . ”pathfilename.ps1"
• Real world examples discussion
Powershell Basics
47. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 48
WhatIf
Powershell Basics
Measure Twice, Cut Once
• Many PowerShell scripts are destructive
• It is time consuming to mirror a separate environment, or duplicate folders, for testing
• Almost any command can be executed without action by using the –WhatIf parameter
• -WhatIf will execute the operation and display what would have happened if the –WhatIf parameter was not used
• Get-ChildItem -Path C:test | Remove-Item -Recurse -WhatIf
• What if: Performing the operation "Remove Directory" on target "C:testConcat".
• What if: Performing the operation "Remove File" on target "C:testArchive.zip".
• What if: Performing the operation "Remove File" on target "C:testemployee.txt".
• Get-ChildItem -Path C:test | Where-Object {-Not $_.PSIsContainer} | Remove-Item -Recurse -WhatIf
48. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 49
Command Line Switches
Any PowerShell file can have switches in the parameters that can be used to accept boolean variables to turn on and off specific
sections of the code. In this example, one PowerShell file has all all the processes to run an entire daily process. Each one of these
switches can be turned on or off from the command line
param([switch]$Backup = $false,
[switch]$loadTime = $false,
[switch]$loadFinance = $false,
[switch]$setVariables = $false,
[switch]$exportData = $false,
[string]$ProdcessName,
[switch]$CleanUp = $false,
[switch]$importTimeMetadata = $false,
[switch]$importFinanceMetadata = $false
)
if($Backup.IsPresent){ code }
if($setVariables.IsPresent){ code }
• Execution (all processes)
• PowerShell -Command "& './filename.ps1' -Backup -setVariables -exportData -importFinanceMetadata -loadFinance -ProcessName
'Finance Full Run'"
• Execution (backup only)
• PowerShell -Command "& './filename.ps1' -Backup -setVariables
Powershell Basics
49. Supercharge PBCS with PowerShell Slide 50Powershell Basics
() {} []
Lions, Tigers, and Brackets, OH MY!
Demystify the confusion around brackets
50. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 51
Braces, Parenthesis, And ScriptBlocks
• braces and parenthesis
• In PowerShell, braces enclose code that is NOT immediately executed.
• Parenthesis, in contrast, enclose code that IS immediately executed.
• $a = (Get-Process) = produces results
$b = {Get-Process} = produces the text
• When Use Braces, When Parenthesis?
• Which raises the question: why use parenthesis at all?
• Parenthesis are needed when it is not clear to PowerShell which statement should run first.
• So parenthesis are not needed at all if your script code goes step by step. Parenthesis are
needed, though, once you start putting more than one expression into one line.
• Ambiguous Code
• Get–Random –InputObject 1..49 –Count 6 [produces “1..49”]
• Get–Random –InputObject (1..49) –Count 6 [produces 6 random values]
Powershell Basics
Explaining the purpose and use of bracket types
51. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 52
Braces, Parenthesis, And ScriptBlocks
• Braces: Transport Containers For Code
• Braces, in contrast, are specialized "transport containers" for PowerShell code. Whatever you put in braces will not
immediately execute, but instead can be handed over to a parameter, or stored in a variable. Code in braces is
called a "Scriptblock".
• $condition = { $_.Length -gt 1MB }
• Get-ChildItem -Path c:windows | Where-Object -FilterScript $condition
• The code doesn’t get execubed in line 1, but in line 2
• Deferred Execution
• You can run scriptblocks manually, too. So if you wanted, you can place code into a scriptblock and run it whenever
you need to:
• $code = {
$time = Get-Date
$hour = $time.Hour
$minute = $time.Minute
$seconds = $time.Second
$speaker = New-Object -ComObject Sapi.SpVoice
$null = $speaker.Speak("It is now $hour $minute and $seconds seconds.")
}
• & $code
Start-Sleep -Seconds 4
& $code
• You often see script blocks in if statements, loops, and functions
Powershell Basics
Explaining the purpose and use of bracket types
52. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 53
Braces, Parenthesis, And ScriptBlocks
• What About Parameters?
• If PowerShell functions and scriptblocks are the same, what about parameters?
• The truth is: parameter support is built into scriptblocks, not functions. So when you use
functions with parameters, functions simply use the parameter mechanism built into its
scriptblock.
• function Say-Something
{
param
(
[Parameter(Mandatory=$true)]
$Text
)
$speaker = New-Object -ComObject Sapi.SpVoice
$null = $speaker.Speak($Text)
}
• Say-Something -Text 'Hello'
Powershell Basics
Explaining the purpose and use of bracket types
53. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 54
Looping
• ForEach-Object
• ForEach-Object requires only an object to be looped through and a script block containing the
commands to be performed on each member of the object.
• These parameters can be specified either by the -InputObject and -Process parameter names, or
by piping the object to the ForEach-Object cmdlet and placing the script block as the first
parameter. To illustrate this basic syntax the following example shows two methods of using
ForEach-Object to loop through the contents of a user's Documents folder:
• The -Begin and -End parameters can be used to define script blocks to execute just before or after
the contents of the -Process script block
• Execution
• $myDocuments = Get-ChildItem $env:USERPROFILEDocuments –File
• $myDocuments | ForEach-Object {$_.FullName}
• ForEach-Object -InputObject $myDocuments -Process {$_.FullName}
Powershell Basics
ForEach-Object
54. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 55
Looping
• For loops are typically used to iterate through a set of commands a specified number of
times, either to step through an array or object, or just to repeat the same block of code as
needed. A For loop is constructed by setting the value of a variable when entering the loop,
the condition on which the loop should be terminated, and an action to be performed
against that variable each time through the loop.
• Execution
• For ($i=0; $i -le 10; $i++) {
"10 * $i = " + (10 * $i)
}
• $colors = @("Red","Orange","Yellow","Green","Blue","Indigo","Violet")
For ($i=0; $i -lt $colors.Length; $i++) {
$colors[$i]
}
Powershell Basics
For
55. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 56
Looping
• A third type of loop that PowerShell supports involves setting a condition which either allows the loop to
process as long as the condition is true or until it is met. While and Do-While loops are both used to perform
an action while the condition evaluates to $true, and differ only in their syntax. Do-Until loops have similar
syntax to Do-While, but stop processing once the condition statement is met.
• Do While Execution
• $i=1
Do {
$i
$i++
}
While ($i -le 10)
• Do Until Execution
• $i=1
Do {
$i
$i++
}
Until ($i -gt 10)
Powershell Basics
While, Do-While, and Do-Until Loops
56. Query CSV Files
Perform SQL functionality on delimited files without a
relational database
Update LCM Extracts
Remove a dimension from the form definition files to
easily migrate
57. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 58
Querying CSV files
Advanced Topics
Manipulating Small Delimited Files Without a Relational Application
• Easy to query and alter delimited files
• Similar functions to any relational tool
• Query
• Remove / Add logical fields
• Grouping
• Filtering
• Great for small files where relational
integration would create complexity
• Not so good for files that have millions of
records
59. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 60
Update LCM Extracts
$lcmSourceDir = "Z:DownloadsKG04HP-SanPlanresourceGlobal ArtifactsComposite Forms"
$dimName = "CustomerSegment"
# List all files
$files = Get-ChildItem $lcmSourceDir -Recurse | where {$_.Attributes -notmatch 'Directory'} |
# Remove CustomerSegment
Foreach-Object
{
# Reset a counter to 0 - used later when files is saved
$fileCount = 0
[xml][/xml]$xml = Get-Content $_.FullName
$node = $xml.SelectNodes("//sharedDimension") | Where-Object {$_.dimension -eq $dimName} |
ForEach-Object
{
#Increase the counter for each file that matches the criteria
$fileCount++
# Remove each node from its parent
[void][/void]$_.ParentNode.RemoveChild($_)
}
# If the dimension was found in the file, save the updated contents.
if($fileCount -ge 1)
{
$xml.save($_.FullName)
Write-Host "$_.FullName updated."
}
}
http://www.in2hyperion.com/2016/12/10/remove-dimensions-from-planning-lcm-extracts/
Advanced Topics
Remove a dimension from all Form Definition Extracts
60. POWERSHELL OVERVIEW
PowerShell is a powerful utility for all
kinds of functional purposes, including
system automation.
01 Calling EPM Automate
02
Login, update variable, and execute
calculation
03
Responding to Return Codes04
Create Variables
05 Logging Results
PBCS INTEGRATION
Running the PBCS Utility through
PowerShell invokes all kinds of benefits,
including monitoring results, logging
results, sending emails, and responding
to critical failures.
61. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 62
Calling EPM Automate
• There are still limitations on what can be automated, but the list is getting smaller
• Command line application
• Can be installed on UNIX or Windows
• Not exclusive of Planning – used for all cloud applications
PBCS Integration
EPMAutomate Command Value 1 …
Epmautomate downloadfile "[FILE_PATH]/FILE_NAME"
Command Parameters
Value n
62. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 63
Basic Commands
• Setting common strings will reduce code, complexity, errors, and make life easier when
migrating between environments
$PBCS_URL = "https://planning-a17871.pbcs.us2.oraclecloud.com"
$PBCS_Domain = "a17871"
$PBCS_UserId = "kgoodfriend@huronconsultinggroup.com"
$PBCS_UserPw = ”HideMe!"
$EPMAutomate_Path = "C:OracleEPM Automatebin"
if ($PBCS_URL -like '*test*')
{
$SysEnvironment = "Test"
}
else
{
$SysEnvironment = "Production"
}
PBCS Integration
Setting Variables
64. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 65
Basic Commands
function EPMA_RunCalc{
param([string]$strBusRule,[string[]]$strVariables)
LogLine "Running Business Rule $strBusRule"
$CmdLine = "runbusinessrule `"$strBusRule`""
#Loop through variables
if($strVariables.count -gt 0)
{
Foreach($v in $strVariables)
{
LogLine " VAR: $v"
$CmdLine = "$CmdLine `"$v`""
}
}
else
{
LogLine " No Variables Present"
}
$ReturnCode = Start-Process "$EPMAutomate_Pathepmautomate.bat" $CmdLine -Wait -passthru -WindowStyle $ShowDosWindow
LogResult "Executing Business Rule" $ReturnCode.ExitCode
LogLine "Finished Business Rule $strBusRule" 1
Return $ReturnCode.ExitCode
}
PBCS Integration
Supporting Function
65. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 66
Getting/Responding to Return Codes
PBCS Integration
Dealing With Results Returned by External Processes
Start-Process [-FilePath] <String> [[-ArgumentList] <String[]>]
[-Credential <PSCredential>] [-WorkingDirectory <String>]
[-LoadUserProfile] [-NoNewWindow] [-PassThru]
[-RedirectStandardError <String>] [-RedirectStandardInput <String>]
[-RedirectStandardOutput <String>]
[-WindowStyle <ProcessWindowStyle>] [-Wait] [-UseNewEnvironment]
[<CommonParameters>]
Executing EPMAutomate returns codes (less than 20) that can be helpful in determining if the EPMAutomate command was successful, and if it failed, why.
Some of the errors are general, but most can be acted on.
There are several methods to get return codes, and this is my preference
The Script
$ReturnCode = Start-Process external “program" “program parameters” -Wait -passthru -WindowStyle $ShowDosWindow
Additional Reference
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/start-process
66. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 67
Logging Results
• Logging and communicating process information
• Builds trust
• Reduces time to identify and resolve the root cause
• Can be used to act without interaction
• Creating functions to repeat the process can improve development time
PBCS Integration
Dealing With Results Returned by External Processes
67. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 68
Logging Results
PBCS Integration
Reusable Functions
PowerShell Script
LogHeader "Running for $Process_Name in $SysEnvironment".Replace("_${DateStamp}","")
LogLine "Logging in"
$CmdLine = "login $PBCS_UserId $PBCS_UserPw $PBCS_URL $PBCS_Domain"
$ReturnCode = Start-Process "$EPMAutomate_Pathepmautomate.bat" $CmdLine -Wait -passthru -WindowStyle $ShowDosWindow
LogResult "Login" $ReturnCode.ExitCode
if( $ReturnResult -eq 1){Send_Email_Error;Exit}
Log Results
###########################################
# Running for Time Full Run in Production #
###########################################
2016 09 08 @ 09:20:21 | Logging in
2016 09 08 @ 09:20:23 | COMMAND: login kgoodfriend@huronconsultinggroup.com Pas1234
https://planning-a17871.pbcs.us2.oraclecloud.com a17871
2016 09 08 @ 09:20:23 | Login finished successfully
68. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 69
Logging Results
Function LogHeader([string]$strValue){
Add-content $Logfile -value ""
$Line1 = "#" * ($strValue.length + 4)
$Line2 = "# $strValue #"
Add-content $Logfile -value $Line1
Add-content $Logfile -value $Line2
Add-content $Logfile -value $Line1
}
PBCS Integration
Examples
Function LogLine([string]$strValue,[int64]$iDivider = 0,[int64]$iIndent = 5){
$iIndent = 5
$NowStamp = get-date -uformat "%Y %m %d @ %H:%M:%S"
Add-content $Logfile -value ("${NowStamp} | ".PadRight(${iIndent} +
"${NowStamp} | ".length) + "${strValue}")
Write-Host ("${NowStamp} | ".PadRight(${iIndent} + "${NowStamp} | ".length) +
"${strValue}")
for ($i=1; $i -le $iDivider; $i++)
{
Add-content $Logfile -value ""
}
}
Function Purpose
LogHeader is used to break up sections of code sets
LogLine is used to write something to the log, with the ability to pad the text with additional blank lines
LogResult is used to write out the command sent to EPMAutomate that can be used to manually run tasks and troubleshoot issues, and
log the result of the command (success or failure)
Functions
70. WORKING EXAMPLES
Now, we are ready to walk through some
working code that you can take back and use
immediately.
03
Updating Delimited Files
02
Purging Files
01
Archiving/Zipping Files
71. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 72
Archiving Files
Working Examples
Archive and Date/Time Stamp
Useful Information
• Only available in version 5 or greater
• It is always a good idea to confirm the zip file being created doesn’t exist
and delete/overwrite if it does
• Compress-Archive can take a file, single path, or an array of any
combination
• Can be combined to exclude specific files using Get-ChildItem
• Get-ChildItem –Path $ListOfFolders –Exclude *.zip | Compress-Archive
-DestinationPath –DestinationPath
"${Script_Archive_Path}${Process_Name}_Archive.zip"
Compress-Archive [-Path] String[] [-DestinationPath] String
[-CompressionLevel String ] [-Update] [-Confirm] [-WhatIf]
Path: Path or paths of files to be compressed
CompressionLevel: Fastest, NoCompression, or Optimal
DestinationPath: The path of the zip being used to add files
Update: Replace older files with new files if they exist
Confirm: Prompt for confirmation before executing
WhatIf: Describes what would happen if executed
When daily processes are created and executed, it is helpful to maintain a history of the process, including logs, data files, backups, scripts, and other artifacts
involved in the process.
If you have done this in VBScript or DOS, the following will be a welcome change in simplicity. The following script will zip all the files in the specified paths
and date and time stamp the archive file.
The Script
$DateStamp = get-date -format "yyyyMMdd_HH-mm”
$Process_Name = (Get-Item $PSCommandPath ).Basename -replace "_"," "
$Process_Name = "${ProcessName}_${DateStamp}”
$ListOfFolders = @($Script_Backup_Path,$Script_Log_Path,$PathOfMetaDataFiles,$PathOfDataFiles,$Script_BackupData_Path,$Script_Path)
Compress-Archive -Path $ListOfFolders -CompressionLevel Optimal -DestinationPath "${Script_Archive_Path}${Process_Name}_Archive.zip"
72. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 73
Purging Files
Working Examples
Local Sets of Files Is Beneficial – To A Point
Remove-Item [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-Force]
Confirm: Prompts you for confirmation before running the cmdlet.
Path: Path or paths of files to be compressed
Exclude: Specifies items that this cmdlet omits. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt.
Wildcard characters are permitted.
Include: Specifies items to delete. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt.
Force: Forces the cmdlet to remove items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables
Keeping historical logs, data, processes, and a number of other files is valuable, but there is a point where the volume of them is not beneficial. For that
reason, most of the environments I set up institute a script that purges files older than a preset number of days. Sometimes this is days, sometimes months,
and in some instances, I have ignored quarterly or finally monthly logs.
The Script
$limit = (Get-Date).AddDays(-15)
$path = "C:SomePath”
Get-ChildItem -Path $path | Where-Object {-Not $_.PSIsContainer -and $_.CreationTime -lt $limit} | Remove-Item -Recurse
73. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 74
Updating Delimited Files
• Many source files have a need to be changed, and sometimes eliminating the complexity of
maintaining a relational environment and additional expertise is beneficial, if not a
requirement. PowerShell includes simple language that can query, delete or add columns,
group data, and filter data.
• Files can merge columns similar to joins in relational databases
Working Examples
Delimited Files Can Be Manipulated Without SQL
74. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 75
Functions for common/repetitive operations
• not case sensitive!
• most nouns are singular (service, not services)
• run as administrator
• get-help
• get-help , then tab and it will autofill• get-help get-service
Suggested Practices
75. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 76
Split Functions and Variables for Migration Efficiency
• Have common passwords and environment specific things in one file
• Have common functions in one file
• Wrapper execution that uses the first two
Tips
Code used to
automate
tasks
Name: Variables.ps1
Variables used in the Code file – passwords,
paths, environment specific strings
Name: Function.ps1
Functions referenced in the Code file –
normally processes that are reused
76. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 77
Stay In Touch
• Email
• In2Hyperion@gmail.com
• Kyle.Goodfriend@Gmail.com
• In2Hyperion
• Sign up for email updates at www.In2Hyperion.com
• Follow us via Twitter (@In2Hyperion)
• Like us on Facebook
• Join the In2Hyperion LinkedIn group
• More than 2,000 people follow In2Hyperion through social media
• More than 3,000 people visit In2hyperion daily
Closure
77. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 78
Other Collateral
• Collaborate 2011 – Business Presentation
• Download Presentation
• Kscope12 – Unlimited Custom Spreads
• Download Presentation
• OAUG Insight - Summer 2012 issue
• Download Article at ODTUG.com
• Request a copy by emailing me at
in2hyperion@gmail.com
Closure
80. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 81
Operator Summary
The Arithmetic Operators
• + (add), - (subtract), * (multiply), / (divide), and % (modulus, or division remainder).
Assignment Operators
• =, which sets a variable or object property to a value. There are some other assignment operators as well: +=, -=, *=,
/=, %=, ++, and --
The Comparison Operators
• Equality
• equal (-eq), not equal (-ne), greater than (-gt), greater than or equal (-ge), less than (-lt), and less than or equal (-le). -like, -
notlike, -match, and –notmatch
• Containment operators
• -contains and –notcontains
• Replace operator
• "The rain in Seattle" -replace "rain","hail”
• Split and Join Operators
• -split and –join
• Logical Operators
• -and, -or, -xor, -not, and !
• Type Operators
• -is and –isnot
Appendix
1 of 3
81. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 82
Operator Summary
Appendix
2 of 3 (Redirect Operators)
Operator Description Available In
> Redirects standard (non-error) output to a file All PowerShell versions
>> Redirects output and appends it to a file All PowerShell versions
2> Redirects error output to a file All PowerShell versions
2>> Redirects error output and appends it to a file All PowerShell versions
2>&1 Redirects error output to the same location as standard output All PowerShell versions
3> Redirects warning output to a file PowerShell 3.0 and later
3>> Redirects warning output and appends it to a file PowerShell 3.0 and later
4> Redirects verbose output to a file PowerShell 3.0 and later
4>> Redirects verbose output and appends it to a file PowerShell 3.0 and later
5> Redirects debug output to a file PowerShell 3.0 and later
5>> Redirects debug output and appends it to a file PowerShell 3.0 and later
n>&1
Redirects warning (n = 3), verbose (n = 4), or debug (n = 5) output to the same
location as standard output
PowerShell 3.0 and later
*> Redirects all output streams (standard, errorwarning, verbose, and debug) to a file PowerShell 3.0 and later
*>> Redirects all output streams and appends them to a file PowerShell 3.0 and later
82. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 83
Operator Summary
Special Operators
• invocation (&) operator to run an external program
• dot sourcing (.) operator to reference external powershell script and keep variables in scope
subexpression operator
The $( ) operator causes PowerShell to evaluate the expression in between the $( and the )
characters. This operator is helpful when you want to force PowerShell to evaluate an expression
inside a quoted string, such as when you want to get an object's property. For example, suppose you
have a variable $myString that contains the string "KenDyer". The expression "$myString is
$myString.Length characters long” will output "KenDyer is KenDyer.Length characters long", which is
probably not what you intended. To solve this, you can use the $( ) operator to get the desired result.
In this example, the expression "$myString is $($myString.Length) characters long"
will output the result you were probably expecting ("KenDyer is 7 characters long").
array subexpression operator
The @( ) operator is useful when you have some data (such as an object property or the output of a
function or method) that might be empty, a single value, or an array. For example, an Active Directory
(AD) group might have no members, a single member, or multiple members. The subexpression
operator coerces the data into an array to make processing easier.
Appendix
3 of 3
83. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 84
Logical Summary
Appendix
Evaluating
Operator Description
-eq Equal
-ne Not equal
-ge Greater than or equal
-gt Greater than
-lt Less than
-le Less than or equal
-like Wildcard comparison
-notlike Wildcard comparison
-match Regular expression comparison
-notmatch Regular expression comparison
-replace Replace operator
-contains Containment operator
-notcontains Containment operator
-shl Shift bits left (PowerShell 3.0)
-shr Shift bits right – preserves sign for signed values.(PowerShell 3.0)
-in Like –contains, but with the operands reversed.(PowerShell 3.0)
-notin Like –notcontains, but with the operands reversed.(PowerShell 3.0)
85. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 86
Working With Dates
Appendix
Formatting Options
Specifier Format Sample Output
d ShortDatePattern 8/30/2007
D LongDatePattern Thursday, August 30, 2007
f Full date and time (long date and short time) Thursday, August 30, 20
F FullDateTimePattern (long date and long time) Thursday, August 30, 2007 11:19:59 AM
g General (short date and short time) 8/30/2007 11:20 AM
G General (short date and long time) 8/30/2007 11:20:24 AM
m, M MonthDayPattern August 30
o Round-trip date/time pattern [Text]
2007-08-30T11:18:49.0312500-07:00 RFC1123Pattern Thu, 30 Aug 2007 11:21:36 GMT
s
SortableDateTimePattern (based on ISO 8601)
using local time
2007-08-30T11:20:36
t ShortTimePattern 11:20 AM
T LongTimePattern 11:20:42 AM
u
UniversalSortableDateTimePattern using the
format for universal time display
2007-08-30 11:21:50Z
U
Full date and time (long date and long time) using
universal time
Thursday, August 30, 2007 6:21:52 PM
y, Y YearMonthPattern August, 2007
86. Kyle Goodfriend
614.668.7324
Supercharge PBCS with PowerShell Slide 87
Working With Dates
Appendix
Formatting Options
Specifier Description
d. %d The day of the month. Single-digit days will not have a leading zero. Specify "%d" if the format pattern is not combined with other format patterns.
dd The day of the month. Single-digit days will have a leading zero.
ddd The abbreviated name of the day of the week.
dddd The full name of the day of the week, as defined in DayNames.
h, %h The hour in a 12-hour clock. Single-digit hours will not have a leading zero. Specify "%h" if the format pattern is not combined with other format patterns.
hh The hour in a 12-hour clock. Single-digit hours will have a leading zero.
H, %H The hour in a 24-hour clock. Single-digit hours will not have a leading zero. Specify "%H" if the format pattern is not combined with other format patterns.
HH The hour in a 24-hour clock. Single-digit hours will have a leading zero.
m, %m The minute. Single-digit minutes will not have a leading zero. Specify "%m" if the format pattern is not combined with other format patterns.
mm The minute. Single-digit minutes will have a leading zero.
M, %M The numeric month. Single-digit months will not have a leading zero. Specify "%M" if the format pattern is not combined with other format patterns.
MM The numeric month. Single-digit months will have a leading zero.
MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames.
MMMM The full name of the month, as defined in MonthNames.
s, %s The second. Single-digit seconds will not have a leading zero. Specify "%s" if the format pattern is not combined with other format patterns.
ss The second. Single-digit seconds will have a leading zero.
t, %t The first character in the AM/PM designator defined in AMDesignator or PMDesignator, if any. Specify "%t" if the format pattern is not combined with other format patterns.
tt The AM/PM designator defined in AMDesignator or PMDesignator, if any.
y, %y
The year without the century. If the year without the century is less than 10, the year is displayed with no leading zero. Specify "%y" if the format pattern is not combined with other format
patterns.
yy The year without the century. If the year without the century is less than 10, the year is displayed with a leading zero.
yyy The year in three digits. If the year is less than 100, the year is displayed with a leading zero.
yyyy
The year in four or five digits (depending on the calendar used), including the century. Will pad with leading zeroes to get four digits. Thai Buddhist and Korean calendars both have five digit years;
users selecting the "yyyy" pattern will see all five digits without leading zeros for calendars that have five digits. Exception: the Japanese and Taiwan calendars always behave as if "yy" was selected.
%c
Where c is a format pattern if used alone. That is, to use format pattern "d", "f", "F", "h", "m", "s", "t", "y", "z", "H", or "M" by itself, specify "%d", "%f", "%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H",
or "%M". The "%" character can be omitted if the format pattern is combined with literal characters or other format patterns.
c Where c is any character. Displays the character literally. To display the backslash character, use "".