├── .gitignore
├── README.md
├── cmdlets
├── acl
│ └── add-rule.ps1
├── childItem
│ ├── filter-il.ps1
│ └── get
│ │ └── include
│ │ └── cast-to-string.ps1
├── command
│ ├── get
│ │ ├── DLL.ps1
│ │ └── type.ps1
│ ├── invoke
│ │ ├── argumentList.ps1
│ │ └── script-block.ps1
│ └── measure
│ │ └── pipeline.ps1
├── content
│ ├── get
│ │ ├── data.xml
│ │ ├── every-nth-line-max.ps1
│ │ ├── every-nth-line.ps1
│ │ ├── file.txt
│ │ ├── function.ps1
│ │ ├── hexString.ps1
│ │ ├── lines.txt
│ │ ├── read-xml.ps1
│ │ ├── readCount-totalCount-byte-array.ps1
│ │ └── variable.ps1
│ ├── inplace-editing.ps1
│ ├── set
│ │ ├── .gitignore
│ │ ├── set-stream-Zone.Identifier.ps1
│ │ ├── unix-vs-dos.ps1
│ │ └── write-file.ps1
│ └── some.text.orig
├── counter
│ └── get
│ │ └── all-counters.ps1
├── credential
│ └── get
│ │ └── img
│ │ └── basic.png
├── csv
│ └── convertTo
│ │ └── processes.ps1
├── culture
│ └── get
│ │ └── KeyboardLayoutId.ps1
├── custom
│ └── format
│ │ └── simple.ps1
├── date
│ └── get
│ │ ├── add-explicit.ps1
│ │ ├── add-implicit.ps1
│ │ ├── basic.ps1
│ │ └── format.ps1
├── default
│ └── out
│ │ └── overriding
│ │ ├── out-default.ps1
│ │ ├── pipeline.ps1
│ │ └── rm-out-default.ps1
├── expression
│ └── invoke
│ │ ├── an-expression.txt
│ │ ├── apply-on-array-elements.ps1
│ │ ├── commands.ps1
│ │ ├── eval.ps1
│ │ ├── get-content.ps1
│ │ ├── multiline.ps1
│ │ ├── pipe-into
│ │ ├── expression.txt
│ │ └── pipeline.ps1
│ │ └── source.ps1
├── file
│ ├── out
│ │ ├── .gitignore
│ │ ├── append.ps1
│ │ ├── noNewLine-pipeline.ps1
│ │ └── write-file.ps1
│ └── unblock
│ │ ├── after.png
│ │ └── before.png
├── fileHash
│ └── get
│ │ ├── calculate-hash.ps1
│ │ └── xyz.txt
├── gridView
│ └── out
│ │ ├── array-psCustomObjects.ps1
│ │ ├── array.ps1
│ │ └── img
│ │ ├── array-psCustomObjects.png
│ │ └── array.png
├── host
│ └── write
│ │ ├── color.ps1
│ │ ├── img
│ │ └── color.png
│ │ ├── pipeline.ps1
│ │ ├── vs-string-use.ps1
│ │ └── vs-string.ps1
├── item
│ ├── copy
│ │ └── create-backups.ps1
│ ├── new
│ │ ├── .gitignore
│ │ ├── create-directory.ps1
│ │ └── type-file.ps1
│ └── remove
│ │ └── literalPath.ps1
├── itemProperty
│ ├── get
│ │ └── data-type.ps1
│ ├── remove
│ │ └── registry-value.ps1
│ └── set
│ │ ├── .gitignore
│ │ ├── img
│ │ └── registry-value.png
│ │ ├── registry-value.ps1
│ │ └── touch.ps1
├── job
│ ├── receive
│ │ └── show-result.ps1
│ └── start
│ │ ├── current-directory.ps1
│ │ └── pass-variable.ps1
├── json
│ ├── convertFrom
│ │ └── basic.ps1
│ └── convertTo
│ │ └── basic.ps1
├── member
│ └── add
│ │ ├── access-members-by-variable.ps1
│ │ ├── obj.ps1
│ │ └── scriptMethod.ps1
├── new-object.ps1
├── object
│ ├── compare
│ │ ├── compare-directory-structure.ps1
│ │ ├── dir-one
│ │ │ ├── subdir-A
│ │ │ │ ├── in-both_differing-content.txt
│ │ │ │ └── only-in-dir-one.txt
│ │ │ └── subdir-B
│ │ │ │ └── file-x
│ │ ├── dir-two
│ │ │ ├── subdir-A
│ │ │ │ ├── in-both_differing-content.txt
│ │ │ │ └── only-in-dir-two.txt
│ │ │ └── subdir-C
│ │ │ │ └── file-x
│ │ ├── psObjects.ps1
│ │ └── string-arrays.ps1
│ ├── forEach
│ │ └── script-block.ps1
│ ├── group
│ │ ├── asHashTable.ps1
│ │ ├── data.csv
│ │ └── group-then-print-objects.ps1
│ ├── measure
│ │ ├── int-array.ps1
│ │ ├── max-length.ps1
│ │ ├── property-scriptBlock.ps1
│ │ └── property.ps1
│ ├── new
│ │ ├── COM
│ │ │ └── img
│ │ │ │ ├── fso.png
│ │ │ │ └── xls.png
│ │ ├── cs-class
│ │ │ ├── .gitignore
│ │ │ └── obj.cs
│ │ ├── inline-c-sharp.ps1
│ │ ├── property-dotNet.ps1
│ │ ├── property-ps.ps1
│ │ └── psObject
│ │ │ └── hash-like-object.ps1
│ └── select
│ │ ├── calculated.ps1
│ │ ├── expandProperty-ary.ps1
│ │ ├── expandProperty-obj.ps1
│ │ └── expandProperty.ps1
├── odbcDsn
│ └── add
│ │ ├── Oracle.ps1
│ │ └── img
│ │ └── Oracle.png
├── output
│ └── write
│ │ └── noEnumerate.ps1
├── path
│ ├── resolve
│ │ └── force.ps1
│ ├── split
│ │ └── go.ps1
│ └── test
│ │ ├── IO.File.Exists.ps1
│ │ ├── create-directory-if-it-does-not-exist.ps1
│ │ └── pathType.ps1
├── progress
│ ├── img
│ │ └── write.png
│ └── write.ps1
├── scheduledTask
│ └── get
│ │ └── tasks-and-actions.ps1
├── set-executionPolicy.ps1
├── strictMode
│ └── set
│ │ ├── off.ps1
│ │ ├── version-1.ps1
│ │ ├── version-2.ps1
│ │ └── version-3.ps1
├── string
│ └── select
│ │ ├── get-winEvent_inputObject.ps1
│ │ ├── grep-recursively.ps1
│ │ ├── psCustomObject.ps1
│ │ ├── string-array.ps1
│ │ └── strings
│ │ ├── strings.ps1
│ │ └── text
├── stringData
│ └── convertFrom
│ │ └── multiLine.ps1
├── table
│ └── format
│ │ └── generate-objects-for-x-ms.ps1
├── type
│ └── add
│ │ ├── WinApi.ps1
│ │ ├── create-assembly
│ │ ├── .gitignore
│ │ ├── aClass.cs
│ │ ├── compile-useAssembly.ps1
│ │ ├── create-assembly.ps1
│ │ ├── did-not-work.ps1
│ │ ├── use-assembly.ps1
│ │ └── useAssembly.cs
│ │ ├── img
│ │ └── WinApi.png
│ │ ├── inline.ps1
│ │ └── tq84_type.cs
├── verbose
│ └── write
│ │ ├── preference-variable.ps1
│ │ └── verbose-parameter.ps1
├── webRequest
│ └── invoke
│ │ ├── deal-with-unsuccessful-requests.ps1
│ │ └── desktop-vs-core.ps1
├── write-host.ps1
└── xml
│ └── select
│ └── XPath
│ └── simple.ps1
├── encoding
├── script-latin1.ps1
├── script-utf8-bom.ps1
└── script-utf8.ps1
├── examples
├── Problem-Ejecting-USB-Mass-Storage-Device
│ ├── img
│ │ ├── eventVwr_filter-current-log.png
│ │ └── msgBox.png
│ └── readEventLog.ps1
├── WinAPI
│ ├── ExtractStringFromDLL.ps1
│ ├── SendMessage.ps1
│ ├── Shell32
│ │ └── Extract
│ │ │ ├── .gitignore
│ │ │ ├── Shell32_Extract.ps1
│ │ │ ├── User32_DestroyIcon.ps1
│ │ │ ├── create-html-with-icons-of-dll.ps1
│ │ │ └── go.ps1
│ └── setMouseSpeed.ps1
├── message-box
│ ├── img
│ │ └── user32-MessageBox.png
│ └── user32-MessageBox.ps1
└── registry
│ ├── add-another-value.ps1
│ ├── add-value-num.ps1
│ ├── add-value-txt.ps1
│ ├── all.ps1
│ ├── check-if-key-or-value-exists.ps1
│ ├── create-keys-and-values.ps1
│ ├── create-new-key.ps1
│ ├── default-value.ps1
│ ├── delete-keys-and-values.ps1
│ ├── get-itemProperty.ps1
│ ├── get-itemPropertyValue.ps1
│ ├── img
│ └── inserted-values.png
│ ├── read-default-value.ps1
│ └── use-object.ps1
├── host
└── ANSI
│ ├── animated.ps1
│ ├── blink.ps1
│ ├── bold-underlined.ps1
│ ├── color-output
│ ├── .gitignore
│ ├── create-file.ps1
│ ├── format-hex.ps1
│ └── img
│ │ └── output.png
│ ├── foreground-background-16.ps1
│ └── img
│ └── foreground-background-16.png
├── language
├── class
│ ├── ToString
│ │ ├── callToString.ps1
│ │ ├── classWithToString.ps1
│ │ ├── classWithoutToString.ps1
│ │ ├── go.ps1
│ │ ├── select-string.ps1
│ │ └── stringInterpolation.ps1
│ ├── inheritance
│ │ └── simple.ps1
│ └── simple
│ │ ├── CLS.ps1
│ │ ├── _run.ps1
│ │ ├── call-methods.ps1
│ │ ├── call-static-method.ps1
│ │ ├── create-instance.ps1
│ │ └── type.ps1
├── cmdlet
│ └── parameter
│ │ ├── common
│ │ ├── errorVariable
│ │ │ └── get-inexisting-item.ps1
│ │ └── informationVariable.ps1
│ │ └── set
│ │ └── Test-ParameterSet.cs
├── enum
│ ├── base-class.ps1
│ ├── flags.ps1
│ └── play-rock-paper-scissors.ps1
├── function
│ ├── begin-process-end-block
│ │ ├── sum.ps1
│ │ └── with-without-process.ps1
│ ├── cmdletBinding
│ │ └── write-verbose.ps1
│ └── parameter
│ │ ├── default-value.ps1
│ │ ├── info.ps1
│ │ ├── pass-by-reference
│ │ ├── call.ps1
│ │ ├── func.ps1
│ │ └── object.ps1
│ │ ├── splatting.ps1
│ │ └── switch
│ │ └── func-with-switch.ps1
├── lexical-structure
│ └── token
│ │ └── literal
│ │ └── expandable-here-string.ps1
├── object
│ ├── psObject
│ │ ├── ToString.ps1
│ │ ├── add-member.ps1
│ │ ├── create-object.ps1
│ │ ├── obj-get-extended-members.ps1
│ │ ├── psObject-baseObject.ps1
│ │ ├── psObject-properties.ps1
│ │ └── psObject.ps1
│ └── type
│ │ └── accelerators
│ │ └── get.ps1
├── operator
│ ├── array-subexpression
│ │ ├── array-from-funcs.ps1
│ │ └── funcs.ps1
│ ├── as.ps1
│ ├── call
│ │ ├── access-module-variable.ps1
│ │ ├── mdl.psm1
│ │ ├── no-new-process
│ │ │ ├── call-script.ps1
│ │ │ └── the-script.ps1
│ │ ├── printSomething.ps1
│ │ └── script-block
│ │ │ ├── Hello-world.ps1
│ │ │ ├── param.ps1
│ │ │ └── variables.ps1
│ ├── comparison
│ │ ├── match_notmatch
│ │ │ ├── matches-variable.ps1
│ │ │ └── named-capture-group.ps1
│ │ ├── objects.ps1
│ │ ├── required-methods.ps1
│ │ └── scalar-vs-array.ps1
│ ├── contains
│ │ ├── like-vs-contains.ps1
│ │ └── value-in-array.ps1
│ ├── in
│ │ └── is-in-array.ps1
│ ├── is.ps1
│ ├── redirection
│ │ ├── .gitignore
│ │ └── encoding.ps1
│ ├── string-manipulation
│ │ ├── f
│ │ │ ├── DateTime.ps1
│ │ │ └── positional-arguments-and-alignment.ps1
│ │ ├── replace.ps1
│ │ ├── replace
│ │ │ └── psObjects.ps1
│ │ └── split-join.ps1
│ └── subexpression
│ │ └── dayOfYear.ps1
├── provider
│ └── env
│ │ ├── expand.ps1
│ │ └── show-all.ps1
├── scope
│ └── function.ps1
├── statement
│ ├── break
│ │ └── exit-for.ps1
│ ├── for
│ │ └── simple.ps1
│ ├── foreach
│ │ ├── IEnumerator.ps1
│ │ ├── array.ps1
│ │ ├── break.ps1
│ │ ├── continue.ps1
│ │ └── get-childItem.ps1
│ ├── function
│ │ ├── parameters
│ │ │ ├── args.ps1
│ │ │ ├── attributes
│ │ │ │ ├── alias
│ │ │ │ │ └── qm.ps1
│ │ │ │ ├── parameter
│ │ │ │ │ ├── mandatory
│ │ │ │ │ │ └── psBoundParameters.ps1
│ │ │ │ │ ├── valueFromPipeline
│ │ │ │ │ │ └── show-piped-objects.ps1
│ │ │ │ │ ├── valueFromPipelineByPropertyName
│ │ │ │ │ │ └── simple.ps1
│ │ │ │ │ └── valueFromRemainingArguments
│ │ │ │ │ │ └── show-remaining-arguments.ps1
│ │ │ │ └── validate
│ │ │ │ │ ├── Script
│ │ │ │ │ └── ensure-directory.ps1
│ │ │ │ │ └── Set
│ │ │ │ │ └── intro.ps1
│ │ │ ├── named.ps1
│ │ │ ├── param.ps1
│ │ │ ├── script.ps1
│ │ │ ├── shift.ps1
│ │ │ └── typed.ps1
│ │ └── show-definition.ps1
│ ├── switch
│ │ ├── assignment.ps1
│ │ ├── break.ps1
│ │ ├── eval.ps1
│ │ └── num-to-text.ps1
│ ├── try-catch-finally
│ │ ├── catch-type.ps1
│ │ └── simple.ps1
│ ├── using
│ │ └── namespace
│ │ │ └── simple.ps1
│ └── while
│ │ ├── assignment-gt.ps1
│ │ ├── assignment.ps1
│ │ └── condition.ps1
├── type
│ ├── array
│ │ ├── OFS.ps1
│ │ ├── as-argument
│ │ │ ├── .gitignore
│ │ │ ├── ShowArgs.cs
│ │ │ ├── ShowArgs.ps1
│ │ │ └── compile.ps1
│ │ ├── assign.ps1
│ │ ├── byte
│ │ │ └── return-in-function
│ │ │ │ ├── naive.ps1
│ │ │ │ ├── unary-comma.ps1
│ │ │ │ └── write-output.ps1
│ │ ├── filter.ps1
│ │ ├── intro.ps1
│ │ ├── iterate-over-name-value-pairs.ps1
│ │ ├── numerically-sort-array.ps1
│ │ ├── plus-vs-comma.ps1
│ │ ├── print.ps1
│ │ ├── unrolling.ps1
│ │ └── weakly-and-strongly-typed.ps1
│ └── hash-table
│ │ ├── add-remove.ps1
│ │ ├── override-members.ps1
│ │ └── sort.ps1
└── variable
│ ├── automatic
│ ├── args
│ │ └── parameters.ps1
│ ├── matches
│ │ └── simple.ps1
│ ├── myInvocation
│ │ └── script.ps1
│ ├── psBoundParameters
│ │ ├── ContainsKey.ps1
│ │ └── simple.ps1
│ ├── psCmdLet
│ │ ├── cmdletBinding.ps1
│ │ └── getType.ps1
│ └── psItem
│ │ └── equivalency.ps1
│ ├── create-global-var-in-func.ps1
│ ├── preference
│ ├── errorActionPreference
│ │ ├── intro.ps1
│ │ └── param-errorAction.ps1
│ ├── formatEnumerationLimit
│ │ ├── 4.ps1
│ │ ├── 6.ps1
│ │ └── objects.ps1
│ └── ofs.ps1
│ └── typed-untyped.ps1
├── powershell.exe
└── command
│ └── execute-script.bat
└── script
├── abort-on-unrecognized-term.ps1
└── name-and-path.ps1
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # About powershell
2 |
3 | Small powershell scriptlets and/or examples.
4 |
5 | ## Links
6 |
7 | [profile.ps1](https://github.com/ReneNyffenegger/scripts-and-utilities/blob/master/profile.ps1), my startup script for powershell.
8 |
--------------------------------------------------------------------------------
/cmdlets/acl/add-rule.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Create a dummy directory to test on it:
3 | #
4 | $null = new-item -itemType directory foo
5 |
6 | #
7 | # Get the directory's access control list
8 | #
9 | $acl = get-acl foo
10 |
11 | #
12 | # The following would show the access list
13 | #
14 | # $acl.Access
15 |
16 | #
17 | # Create a new rule to grant (allow) FullControl to NT SERVICE\MSSQLSERVER:
18 | #
19 |
20 | $ident = new-object System.Security.Principal.NTAccount 'NT SERVICE\MSSQLSERVER'
21 |
22 | $rule = new-object System.Security.AccessControl.FileSystemAccessRule `
23 | $ident , `
24 | ([type]'System.Security.AccessControl.FileSystemRights' )::FullControl, `
25 | ([type]'System.Security.AccessControl.AccessControlType')::Allow `
26 |
27 | $acl.AddAccessRule($rule)
28 |
29 | set-acl foo $acl
30 |
31 | # remove-item foo
32 |
--------------------------------------------------------------------------------
/cmdlets/childItem/filter-il.ps1:
--------------------------------------------------------------------------------
1 | get-childItem -filter *il*
2 |
--------------------------------------------------------------------------------
/cmdlets/childItem/get/include/cast-to-string.ps1:
--------------------------------------------------------------------------------
1 | foreach ($file in get-childItem . -recurse -include *.ps1) {
2 | [string] $name = $file
3 | $name
4 |
5 | $file.GetType().FullName
6 | }
7 |
8 |
9 | foreach ($file in get-childItem . -recurse *.ps1) {
10 | [string] $name = $file
11 | $name
12 |
13 | $file.GetType().FullName
14 | }
15 |
--------------------------------------------------------------------------------
/cmdlets/command/get/DLL.ps1:
--------------------------------------------------------------------------------
1 | (get-command write-output).dll
2 |
--------------------------------------------------------------------------------
/cmdlets/command/get/type.ps1:
--------------------------------------------------------------------------------
1 | (get-command get-command ).GetType().FullName
2 | (get-command write-output ).GetType().FullName
3 | (get-command start-process).GetType().FullName
4 |
--------------------------------------------------------------------------------
/cmdlets/command/invoke/argumentList.ps1:
--------------------------------------------------------------------------------
1 | $sb = {
2 | param($param_1, $param_2)
3 | write-output "param_1 = $param_1"
4 | write-output "param_2 = $param_2"
5 | }
6 |
7 | invoke-command -scriptBlock $sb -argumentList 42, 'Hello World'
8 |
--------------------------------------------------------------------------------
/cmdlets/command/invoke/script-block.ps1:
--------------------------------------------------------------------------------
1 | $sb = {
2 | write-output 'Hello from a script block'
3 | }
4 | write-output 'Going to invoke command with script block:'
5 | invoke-command $sb
6 |
--------------------------------------------------------------------------------
/cmdlets/command/measure/pipeline.ps1:
--------------------------------------------------------------------------------
1 | measure-command {
2 | 1 .. 1mb |
3 | get-random
4 | }
5 |
--------------------------------------------------------------------------------
/cmdlets/content/get/data.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | - eggs
4 | - why
5 | - foo
- bar
- baz
6 |
7 |
8 |
--------------------------------------------------------------------------------
/cmdlets/content/get/every-nth-line-max.ps1:
--------------------------------------------------------------------------------
1 | get-content lines.txt -readCount 2 -totalCount 6 | foreach-object {
2 | write-host "Processing $($_[0])"
3 | }
4 |
--------------------------------------------------------------------------------
/cmdlets/content/get/every-nth-line.ps1:
--------------------------------------------------------------------------------
1 | get-content lines.txt -readCount 3 | foreach-object {
2 | write-host "Processing $($_[0])"
3 | }
4 |
--------------------------------------------------------------------------------
/cmdlets/content/get/file.txt:
--------------------------------------------------------------------------------
1 | ABC
2 | DEF
3 | GHI
4 |
--------------------------------------------------------------------------------
/cmdlets/content/get/function.ps1:
--------------------------------------------------------------------------------
1 | $mkdir_content = get-content function:\mkdir
2 |
3 | $mkdir_content.GetType().FullName
4 | #
5 | # System.Management.Automation.ScriptBlock
6 |
7 | #
8 | # Print function definition
9 | #
10 | $mkdir_content.ToString()
11 |
--------------------------------------------------------------------------------
/cmdlets/content/get/hexString.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Get the content of a file as a byte array:
3 | #
4 | $arrayOfBytes = get-content -encoding byte -raw file.txt
5 |
6 | $arrayOfBytes.GetType().FullName
7 | #
8 | # System.Byte[]
9 |
10 | #
11 | # Format each element of the byte array to a hexadecimal
12 | # representation, resulting in an array of strings, each
13 | # of which is two characters wide:
14 | #
15 | $arrayOfHex = $arrayOfBytes.foreach( { '{0:X2}' -f $_ } )
16 |
17 | #
18 | # Join the elements of the string array to create
19 | # one string:
20 | #
21 | $hexString = $arrayOfHex -join ''
22 |
23 | #
24 | # Print the string
25 | #
26 | $hexString
27 | #
28 | # 4142430A4445460A4748490A
29 |
--------------------------------------------------------------------------------
/cmdlets/content/get/lines.txt:
--------------------------------------------------------------------------------
1 | first line
2 | second line
3 | third line
4 | fourth line
5 | fifth line
6 | sixth line
7 | seventh line
8 |
--------------------------------------------------------------------------------
/cmdlets/content/get/read-xml.ps1:
--------------------------------------------------------------------------------
1 | [xml] $xml = get-content .\data.xml
2 |
3 | $xml.root.items[2].item[2]
4 | #
5 | # baz
6 |
--------------------------------------------------------------------------------
/cmdlets/content/get/readCount-totalCount-byte-array.ps1:
--------------------------------------------------------------------------------
1 | if ($psVersionTable.psEdition -eq 'Desktop') {
2 | $threeTimesFourBytes = [byte[][]] (get-content $psCommandPath -encoding byte -readCount 4 -totalCount 12)
3 | }
4 | else {
5 | $threeTimesFourBytes = [byte[][]] (get-content $psCommandPath -asByteStream -readCount 4 -totalCount 12)
6 | }
7 |
8 | foreach ($fourBytes in $threeTimesFourBytes) {
9 | '{0:x2} {1:x2} {2:x2} {3:x2}' -f @( $fourBytes )
10 | }
11 |
--------------------------------------------------------------------------------
/cmdlets/content/get/variable.ps1:
--------------------------------------------------------------------------------
1 | $theNumber = 42
2 |
3 | get-content variable:\theNumber
4 | #
5 | # 42
6 |
7 | $varName = 'theNumber'
8 |
9 | get-content variable:\$varName
10 | #
11 | # 42
12 |
--------------------------------------------------------------------------------
/cmdlets/content/inplace-editing.ps1:
--------------------------------------------------------------------------------
1 | $fileName = 'some.text'
2 |
3 | ( get-content $fileName ) `
4 | -replace '#text#', '"Hello World"' `
5 | -replace '#num#' , 42 |
6 | set-content $fileName
7 |
--------------------------------------------------------------------------------
/cmdlets/content/set/.gitignore:
--------------------------------------------------------------------------------
1 | just-some.text
2 | unix.txt
3 | dos.txt
4 | simulate-downloaded-file.txt
5 |
--------------------------------------------------------------------------------
/cmdlets/content/set/set-stream-Zone.Identifier.ps1:
--------------------------------------------------------------------------------
1 | $filepath = "$pwd/simulate-downloaded-file.txt"
2 | $url = 'https://someUrl.xyz/'
3 |
4 | set-content $filepath @'
5 | Prepend that this
6 | file was downloaded
7 | from the internet
8 | '@
9 |
10 | set-content $filepath -stream Zone.Identifier @"
11 | [ZoneTransfer]
12 | ZoneId=3
13 | ReferrerUrl=$url
14 | HostUrl=$url$(split-path -leaf $filepath)
15 | "@
16 |
--------------------------------------------------------------------------------
/cmdlets/content/set/unix-vs-dos.ps1:
--------------------------------------------------------------------------------
1 | $lines = 'foo', 'bar', 'baz'
2 |
3 | set-content dos.txt $lines
4 | set-content unix.txt (($lines -join "`n") + "`n" ) -noNewLine
5 |
6 | format-hex dos.txt
7 | format-hex unix.txt
8 |
--------------------------------------------------------------------------------
/cmdlets/content/set/write-file.ps1:
--------------------------------------------------------------------------------
1 | set-content just-some.text 'first line', 'second line', 'third line'
2 |
--------------------------------------------------------------------------------
/cmdlets/content/some.text.orig:
--------------------------------------------------------------------------------
1 | The text is #text# and the
2 | number is #num#.
3 |
--------------------------------------------------------------------------------
/cmdlets/counter/get/all-counters.ps1:
--------------------------------------------------------------------------------
1 | foreach ($counterSet in get-counter -listSet * | sort-object counterSetName) {
2 |
3 | "$($counterSet.counterSetName) ($($counterSet.description))"
4 | ''
5 |
6 | foreach ($counter in $counterSet.counter) {
7 | " $counter"
8 | }
9 | ''
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/cmdlets/credential/get/img/basic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/credential/get/img/basic.png
--------------------------------------------------------------------------------
/cmdlets/csv/convertTo/processes.ps1:
--------------------------------------------------------------------------------
1 | get-process | select-object name, id, vm, pm | convertTo-CSV
2 |
--------------------------------------------------------------------------------
/cmdlets/culture/get/KeyboardLayoutId.ps1:
--------------------------------------------------------------------------------
1 | $kbdNum = (get-culture).KeyboardLayoutId
2 | $kbdHex = '{0:x8}' -f $kbdNum
3 | $kbdReg = get-itemProperty ('hklm:\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\' + $kbdHex )
4 | $kbdTxt = $kbdReg."Layout Text"
5 |
6 | "Keyboard Layout ID $kbdNum ($kbdHex) corresponds to $kbdTxt"
7 |
--------------------------------------------------------------------------------
/cmdlets/custom/format/simple.ps1:
--------------------------------------------------------------------------------
1 | class ClsOne {
2 |
3 | [string] $txt
4 | [int] $num
5 |
6 | ClsOne($t, $n) {
7 | $this.txt = $t
8 | $this.num = $n
9 | }
10 | }
11 |
12 |
13 | $obj_1 = new-object ClsOne 'Hello world', 42
14 |
15 | $obj_1 | format-custom
16 | #
17 | # class ClsOne
18 | # {
19 | # txt = Hello world
20 | # num = 42
21 | # }
22 |
23 |
24 | class ClsTwo {
25 |
26 | [string] $abc
27 | [ClsOne] $obj
28 |
29 | ClsTwo($a, $o) {
30 |
31 | $this.abc = $a
32 | $this.obj = $o
33 | }
34 | }
35 |
36 |
37 | $obj_2 = new-object ClsTwo 'ABC', $obj_1
38 |
39 | $obj_2 | format-custom
40 | #
41 | # class ClsTwo
42 | # {
43 | # abc = ABC
44 | # obj =
45 | # class ClsOne
46 | # {
47 | # txt = Hello world
48 | # num = 42
49 | # }
50 | # }
51 |
--------------------------------------------------------------------------------
/cmdlets/date/get/add-explicit.ps1:
--------------------------------------------------------------------------------
1 | $now = get-date
2 | $duration = new-timeSpan -days 2 -hours 3 -minutes 14 -seconds 22
3 |
4 | $now + $duration
5 |
--------------------------------------------------------------------------------
/cmdlets/date/get/add-implicit.ps1:
--------------------------------------------------------------------------------
1 | $now = get-date
2 |
3 | $now + '2.03:14:22'
4 |
--------------------------------------------------------------------------------
/cmdlets/date/get/basic.ps1:
--------------------------------------------------------------------------------
1 | $now = get-date
2 |
3 | write-output "Day: $($now.day), month: $($now.month), year: $($now.year)"
4 | #
5 | # Day: 14, month: 10, year: 2019
6 | #
7 |
8 | write-output "Hour: $($now.hour), minute: $($now.minute), second: $($now.second)"
9 | #
10 | # Hour: 8, minute: 2, second: 55
11 | #
12 |
13 | #
14 | # Use ISO 8601 format to specify a given (fixed) date:
15 | #
16 | $then = get-date '2019-08-28T14:15:16'
17 |
18 | #
19 | # Determine difference between now and then
20 | #
21 | $diff = $now - $then
22 | $diff.GetType().FullName
23 | #
24 | # System.TimeSpan
25 | #
26 |
27 | write-output "Days between then and now: $($diff.days)"
28 | #
29 | # Days between then and now: 46
30 | #
31 |
--------------------------------------------------------------------------------
/cmdlets/date/get/format.ps1:
--------------------------------------------------------------------------------
1 | $formattedDate = get-date -format 'yyyy-MM-dd HH-mm-ss (K)'
2 | write-output "formattedDate = $formattedDate"
3 |
--------------------------------------------------------------------------------
/cmdlets/default/out/overriding/out-default.ps1:
--------------------------------------------------------------------------------
1 | function out-default {
2 |
3 | param (
4 | [parameter (valueFromPipeline=$true)] $val
5 | )
6 |
7 | begin { write-host "overwridden out-default is called" }
8 | process{ write-host " received: $val" }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/cmdlets/default/out/overriding/pipeline.ps1:
--------------------------------------------------------------------------------
1 | 'foo', 'bar', 'baz'
2 |
--------------------------------------------------------------------------------
/cmdlets/default/out/overriding/rm-out-default.ps1:
--------------------------------------------------------------------------------
1 | remove-item function:out-default
2 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/an-expression.txt:
--------------------------------------------------------------------------------
1 | $THE_NUMBER = 7 * $someNumber
2 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/apply-on-array-elements.ps1:
--------------------------------------------------------------------------------
1 | $hex_numbers = '0a', 'ff', '10'
2 |
3 | $numbers = $hex_numbers | foreach-object { invoke-expression "0x$_" }
4 |
5 | write-host $numbers
6 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/commands.ps1:
--------------------------------------------------------------------------------
1 | write-output 'This line originates from commands.ps1'
2 | write-output 'so does this'
3 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/eval.ps1:
--------------------------------------------------------------------------------
1 | $num_1 = 3
2 | $num_2 = 14
3 | $operation = '*'
4 |
5 | invoke-expression "write-output ($num_1 $operation $num_2)"
6 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/get-content.ps1:
--------------------------------------------------------------------------------
1 | $someNumber = 6
2 |
3 | get-content an-expression.txt | invoke-expression
4 |
5 | write-output "The number is: $THE_NUMBER"
6 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/multiline.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | function func($p_1, $p_2, $p_3) {
4 | write-host "p_1 = $p_1"
5 | write-host "p_2 = $p_2"
6 | write-host "p_3 = $p_3"
7 | }
8 |
9 | invoke-expression "func ``
10 | -p_2 2 ``
11 | -p_1 one ``
12 | -p_3 III
13 | "
14 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/pipe-into/expression.txt:
--------------------------------------------------------------------------------
1 | @{
2 | num = 42
3 | txt = 'hello world'
4 | }
5 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/pipe-into/pipeline.ps1:
--------------------------------------------------------------------------------
1 | $dict = get-content -raw expression.txt | invoke-expression
2 |
3 | "num = $($dict.num)"
4 | "txt = $($dict.txt)"
5 |
--------------------------------------------------------------------------------
/cmdlets/expression/invoke/source.ps1:
--------------------------------------------------------------------------------
1 | $dir = split-path $myInvocation.myCommand.path
2 |
3 | invoke-expression -command "$dir/commands.ps1"
4 |
--------------------------------------------------------------------------------
/cmdlets/file/out/.gitignore:
--------------------------------------------------------------------------------
1 | file.txt
2 | out-file-append-test.txt
3 | with-new-line.txt
4 | without-new-line.txt
5 |
--------------------------------------------------------------------------------
/cmdlets/file/out/append.ps1:
--------------------------------------------------------------------------------
1 | $file = 'out-file-append-test.txt'
2 |
3 |
4 | 'first line' | out-file -encoding utf8 $file
5 | 'second line' | out-file -encoding utf8 -append $file
6 | 'third line' | out-file -encoding utf8 -append $file
7 |
--------------------------------------------------------------------------------
/cmdlets/file/out/noNewLine-pipeline.ps1:
--------------------------------------------------------------------------------
1 | 'foo', 'bar', 'baz' | out-file -encoding ascii -noNewLine without-new-line.txt
2 | 'foo', 'bar', 'baz' | out-file -encoding ascii with-new-line.txt
3 |
4 | format-hex without-new-line.txt
5 | #
6 | # 66 6F 6F 62 61 72 62 61 7A
7 |
8 | format-hex with-new-line.txt
9 | #
10 | # 66 6F 6F 0D 0A 62 61 72 0D 0A 62 61 7A 0D 0A
11 |
--------------------------------------------------------------------------------
/cmdlets/file/out/write-file.ps1:
--------------------------------------------------------------------------------
1 | 'A' | out-file file.txt
2 | 'B' | out-file -append file.txt
3 | 'C' | out-file -append file.txt
4 |
5 | format-hex file.txt
6 |
--------------------------------------------------------------------------------
/cmdlets/file/unblock/after.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/file/unblock/after.png
--------------------------------------------------------------------------------
/cmdlets/file/unblock/before.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/file/unblock/before.png
--------------------------------------------------------------------------------
/cmdlets/fileHash/get/calculate-hash.ps1:
--------------------------------------------------------------------------------
1 | $hash = get-fileHash xyz.txt
2 |
3 | $hash.algorithm
4 | #
5 | # SHA256
6 |
7 | $hash.path
8 | #
9 | # C:\Users\rene\PowerShell\cmdlets\fileHash\get\xyz.txt
10 |
11 | $hash.hash
12 | #
13 | # B1B113C6ED8AB3A14779F7C54179EAC2B87D39FCEBBF65A50556B8D68CAAA2FB
14 |
--------------------------------------------------------------------------------
/cmdlets/fileHash/get/xyz.txt:
--------------------------------------------------------------------------------
1 | foo
2 | bar
3 | baz
4 |
--------------------------------------------------------------------------------
/cmdlets/gridView/out/array-psCustomObjects.ps1:
--------------------------------------------------------------------------------
1 | [psCustomObject] @{ num = 1; english = 'one' ; german = 'eins'; french = 'un' },
2 | [psCustomObject] @{ num = 2; english = 'two' ; german = 'zwei'; french = 'deux' },
3 | [psCustomObject] @{ num = 3; english = 'three'; german = 'drei'; french = 'trois' } | out-gridView
4 |
--------------------------------------------------------------------------------
/cmdlets/gridView/out/array.ps1:
--------------------------------------------------------------------------------
1 | 'foo', 'bar', 'baz' | out-gridView -title 'An array'
2 |
--------------------------------------------------------------------------------
/cmdlets/gridView/out/img/array-psCustomObjects.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/gridView/out/img/array-psCustomObjects.png
--------------------------------------------------------------------------------
/cmdlets/gridView/out/img/array.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/gridView/out/img/array.png
--------------------------------------------------------------------------------
/cmdlets/host/write/color.ps1:
--------------------------------------------------------------------------------
1 | write-host "Text..."
2 | write-host "`nWarning: end of string reached.`n" -foregroundColor yellow -backgroundColor red
3 | write-host "...Text"
4 |
--------------------------------------------------------------------------------
/cmdlets/host/write/img/color.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/host/write/img/color.png
--------------------------------------------------------------------------------
/cmdlets/host/write/pipeline.ps1:
--------------------------------------------------------------------------------
1 | $pipelineResult = 'one', 'two', 'three' | foreach-object {
2 | if ($_ -match 'o$') {
3 | write-host "$_ ends in o"
4 | }
5 | elseif ($_ -match '^o') {
6 | write-output "$_ begins with o"
7 | }
8 | else {
9 | $_
10 | }
11 | }
12 |
13 | ''
14 | 'pipelineResult:'
15 | $pipelineResult
16 |
--------------------------------------------------------------------------------
/cmdlets/host/write/vs-string-use.ps1:
--------------------------------------------------------------------------------
1 | ./vs-string.ps1 | foreach-object {
2 | "I have received the object $_"
3 | }
4 |
--------------------------------------------------------------------------------
/cmdlets/host/write/vs-string.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Pipe an array of strings ...
3 | #
4 | 'foo', 'bar', 'baz' |
5 | #
6 | # ... into foreach-object
7 | #
8 | foreach-object {
9 | #
10 | # ... which checks if the
11 | # string is bar ...
12 | #
13 | if ($_ -eq 'bar') {
14 | #
15 | # If it is bar, the object is written
16 | #
17 | write-host $_
18 | }
19 | else {
20 | #
21 | # ... otherwise, it is passed on in
22 | # the pipeline:
23 | #
24 | $_
25 | #
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/cmdlets/item/copy/create-backups.ps1:
--------------------------------------------------------------------------------
1 | get-childItem -recurse *.ps1 |
2 | foreach-object {
3 | copy-item $_ $( $_.fullName -replace 'ps1$', 'ps1.bak' )
4 | }
5 |
--------------------------------------------------------------------------------
/cmdlets/item/new/.gitignore:
--------------------------------------------------------------------------------
1 | xyz.txt
2 |
--------------------------------------------------------------------------------
/cmdlets/item/new/create-directory.ps1:
--------------------------------------------------------------------------------
1 | $dirName = 'a-folder'
2 |
3 | if (test-path $dirName) {
4 | write-host "Directory $dirName already exists, going to remove it"
5 | remove-item -recurse -force $dirName
6 | }
7 |
8 | $createdDir = new-item -type directory a-folder
9 |
10 | write-host "Directory was created at $('{0:yyyy-MM-dd HH:mm:ss}' -f $createdDir.creationTime)"
11 |
--------------------------------------------------------------------------------
/cmdlets/item/new/type-file.ps1:
--------------------------------------------------------------------------------
1 | new-item -type file xyz.txt -value @'
2 | some text
3 | that goes into
4 | the file named xyz.txt
5 | '@
6 |
--------------------------------------------------------------------------------
/cmdlets/item/remove/literalPath.ps1:
--------------------------------------------------------------------------------
1 | $fileName = 'a file with [brackets] in its name.abc'
2 |
3 | $null = new-item $fileName
4 | remove-item $fileName
5 |
6 | #
7 | # File still exists
8 | #
9 | get-childItem *.abc
10 |
11 | #
12 | # Use -literalPath to remove file with brackets
13 | #
14 | remove-item -literalPath $fileName
15 |
--------------------------------------------------------------------------------
/cmdlets/itemProperty/get/data-type.ps1:
--------------------------------------------------------------------------------
1 | $scriptName = $myInvocation.myCommand.name
2 | $propFile = get-itemProperty $scriptName
3 | $propFile.GetType().FullName
4 | #
5 | # System.IO.FileInfo
6 |
7 | $propFileattr = get-itemProperty $scriptName lastAccessTime
8 | $propFileattr.GetType().FullName
9 | #
10 | # System.Management.Automation.PSCustomObject
11 |
12 |
13 | $propDir = get-itemProperty .
14 | $propDir.GetType().FullName
15 | #
16 | # System.IO.DirectoryInfo
17 |
18 |
19 | $propRegKey = get-itemProperty 'HKCU:\Control Panel\International'
20 | $propRegKey.GetType().FullName
21 | #
22 | # System.Management.Automation.PSCustomObject
23 |
24 | $propVal = get-itemProperty 'HKCU:\Control Panel\International' sTimeFormat
25 | $propVal.GetType().FullName
26 | #
27 | # System.Management.Automation.PSCustomObject
28 |
29 | $propVal.sTimeFormat.GetType().FullName
30 | #
31 | # System.String
32 |
33 | $val = get-itemPropertyValue 'HKCU:\Control Panel\International' sTimeFormat
34 | $val.GetType().FullName
35 | #
36 | # System.String
37 |
--------------------------------------------------------------------------------
/cmdlets/itemProperty/remove/registry-value.ps1:
--------------------------------------------------------------------------------
1 | $regKey = 'hkcu:\Software\tq84_removeItemTest'
2 |
3 | $null = new-item $regKey
4 |
5 | set-itemProperty $regKey num 42
6 | set-itemProperty $regKey txt 'Hello world'
7 | set-itemProperty $regKey xyz 'Foo, bar, baz'
8 |
9 | read-host 'Registry key and values created.'
10 |
11 | remove-itemProperty $regKey xyz
12 |
13 | read-host 'Value "xyz" removed.'
14 |
15 | remove-item $regKey
16 |
--------------------------------------------------------------------------------
/cmdlets/itemProperty/set/.gitignore:
--------------------------------------------------------------------------------
1 | test
2 |
--------------------------------------------------------------------------------
/cmdlets/itemProperty/set/img/registry-value.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/itemProperty/set/img/registry-value.png
--------------------------------------------------------------------------------
/cmdlets/itemProperty/set/registry-value.ps1:
--------------------------------------------------------------------------------
1 | $regKey = 'hkcu:\Software\TQ84'
2 |
3 | if (! (test-path $regKey )) {
4 | $null = new-item $regKey
5 | }
6 |
7 | set-itemProperty `
8 | $regKey `
9 | -name foo `
10 | -type dWord `
11 | -value 42
12 |
13 | set-itemProperty `
14 | $regKey `
15 | -name bar `
16 | -type string `
17 | -value 'hello World'
18 |
--------------------------------------------------------------------------------
/cmdlets/itemProperty/set/touch.ps1:
--------------------------------------------------------------------------------
1 | $fileName = 'test'
2 |
3 | set-content $fileName 'foo bar baz'
4 |
5 | set-itemProperty $fileName lastWriteTime (get-date '2001-02-03T04:05:06')
6 |
7 | get-item $fileName
8 | #
9 | # Directory: C:\Users\r.nyffenegger\github\temp\PowerShell\cmdLets\itemProperty\set
10 | #
11 | # Mode LastWriteTime Length Name
12 | # ---- ------------- ------ ----
13 | # -a--- 03.02.2001 04:05 13 test
14 |
--------------------------------------------------------------------------------
/cmdlets/job/receive/show-result.ps1:
--------------------------------------------------------------------------------
1 | $job = start-job {
2 | #
3 | # Calculate the 17th triangular number.
4 | #
5 | $result = 0;
6 | foreach ($i in 1 .. 17) {
7 | $result += $i
8 | }
9 |
10 | return $result
11 | #
12 | # Pretend it's a real difficult calculation that
13 | # takes some time …
14 | #
15 | start-sleep 6
16 |
17 | return $result
18 | }
19 |
20 |
21 | foreach ($j in 1 .. 10) {
22 | #
23 | # Do something different while the
24 | # calculation runs in the background
25 | #
26 |
27 | write-host "j = $j"
28 |
29 | if ($job.state -eq 'Completed') {
30 |
31 | if ($job.hasMoreData) {
32 | $t17 = receive-job $job
33 | write-host "Calculated result = $t17"
34 | }
35 |
36 | }
37 |
38 | start-sleep 2
39 | }
40 |
--------------------------------------------------------------------------------
/cmdlets/job/start/current-directory.ps1:
--------------------------------------------------------------------------------
1 | start-job { add-content ~/current-directory (get-location) }
2 |
--------------------------------------------------------------------------------
/cmdlets/job/start/pass-variable.ps1:
--------------------------------------------------------------------------------
1 | $var=42
2 |
3 | $scriptBlock = { add-content ~/variable-value "var=$var | using:var=$using:var" }
4 |
5 | $var='changed'
6 |
7 | start-job $scriptBlock
8 |
--------------------------------------------------------------------------------
/cmdlets/json/convertFrom/basic.ps1:
--------------------------------------------------------------------------------
1 | $json = @'
2 | {
3 | "ary": [
4 | "one",
5 | {
6 | "x": "eggs",
7 | "y": "why"
8 | },
9 | 3
10 | ],
11 | "txt": "Hello world",
12 | "num": 42
13 | }
14 | '@
15 |
16 | $obj = convertFrom-json $json
17 | $obj.GetType().FullName
18 | #
19 | # System.Management.Automation.PSCustomObject
20 |
21 | #
22 | # $obj.ary is an array with three elements:
23 | #
24 |
25 | $obj.ary.GetType().FullName
26 | #
27 | # System.Object[]
28 |
29 | $obj.ary.length
30 | #
31 | # 3
32 |
33 | #
34 | # $obj.arry's first element
35 | #
36 |
37 | $obj.ary[0].GetType().FullName
38 | #
39 | # System.String
40 |
41 | $obj.ary[0]
42 | #
43 | # one
44 |
45 |
46 | #
47 | # $obj.arry's second element
48 | #
49 |
50 | $obj.ary[1].GetType().FullName
51 | #
52 | # System.Management.Automation.PSCustomObject
53 |
54 | $obj.ary[1]
55 | #
56 | # x y
57 | # - -
58 | # eggs why
59 |
60 | $obj.ary[1].x
61 | #
62 | # eggs
63 |
64 | #
65 | # etc. etc. etc.
66 | #
67 |
68 |
69 | $obj.txt
70 | #
71 | # Hello World
72 |
73 | $obj.num
74 | #
75 | # 42
76 |
--------------------------------------------------------------------------------
/cmdlets/json/convertTo/basic.ps1:
--------------------------------------------------------------------------------
1 | $obj = [psObject] @{
2 | txt = 'Hello world'
3 | num = 42
4 | bla = 'foo', 'bar', 'baz'
5 | }
6 |
7 | convertTo-json $obj
8 | #
9 | # {
10 | # "bla": [
11 | # "foo",
12 | # "bar",
13 | # "baz"
14 | # ],
15 | # "txt": "Hello world",
16 | # "num": 42
17 | # }
18 |
--------------------------------------------------------------------------------
/cmdlets/member/add/access-members-by-variable.ps1:
--------------------------------------------------------------------------------
1 | $cust_obj = new-object psObject
2 |
3 | $cust_obj | add-member number 42
4 | $cust_obj | add-member text 'hello world'
5 | $cust_obj | add-member meta 'foo', 'bar', 'baz'
6 |
7 | $member_name = 'text'
8 | $cust_obj.$member_name
9 |
10 | 'number', 'text', 'meta' | foreach-object {
11 | '{0,-6}: {1}' -f $_, $cust_obj.$_
12 | }
13 |
--------------------------------------------------------------------------------
/cmdlets/member/add/obj.ps1:
--------------------------------------------------------------------------------
1 | $obj = new-object System.Object
2 |
3 | $obj | add-member -memberType noteProperty -name num -value 21
4 | $obj | add-member -memberType noteProperty -name text -value foo
5 | $obj | add-member -memberType scriptMethod -name twice -value { $this.num *= 2 }
6 |
7 | $obj.twice()
8 |
9 | write-output "`The num is $($obj.num), text is $($obj.text)"
10 | #
11 | # The num is 42, text is foo
12 |
13 | $obj | get-member
14 | #
15 | # TypeName: System.Object
16 | #
17 | # Name MemberType Definition
18 | # ---- ---------- ----------
19 | # Equals Method bool Equals(System.Object obj)
20 | # GetHashCode Method int GetHashCode()
21 | # GetType Method type GetType()
22 | # ToString Method string ToString()
23 | # num NoteProperty int num=42
24 | # text NoteProperty string text=foo
25 | # twice ScriptMethod System.Object twice();
26 |
--------------------------------------------------------------------------------
/cmdlets/member/add/scriptMethod.ps1:
--------------------------------------------------------------------------------
1 | $num = new-object psObject @{
2 | val = 4
3 | txt = 'four'
4 | }
5 |
6 | $num | add-member scriptMethod dbl {
7 | $this.val * 2
8 | }
9 |
10 | $num | add-member scriptMethod mult {
11 | param([int]$i = 1)
12 | $this.val * $i
13 | }
14 |
15 | $num.dbl()
16 | #
17 | # 8
18 |
19 | $num.mult(7)
20 | #
21 | # 28
22 |
--------------------------------------------------------------------------------
/cmdlets/new-object.ps1:
--------------------------------------------------------------------------------
1 | $obj = new-object -typeName PSObject
2 |
3 | $obj | get-member
4 | #
5 | # TypeName: System.Management.Automation.PSCustomObject
6 | #
7 | # Name MemberType Definition
8 | # ---- ---------- ----------
9 | # Equals Method bool Equals(System.Object obj)
10 | # GetHashCode Method int GetHashCode()
11 | # GetType Method type GetType()
12 | # ToString Method string ToString()
13 |
--------------------------------------------------------------------------------
/cmdlets/object/compare/compare-directory-structure.ps1:
--------------------------------------------------------------------------------
1 | compare-object (get-childItem -recurse dir-one) (get-childItem -recurse dir-two)
2 |
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-one/subdir-A/in-both_differing-content.txt:
--------------------------------------------------------------------------------
1 | one
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-one/subdir-A/only-in-dir-one.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/compare/dir-one/subdir-A/only-in-dir-one.txt
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-one/subdir-B/file-x:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/compare/dir-one/subdir-B/file-x
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-two/subdir-A/in-both_differing-content.txt:
--------------------------------------------------------------------------------
1 | two
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-two/subdir-A/only-in-dir-two.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/compare/dir-two/subdir-A/only-in-dir-two.txt
--------------------------------------------------------------------------------
/cmdlets/object/compare/dir-two/subdir-C/file-x:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/compare/dir-two/subdir-C/file-x
--------------------------------------------------------------------------------
/cmdlets/object/compare/psObjects.ps1:
--------------------------------------------------------------------------------
1 | $psObject_1 = new-object psobject -property @{ word_1 = 'abc' ; word_2 = 'def' ; word_3 = 'ghi' ; word_4 = 'jkl' }
2 | $psObject_2 = new-object psobject -property @{ word_X = 'abc' ; word_2 = 'def' ; word_3 = 'XXX' ; word_4 = 'jkl' }
3 |
4 | compare-object $psObject_1 $psObject_2
5 |
6 |
7 | compare-object $psObject_1 $psObject_2 -includeEqual
8 | #
9 | # InputObject SideIndicator
10 | # ----------- -------------
11 | # @{word_2=def; word_4=jkl; word_1=abc; word_3=ghi} ==
12 |
--------------------------------------------------------------------------------
/cmdlets/object/compare/string-arrays.ps1:
--------------------------------------------------------------------------------
1 | $words_1 = 'foo', 'bar', 'baz', 'four'
2 | $words_2 = 'one', 'foo', 'bar', 'baz'
3 |
4 | compare-object $words_1 $words_2
5 | #
6 | # InputObject SideIndicator
7 | # ----------- -------------
8 | # one =>
9 | # four <=
10 |
--------------------------------------------------------------------------------
/cmdlets/object/forEach/script-block.ps1:
--------------------------------------------------------------------------------
1 | 1 .. 10 | forEach-object { $_ * $_ }
2 |
--------------------------------------------------------------------------------
/cmdlets/object/group/asHashTable.ps1:
--------------------------------------------------------------------------------
1 | $data = import-CSV data.csv
2 |
3 | $quarters = $data | group-object -asHashTable quarter
4 |
5 | $quarters.GetType().FullName
6 | #
7 | # System.Collections.Hashtable
8 | #
9 |
10 | ( $quarters.Q3 | where-object item -eq baz ).val
11 | #
12 | # 16
13 | #
14 |
15 | ( $quarters.Q2 | where-object val -ge 20 ) | select-object item
16 | #
17 | # item
18 | # ----
19 | # foo
20 | # baz
21 | #
22 |
--------------------------------------------------------------------------------
/cmdlets/object/group/data.csv:
--------------------------------------------------------------------------------
1 | quarter,item,val
2 | Q1,foo,17
3 | Q1,bar,26
4 | Q1,baz,15
5 | Q2,foo,21
6 | Q2,bar,18
7 | Q2,baz,29
8 | Q3,foo,9
9 | Q3,bar,22
10 | Q3,baz,16
11 | Q4,foo,15
12 | Q4,bar,18
13 | Q4,baz,19
14 |
--------------------------------------------------------------------------------
/cmdlets/object/group/group-then-print-objects.ps1:
--------------------------------------------------------------------------------
1 | [psCustomObject] @{ category = 'foo'; val_A = 4; val_B = 'abc' } ,
2 | [psCustomObject] @{ category = 'foo'; val_A = 2; val_B = 'def' } ,
3 | [psCustomObject] @{ category = 'bar'; val_A = 9; val_B = 'ghi' } ,
4 | [psCustomObject] @{ category = 'foo'; val_A = 3; val_B = 'jkl' } ,
5 | [psCustomObject] @{ category = 'baz'; val_A = 6; val_B = 'mno' } ,
6 | [psCustomObject] @{ category = 'bar'; val_A = 7; val_B = 'pqr' } ,
7 | [psCustomObject] @{ category = 'baz'; val_A = 5; val_B = 'stu' } |
8 | #
9 | # Pipe all objects into group-object to
10 | # group theym by their category value:
11 | #
12 | group-object category |
13 | #
14 | # There are three different categories, so group-object
15 | # produces three Microsoft.PowerShell.Commands.GroupInfo
16 | # objects.
17 | # These three objects are now piped into foreach-object
18 | # which first prints the group's name, which is the value
19 | # of the respective category, and then passes the group's
20 | # Group value further down the pipeline:
21 | #
22 | foreach-object { write-host $_.Name; $_.Group } |
23 | #
24 | # A group's Group property contanis all object that
25 | # belong to a group. These objects are now passed
26 | # to the following foreach-object which simply
27 | # prints the objects' properties val_A and val_B:
28 | #
29 | foreach-object { write-host " $($_.val_A): $($_.val_B)" }
30 |
--------------------------------------------------------------------------------
/cmdlets/object/measure/int-array.ps1:
--------------------------------------------------------------------------------
1 | 4,6,3,7 | measure-object -minimum -maximum -average -sum
2 | #
3 | # Count : 4
4 | # Average : 5
5 | # Sum : 20
6 | # Maximum : 7
7 | # Minimum : 3
8 | # StandardDeviation :
9 | # Property :
10 |
--------------------------------------------------------------------------------
/cmdlets/object/measure/max-length.ps1:
--------------------------------------------------------------------------------
1 | [psCustomObject] @{ nm = 99; txt = "ninety-nine" } ,
2 | [psCustomObject] @{ nm = 42; txt = "hello, world"} ,
3 | [psCustomObject] @{ nm = 0; txt = "zero" } |
4 | measure-object -property { $_.txt.length } -maximum |
5 | select-object maximum
6 |
--------------------------------------------------------------------------------
/cmdlets/object/measure/property-scriptBlock.ps1:
--------------------------------------------------------------------------------
1 | get-process | measure-object `
2 | -sum { $_.workingSet / 1MB }, `
3 | { $_.PagedMemorySize64 / 1MB }
4 | #
5 | # Count : 433
6 | # Average :
7 | # Sum : 13530.765625
8 | # Maximum :
9 | # Minimum :
10 | # StandardDeviation :
11 | # Property : $_.workingSet / 1MB
12 | #
13 | # Count : 433
14 | # Average :
15 | # Sum : 16070.26953125
16 | # Maximum :
17 | # Minimum :
18 | # StandardDeviation :
19 | # Property : $_.PagedMemorySize64 / 1MB
20 |
--------------------------------------------------------------------------------
/cmdlets/object/measure/property.ps1:
--------------------------------------------------------------------------------
1 | get-process | measure-object `
2 | -property workingSet,PagedMemorySize64,VirtualMemorySize64 `
3 | -minimum -maximum -average -sum
4 | #
5 | # Count : 437
6 | # Average : 32798031.0846682
7 | # Sum : 14332739584
8 | # Maximum : 1850437632
9 | # Minimum : 8192
10 | # StandardDeviation :
11 | # Property : WorkingSet
12 | #
13 | # Count : 437
14 | # Average : 38320076.4485126
15 | # Sum : 16745873408
16 | # Maximum : 1188343808
17 | # Minimum : 57344
18 | # StandardDeviation :
19 | # Property : PagedMemorySize64
20 | #
21 | # Count : 437
22 | # Average : 1146566214653.66
23 | # Sum : 501049435803648
24 | # Maximum : 2238949216256
25 | # Minimum : 8192
26 | # StandardDeviation :
27 | # Property : VirtualMemorySize64
28 |
--------------------------------------------------------------------------------
/cmdlets/object/new/COM/img/fso.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/new/COM/img/fso.png
--------------------------------------------------------------------------------
/cmdlets/object/new/COM/img/xls.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/object/new/COM/img/xls.png
--------------------------------------------------------------------------------
/cmdlets/object/new/cs-class/.gitignore:
--------------------------------------------------------------------------------
1 | *.dll
2 |
--------------------------------------------------------------------------------
/cmdlets/object/new/cs-class/obj.cs:
--------------------------------------------------------------------------------
1 | namespace TQ84 {
2 |
3 | public class Obj {
4 |
5 | private string name_;
6 |
7 | public Obj(string name) {
8 | name_ = name;
9 | System.Console.WriteLine("Obj's constructor was called");
10 | }
11 |
12 | public static int twice(int a) {
13 | return 2*a;
14 | }
15 |
16 | public void saySomeThing(string someThing) {
17 | System.Console.WriteLine(name_ + " says " + someThing);
18 | }
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/cmdlets/object/new/inline-c-sharp.ps1:
--------------------------------------------------------------------------------
1 | add-Type -typedef @'
2 |
3 | using System;
4 | namespace tq84 {
5 |
6 | public class CLS {
7 |
8 | private String txt;
9 |
10 | public void writeTxt() {
11 | Console.WriteLine("txt is {0}", txt);
12 | }
13 |
14 | public CLS(String txt_) {
15 | txt = txt_;
16 | }
17 | }
18 | }
19 | '@
20 |
21 | $obj_1 = new-object tq84.CLS 'Hello world'
22 | $obj_2 = new-object tq84.CLS 'The number is 42'
23 |
24 | $obj_1.writeTxt()
25 | #
26 | # txt is Hello world
27 |
28 | $obj_2.writeTxt()
29 | #
30 | # txt is The number is 42
31 |
--------------------------------------------------------------------------------
/cmdlets/object/new/property-dotNet.ps1:
--------------------------------------------------------------------------------
1 | add-Type -typedef @'
2 |
3 | using System;
4 |
5 | public class XYZ {
6 | public int num;
7 | public String txt;
8 | }
9 |
10 | '@
11 |
12 | $props = @{
13 | num = 4
14 | txt ='four'
15 | }
16 |
17 | $obj_1 = new-object XYZ -property $props
18 |
19 | #
20 | # Note: the memberType we're looking for is
21 | # property, not noteProperty:
22 | #
23 | $obj_1 | get-member -memberType property
24 | #
25 | # TypeName: XYZ
26 | #
27 | # Name MemberType Definition
28 | # ---- ---------- ----------
29 | # num Property int num {get;set;}
30 | # txt Property string txt {get;set;}
31 |
--------------------------------------------------------------------------------
/cmdlets/object/new/property-ps.ps1:
--------------------------------------------------------------------------------
1 | $props = @{
2 | num = 42
3 | txt ='Hello world'
4 | }
5 |
6 | $props.GetType().FullName
7 | #
8 | # System.Collections.Hashtable
9 |
10 | $obj = new-object psObject -property $props
11 |
12 | $obj | get-member -memberType noteProperty
13 | #
14 | # TypeName: System.Management.Automation.PSCustomObject
15 | #
16 | # Name MemberType Definition
17 | # ---- ---------- ----------
18 | # num NoteProperty int num=42
19 | # txt NoteProperty string txt=Hello world
20 |
21 | #
22 | # The properties of the object can
23 | # now be changed
24 | #
25 | $obj.num = 4
26 |
27 | $obj | format-table
28 | #
29 | # num txt
30 | # --- ---
31 | # 4 Hello world
32 |
33 |
--------------------------------------------------------------------------------
/cmdlets/object/new/psObject/hash-like-object.ps1:
--------------------------------------------------------------------------------
1 | $psObj = new-object psObject
2 |
3 | $psObj.getType().fullName
4 | #
5 | # System.Management.Automation.PSCustomObject
6 |
7 | add-member -in $psObj noteProperty greeting 'Hello world'
8 | add-member -in $psObj noteProperty 'the number' 42
9 |
10 | $psObj
11 | #
12 | # greeting the number
13 | # -------- ----------
14 | # Hello world 42
15 |
16 | write-output("I say " + $psObj.greeting)
17 | #
18 | # I say Hello world
19 |
20 | write-output("The number is " + $psObj.'the number')
21 | #
22 | # The number is 42
23 |
--------------------------------------------------------------------------------
/cmdlets/object/select/calculated.ps1:
--------------------------------------------------------------------------------
1 | [psCustomObject] @{ x = 7.1 ; y = 3.3 } ,
2 | [psCustomObject] @{ x = 8.4 ; y = 3.6 } ,
3 | [psCustomObject] @{ x = 6.9 ; y = 3.4 } |
4 | select-object `
5 | x,
6 | y,
7 | @{L = 'ratio'; E = { '{0,5:N2}' -f ($_.x / $_.y) } },
8 | @{L = ' sum'; E = { '{0,4:N1}' -f ($_.x + $_.y) } }
9 | #
10 | # x y ratio sum
11 | # - - ----- ----
12 | # 7.1 3.3 2.15 10.4
13 | # 8.4 3.6 2.33 12.0
14 | # 6.9 3.4 2.03 10.3
15 |
--------------------------------------------------------------------------------
/cmdlets/object/select/expandProperty-ary.ps1:
--------------------------------------------------------------------------------
1 | $ary =
2 | [psCustomObject] @{
3 | num = 42
4 | txt = 'hello world'
5 | elems = 7,9,1
6 | },
7 | [psCustomObject] @{
8 | num = 99
9 | txt = 'ninety nine'
10 | elems = 3,2
11 | },
12 | [psCustomObject] @{
13 | num = 7
14 | txt = 'seven nine'
15 | elems =@()
16 | }
17 |
18 | $ary | select-object num, txt -expandProperty elems
19 | #
20 | # 7
21 | # 9
22 | # 1
23 | # 3
24 | # 2
25 |
--------------------------------------------------------------------------------
/cmdlets/object/select/expandProperty-obj.ps1:
--------------------------------------------------------------------------------
1 | $ary =
2 | [psCustomObject] @{
3 | num = 42
4 | txt = 'hello world'
5 | obj = [psCustomObject] @{
6 | foo = 'abc'
7 | bar = 'de'
8 | baz = 'fghi'
9 | }
10 | },
11 | [psCustomObject] @{
12 | num = 99
13 | txt = 'ninety nine'
14 | obj = [psCustomObject] @{
15 | foo = 'jk'
16 | bar = 'lm'
17 | baz = 'nopqr'
18 | }
19 | },
20 | [psCustomObject] @{
21 | num = 7
22 | txt = 'seven nine'
23 | obj = [psCustomObject] @{
24 | foo = 'stuv'
25 | bar = 'w'
26 | baz = 'xyz'
27 | }
28 | }
29 |
30 | $ary |
31 | select-object num, txt, obj
32 | #
33 | # num txt obj
34 | # --- --- ---
35 | # 42 hello world @{foo=abc; bar=de; baz=fghi}
36 | # 99 ninety nine @{foo=jk; bar=lm; baz=nopqr}
37 | # 7 seven nine @{foo=stuv; bar=w; baz=xyz}
38 |
39 |
40 | $ary |
41 | select-object num, txt -expandProperty obj |
42 | format-table
43 | #
44 | # foo bar baz num txt
45 | # --- --- --- --- ---
46 | # abc de fghi 42 hello world
47 | # jk lm nopqr 99 ninety nine
48 | # stuv w xyz 7 seven nine
49 |
--------------------------------------------------------------------------------
/cmdlets/object/select/expandProperty.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # An array with three elements is created.
3 | #
4 | # Each element is a psCustomObject with the two note properties
5 | # key_1 and key_2.
6 | #
7 | # Note: key_1 of the last element in the array contains an array.
8 | #
9 | $ary =
10 | [psCustomObject] @{ key_1 = 'val' ; key_2 = 'foo' },
11 | [psCustomObject] @{ key_1 = 'another val' ; key_2 = 'bar' },
12 | [psCustomObject] @{ key_1 = 'an', 'array', 'of', 'words'; key_2 = 'baz' }
13 |
14 | #
15 | # The array is sent to the select-object cmdLet, once with the -property
16 | # and once with the -expandedProperties argument. The return values
17 | # are captured in two variables:
18 | #
19 | $properties = $ary | select-object -property key_1
20 | $expandedProperties = $ary | select-object -expandProperty key_1
21 |
22 | #
23 | # With -property, select-object just filters the properties from
24 | # the object it receives from the pipeline. Thus, we still have
25 | # three elements:
26 | #
27 | $properties.count
28 | #
29 | # 3
30 |
31 | #
32 | # However, when using -expandedProperties, select-object will
33 | # turn each element of the value of the expanded property into
34 | # its own object. Because the last element of $ary contains 4 elements,
35 | # we now have 6 (=2+4) objects (strings) in the $expandedProperties
36 | # Variable
37 | $expandedProperties.count
38 | #
39 | # 6
40 |
41 | #
42 | # The second (last) element in $properties is still an array:
43 | #
44 | $properties[2]
45 | #
46 | # key_1
47 | # -----
48 | # {an, array, of, words}
49 |
50 | #
51 | # The second element $expandedProperties is the first element
52 | # of the array that was assigned to key_1:
53 | #
54 | $expandedProperties[2]
55 | #
56 | # an
57 |
--------------------------------------------------------------------------------
/cmdlets/odbcDsn/add/Oracle.ps1:
--------------------------------------------------------------------------------
1 | $driverName = 'Oracle In OraDB18Home2'
2 | $dsnName = 'Ora18'
3 |
4 | remove-odbcDsn -name $dsnName -dsnType user -errorAction silentlyContinue
5 |
6 | add-odbcDsn `
7 | -name $dsnName `
8 | -driverName $driverName `
9 | -dsnType user `
10 | -setPropertyValue @(
11 | # "Password = secretGarden", # is it possible to add a passowrd here?
12 | "StatementCache = F",
13 | "NumericSetting = NLS",
14 | "Description = DSN for Ora18",
15 | "BindAsFLOAT = F",
16 | "UserID = rene",
17 | "Application Attributes = T",
18 | "FailoverDelay = 10",
19 | "DisableDPM = F",
20 | "ServerName = Ora18",
21 | "BatchAutocommitMode = IfAllSuccessful",
22 | "FailoverRetryCount = 10",
23 | "MaxTokenSize = 8192",
24 | "EXECSyntax = F",
25 | "DisableRULEHint = T",
26 | "UseOCIDescribeAny = F",
27 | "ForceWCHAR = F",
28 | "LobPrefetchSize = 8192",
29 | "Attributes = W",
30 | # "EXECSchemaOpt",
31 | "AggregateSQLType = FLOAT",
32 | "Lobs = T",
33 | "QueryTimeout = T",
34 | "MetadataIdDefault = F",
35 | "MaxLargeData = 0",
36 | # "DSN = OT",
37 | "CloseCursor = F",
38 | "DisableMTS = T",
39 | "Failover = T",
40 | "ResultSets = T",
41 | "CacheBufferSize = 20",
42 | "FetchBufferSize = 64000",
43 | "SQLTranslateErrors = F",
44 | "BindAsDATE = F"
45 | )
46 |
--------------------------------------------------------------------------------
/cmdlets/odbcDsn/add/img/Oracle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/odbcDsn/add/img/Oracle.png
--------------------------------------------------------------------------------
/cmdlets/output/write/noEnumerate.ps1:
--------------------------------------------------------------------------------
1 | $array_of_three_objects = 'foo', 'bar', 'baz'
2 |
3 | write-output $array_of_three_objects | foreach-object { "object is $_" }
4 | write-output -noEnumerate $array_of_three_objects | foreach-object { "object is $_" }
5 |
--------------------------------------------------------------------------------
/cmdlets/path/resolve/force.ps1:
--------------------------------------------------------------------------------
1 | function resolve-always($path) {
2 |
3 | $resolved = resolve-path $path -errorAction silentlyContinue -errorVariable err
4 |
5 | if (! $resolved) {
6 | return $err[0].targetObject
7 | }
8 |
9 | return $resolved
10 | }
11 |
--------------------------------------------------------------------------------
/cmdlets/path/split/go.ps1:
--------------------------------------------------------------------------------
1 | $path = 'drive:\dirOne\dirTwo\file.ext'
2 |
3 | # Get directory that contains the path:
4 | #
5 | split-path $path
6 | #
7 | # drive:\dirOne\dirTwo
8 |
9 | #
10 | # Get parent directory. In case of
11 | # files, get directory in which file is
12 | # located
13 | #
14 | split-path $path -parent
15 | #
16 | # drive:\dirOne\dirTwo
17 |
18 | # Get parent directory's parent directory
19 | #
20 | split-path (split-path $path -parent) -parent
21 | #
22 | # drive:\dirOne
23 |
24 | # Get file name only:
25 | #
26 | split-path $path -leaf
27 | #
28 | # file.ext
29 |
30 | # Get file's extension (requires Powershell 6)
31 | #
32 | split-path $path -extension
33 | #
34 | # .ext
35 |
36 | # Get file name without extension:
37 | #
38 | # -leafBase requires PowerShell 6.
39 | # Use [IO.Path]::GetFileNameWithoutExtension($path)
40 | # in earlier versions.
41 | #
42 | split-path $path -leafBase
43 | #
44 | # file
45 |
46 | # Check if path is absolute:
47 | #
48 | split-path $path -isAbsolute
49 | #
50 | # True
51 |
52 | # Get drive of path:
53 | #
54 | split-path $path -qualifier
55 | #
56 | # drive:
57 |
58 | # Get entire path without drive:
59 | #
60 | split-path $path -noQualifier
61 | #
62 | # \dirOne\dirTwo\file.ext
63 |
64 |
--------------------------------------------------------------------------------
/cmdlets/path/test/IO.File.Exists.ps1:
--------------------------------------------------------------------------------
1 | if ([System.IO.File]::Exists($profile)) {
2 | write-host "The profile file exists"
3 | }
4 | else {
5 | write-host "The profile file does not exist"
6 | }
7 |
--------------------------------------------------------------------------------
/cmdlets/path/test/create-directory-if-it-does-not-exist.ps1:
--------------------------------------------------------------------------------
1 | if (! (test-path "$home\some-dir") ) {
2 | $null = new-item -itemType directory -path "$home\some-dir"
3 | write-host "directory was created"
4 | }
5 |
--------------------------------------------------------------------------------
/cmdlets/path/test/pathType.ps1:
--------------------------------------------------------------------------------
1 | $scriptFile = $myInvocation.myCommand.path
2 |
3 | test-path $scriptFile
4 | #
5 | # True
6 |
7 | test-path $scriptFile -pathType leaf
8 | #
9 | # True
10 |
11 | test-path $scriptFile -pathType container
12 | #
13 | # False
14 |
15 | test-path (split-path $scriptFile) -pathType container
16 | #
17 | # True
18 |
--------------------------------------------------------------------------------
/cmdlets/progress/img/write.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/progress/img/write.png
--------------------------------------------------------------------------------
/cmdlets/progress/write.ps1:
--------------------------------------------------------------------------------
1 | for ($percent = 0; $percent -le 100; $percent += 5) {
2 | start-sleep -milliSeconds 500
3 | write-progress -activity 'Doing nothing' -status "$percent%:" -percentComplete $percent
4 | }
5 |
--------------------------------------------------------------------------------
/cmdlets/scheduledTask/get/tasks-and-actions.ps1:
--------------------------------------------------------------------------------
1 | $i = 0
2 | foreach ($task in (get-scheduledTask)) {
3 |
4 |
5 | # if ($task.actions.length -gt 0) # Seems always to be 1
6 | if ($task.actions.execute)
7 | {
8 |
9 | # "i: $($i)"
10 | "taskPath : $($task.taskPath)"
11 | "taskName : $($task.taskName)"
12 | "state : $($task.state)"
13 | "triggers : $($task.triggers)"
14 | "date : $($task.date)"
15 | "description: $($task.description)"
16 |
17 | foreach ($action in $task.actions) {
18 | " $($action.execute)"
19 | " $($action.arguments)"
20 | # $action.id
21 | # $action.workingDirectory
22 | # $action.psComputerName
23 |
24 | }
25 | '------------------------------------------'
26 | }
27 | $i++
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/cmdlets/set-executionPolicy.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Run as administrator
3 | #
4 | set-executionPolicy unrestricted
5 |
--------------------------------------------------------------------------------
/cmdlets/strictMode/set/off.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -off
2 |
3 | $someText = 'hello world'
4 |
5 | write-host "They first said '$someText', followed by '$undefinedText'"
6 |
--------------------------------------------------------------------------------
/cmdlets/strictMode/set/version-1.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 1
2 |
3 | $val = 42
4 | $result = $val * $uninitialized_val
5 |
--------------------------------------------------------------------------------
/cmdlets/strictMode/set/version-2.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 3
2 |
3 | [psCustomObject] $obj = @{ num = 42; txt = 'hello world' }
4 |
5 | write-host $obj.num
6 | write-host $obj.unobtainium
7 |
--------------------------------------------------------------------------------
/cmdlets/strictMode/set/version-3.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 3
2 |
3 | $ary = 'foo', 'bar', 'baz'
4 |
5 | write-host $ary[0]
6 | write-host $ary[1]
7 | write-host $ary[2]
8 | write-host $ary[3]
9 |
--------------------------------------------------------------------------------
/cmdlets/string/select/get-winEvent_inputObject.ps1:
--------------------------------------------------------------------------------
1 | get-winEvent application | select-string -inputObject {$_.message} -pattern 'Failed'
2 |
--------------------------------------------------------------------------------
/cmdlets/string/select/grep-recursively.ps1:
--------------------------------------------------------------------------------
1 | get-childItem <# Get a list of files #> `
2 | -recurse <# recursively #> `
3 | ..\.. <# start two directories further up #> `
4 | -include '*.ps1' <# Only interested in PowerShell scripts #> |
5 | select-string <# pipe found files into select-string #> `
6 | 'foo.*bar' ` <# find files that contain foo followed by bar #> |
7 | format-table <# Pipe to format-table for nice output #> `
8 | lineNumber <# We want lineNumber #> ,
9 | @{name='rel. path' ; <# relative path #> `
10 | expression={ resolve-path -relative $_.path }} <#(which is returned by resolve-path …) #> ,
11 | line <# and the text of the matching line #>
12 |
--------------------------------------------------------------------------------
/cmdlets/string/select/psCustomObject.ps1:
--------------------------------------------------------------------------------
1 | $objs = `
2 | ( new-object psObject -property @{ val_1 = 'one' ; val_2 = 'two' ; val_3 = 'three' } ) ,
3 | ( new-object psObject -property @{ val_1 = 'foo' ; val_2 = 'bar' ; val_3 = 'baz' } ) ,
4 | ( new-object psObject -property @{ val_1 = 'abcde' ; val_2 = 'fghij' ; val_3 = $null } ) ;
5 |
6 | $objs | select-string -inputObject { $_.val_2 } -pattern 'a'
7 |
--------------------------------------------------------------------------------
/cmdlets/string/select/string-array.ps1:
--------------------------------------------------------------------------------
1 | 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten' | select-string '^[^e]*$'
2 |
--------------------------------------------------------------------------------
/cmdlets/string/select/strings/strings.ps1:
--------------------------------------------------------------------------------
1 | foreach($matchedLine in
2 | get-content text |
3 | select-string -allMatches '\b\w{5}\b'
4 | ) {
5 | foreach ($matchedWord in $matchedLine.matches) {
6 | "$($matchedLine.lineNumber): $matchedWord"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/cmdlets/string/select/strings/text:
--------------------------------------------------------------------------------
1 | one two three
2 | four five six
3 | seven eight nine
4 | ten elevent twelve.
5 |
--------------------------------------------------------------------------------
/cmdlets/stringData/convertFrom/multiLine.ps1:
--------------------------------------------------------------------------------
1 | $data = @'
2 | foo = 42
3 | bar = 99
4 |
5 | # Empty lines and lines
6 | # starting with the comment
7 | # character are ignored.
8 |
9 | baz = 0
10 | '@
11 |
12 | $ht = convertFrom-stringData $data
13 |
14 | write-output "Value of bar = $($ht['bar'])"
15 | #
16 | # Value of bar = 99
17 |
18 | write-output $ht
19 | #
20 | # Name Value
21 | # ---- -----
22 | # baz 0
23 | # bar 99
24 | # foo 42
25 |
--------------------------------------------------------------------------------
/cmdlets/table/format/generate-objects-for-x-ms.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | $milliSeconds
3 | )
4 |
5 | $ticks_ = (get-date).ticks
6 |
7 | $i = 0
8 | while ( (get-date).ticks - $ticks_ -lt $milliSeconds * [System.TimeSpan]::TicksPerMillisecond ) {
9 | $i++
10 | [pscustomobject] @{num = $i; txt = 'abcdefghi' }
11 |
12 | start-sleep -milliSecond 50
13 |
14 | }
15 |
16 | $i++; [pscustomobject] @{num = $i; txt = 'abcdefghijklmnopqrstuvwxyz' }
17 | $i++; [pscustomobject] @{num = $i; txt = 'abcdef' }
18 |
--------------------------------------------------------------------------------
/cmdlets/type/add/WinApi.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | $newType = add-type -name user32 -passThru -memberDefinition '
4 | [DllImport("user32.dll", CharSet=CharSet.Auto)]
5 | public static extern Int32 MessageBox(
6 | IntPtr hWnd,
7 | String text,
8 | String caption,
9 | int options
10 | );'
11 |
12 |
13 | $MB_OKCANCEL = 4
14 | $ID_YES = 6
15 | $ID_NO = 7
16 |
17 | $chosen = $newType::MessageBox(0, 'Should I?', 'Important question', $MB_OKCANCEL)
18 |
19 | if ($chosen -eq $ID_YES) {
20 | write-host 'Yeah!'
21 | }
22 | elseif ($chosen -eq $ID_NO) {
23 | write-host 'Nay!'
24 | }
25 | else {
26 | write-host 'This is quite an unexpected answer.'
27 | }
28 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/.gitignore:
--------------------------------------------------------------------------------
1 | anAssembly.dll
2 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/aClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace TQ84 {
4 |
5 | public class aClass {
6 |
7 | private int num_;
8 | private string txt_;
9 |
10 | public aClass(int num, string txt) {
11 | num_ = num;
12 | txt_ = txt;
13 | }
14 |
15 | public void printValues() {
16 | Console.WriteLine(String.Format("num = {0}, txt = {1}", num_, txt_));
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/compile-useAssembly.ps1:
--------------------------------------------------------------------------------
1 | $null = [System.Reflection.Assembly]::LoadFile("$pwd/anAssembly.dll")
2 |
3 | add-type `
4 | -typeDefinition (get-content -raw useAssembly.cs) `
5 | -referencedAssemblies "$pwd/anAssembly.dll"
6 |
7 | [XYZ.useAssembly]::run()
8 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/create-assembly.ps1:
--------------------------------------------------------------------------------
1 | $sourceCode = get-content -raw aClass.cs
2 | $assemblyPath = "$pwd/anAssembly.dll"
3 |
4 | if (test-path $assemblyPath) {
5 | remove-item $assemblyPath
6 | }
7 |
8 | add-type `
9 | -typeDefinition $sourceCode `
10 | -outputAssembly $assemblyPath `
11 | -outputType library
12 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/did-not-work.ps1:
--------------------------------------------------------------------------------
1 | add-type `
2 | -typeDefinition (get-content -raw useAssembly.cs) `
3 | -referencedAssemblies `
4 | "$pwd/anAssembly.dll"
5 |
6 | [XYZ.useAssembly]::run()
7 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/use-assembly.ps1:
--------------------------------------------------------------------------------
1 | $null = [System.Reflection.Assembly]::LoadFile("$pwd/anAssembly.dll")
2 |
3 | $obj_1 = new-object TQ84.aClass 42, 'Hello world'
4 | $obj_2 = new-object TQ84.aClass 99, 'Ninety-nine'
5 |
6 | $obj_1.printValues()
7 | $obj_2.printValues()
8 |
--------------------------------------------------------------------------------
/cmdlets/type/add/create-assembly/useAssembly.cs:
--------------------------------------------------------------------------------
1 | using TQ84;
2 |
3 | namespace XYZ {
4 |
5 | public class useAssembly {
6 |
7 | static public void run() {
8 |
9 | aClass obj_1 = new TQ84.aClass(42, "Hello world");
10 | aClass obj_2 = new TQ84.aClass(99, "ninety-nine");
11 |
12 | obj_1.printValues();
13 | obj_2.printValues();
14 |
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/cmdlets/type/add/img/WinApi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/cmdlets/type/add/img/WinApi.png
--------------------------------------------------------------------------------
/cmdlets/type/add/inline.ps1:
--------------------------------------------------------------------------------
1 | add-Type -typedef @'
2 | using System;
3 |
4 | public class inl {
5 | public DateTime whenCreated;
6 | public inl() { whenCreated = DateTime.Now; }
7 | }
8 | '@
9 |
10 | $inl = new-object inl
11 |
12 | start-sleep -s 3
13 |
14 | write-output "It's $([DateTime]::Now) now, `$inl was created at $($inl.whenCreated)."
15 |
--------------------------------------------------------------------------------
/cmdlets/type/add/tq84_type.cs:
--------------------------------------------------------------------------------
1 | namespace TQ84 {
2 | public class T {
3 | public static int twice(int a) {
4 | return 2*a;
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/cmdlets/verbose/write/preference-variable.ps1:
--------------------------------------------------------------------------------
1 | function writeVerbosely {
2 | write-host "going to write verbosely"
3 | write-verbose "This is a verbose message"
4 | write-host
5 | }
6 |
7 | $verbosePreference = 'silentlyContinue'
8 | writeVerbosely
9 |
10 | $verbosePreference = 'continue'
11 | writeVerbosely
12 |
--------------------------------------------------------------------------------
/cmdlets/verbose/write/verbose-parameter.ps1:
--------------------------------------------------------------------------------
1 | function writeVerbosely {
2 |
3 | [cmdletBinding()]
4 | param()
5 |
6 | write-host "Value of `$verbosePreference is $verbosePreference"
7 | write-verbose "This is a verbose message"
8 | write-host
9 | }
10 |
11 | writeVerbosely
12 | writeVerbosely -verbose
13 |
--------------------------------------------------------------------------------
/cmdlets/webRequest/invoke/deal-with-unsuccessful-requests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Inspired by https://stackoverflow.com/a/19122582/180275
3 | #
4 |
5 | set-strictMode -version latest
6 |
7 | function get-url {
8 | param (
9 | [string] $url
10 | )
11 |
12 |
13 | if ($psVersionTable.psVersion.major -ge 7) {
14 | $res = invoke-webRequest -skipHttpErrorCheck $url
15 | }
16 | else {
17 |
18 | $res = try {
19 | invoke-webRequest $url
20 | }
21 | catch {
22 | $_.exception.response
23 | }
24 | }
25 |
26 | write-host ""
27 | write-host " Status for ${url}: $($res.statusCode)"
28 | write-host " type of `$res: $($res.GetType().FullName)"
29 | }
30 |
31 |
32 | write-host "psVersion: $($psVersionTable.psVersion)"
33 |
34 | get-url https://google.com/
35 | get-url https://google.com/does-not-exist
36 |
--------------------------------------------------------------------------------
/cmdlets/webRequest/invoke/desktop-vs-core.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 3
2 |
3 | function check-eq {
4 | param (
5 | [string] $value,
6 | [string] $expectedDesktopValue,
7 | [string] $expectedCoreValue
8 | )
9 |
10 | if ($psVersionTable.psEdition -eq 'Desktop') {
11 | if ($value -ne $expectedDesktopValue) {
12 | write-host "Expected Desktop value was $expectedDesktopValue, but I had $value"
13 | }
14 |
15 | }
16 | elseif ($psVersionTable.psEdition -eq 'Core') {
17 |
18 | if ($value -ne $expectedCoreValue) {
19 | write-host "Expected Core value was $expectedCoreValue, but I had $value"
20 | }
21 |
22 | }
23 |
24 | }
25 |
26 | $url = 'https://renenyffenegger.ch/'
27 |
28 | $response = invoke-webRequest $url
29 | $baseResponse = $response.baseResponse
30 |
31 | $responseType = $response.GetType().FullName
32 | $baseResponseType = $baseResponse.GetType().FullName
33 |
34 | check-eq $responseType 'Microsoft.PowerShell.Commands.HtmlWebResponseObject' 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
35 | check-eq $baseResponseType 'System.Net.HttpWebResponse' 'System.Net.Http.HttpResponseMessage'
36 |
--------------------------------------------------------------------------------
/cmdlets/write-host.ps1:
--------------------------------------------------------------------------------
1 | write-host "Foo bar baz" -foregroundColor red -backgroundColor yellow
2 |
3 | # ------------------------------
4 |
5 | $ar = 1..5
6 |
7 | write-host $ar
8 | # 1 2 3 4 5
9 |
10 | write-host $ar -separator ", "
11 | # 1, 2, 3, 4, 5
12 |
13 | # ------------------------------
14 |
15 | write-host "foo bar" -noNewline
16 | write-host " baz"
17 | # foo bar baz
18 |
--------------------------------------------------------------------------------
/cmdlets/xml/select/XPath/simple.ps1:
--------------------------------------------------------------------------------
1 | [xml] $xml = "
2 |
3 |
4 | - eggs
5 | - foo
- bar
- baz
6 | - hen
7 |
8 | "
9 |
10 | $xml.root.items[1].item[2]
11 | #
12 | # baz
13 |
14 | ($xml | select-xml -xpath '/root/items[@id="2"]').value
15 | #
16 | # baz
17 |
--------------------------------------------------------------------------------
/encoding/script-latin1.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/encoding/script-latin1.ps1
--------------------------------------------------------------------------------
/encoding/script-utf8-bom.ps1:
--------------------------------------------------------------------------------
1 | "PowerShell version: $($psVersionTable.psVersion)"
2 | "This file is encoded in utf-8 with a bom"
3 | 'Bär'.length
4 |
--------------------------------------------------------------------------------
/encoding/script-utf8.ps1:
--------------------------------------------------------------------------------
1 | "PowerShell version: $($psVersionTable.psVersion)"
2 | "This file is encoded in utf-8 without a bom"
3 | 'Bär'.length
4 |
--------------------------------------------------------------------------------
/examples/Problem-Ejecting-USB-Mass-Storage-Device/img/eventVwr_filter-current-log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/examples/Problem-Ejecting-USB-Mass-Storage-Device/img/eventVwr_filter-current-log.png
--------------------------------------------------------------------------------
/examples/Problem-Ejecting-USB-Mass-Storage-Device/img/msgBox.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/examples/Problem-Ejecting-USB-Mass-Storage-Device/img/msgBox.png
--------------------------------------------------------------------------------
/examples/Problem-Ejecting-USB-Mass-Storage-Device/readEventLog.ps1:
--------------------------------------------------------------------------------
1 | get-eventLog -logName system |
2 | where-object instanceId -eq 225 |
3 | select-object timeGenerated, message -first 1
4 |
--------------------------------------------------------------------------------
/examples/WinAPI/ExtractStringFromDLL.ps1:
--------------------------------------------------------------------------------
1 | add-type -typeDefinition @"
2 | using System;
3 | using System.Runtime.InteropServices;
4 | using System.Text;
5 |
6 | public class tq84_krnl {
7 |
8 | [DllImport("kernel32.dll",
9 | SetLastError = true,
10 | CharSet = CharSet.Ansi
11 | )]
12 | private static extern IntPtr LoadLibraryEx
13 | (
14 | [MarshalAs(UnmanagedType.LPStr)]string lpFileName,
15 | IntPtr hFile,
16 | uint dwFlags
17 | );
18 |
19 | [DllImport("user32.dll" ,
20 | SetLastError = true,
21 | CharSet = CharSet.Auto
22 | )]
23 | private static extern int LoadString
24 | (
25 | IntPtr hInstance,
26 | int ID,
27 | StringBuilder lpBuffer,
28 | int nBufferMax
29 | );
30 |
31 | [DllImport("kernel32.dll",
32 | SetLastError = true)]
33 | [return: MarshalAs(UnmanagedType.Bool)]
34 | private static extern bool FreeLibrary
35 | (
36 | IntPtr hModule
37 | );
38 |
39 | public static string ExtractStringFromDLL(string file, int number) {
40 |
41 | IntPtr lib = LoadLibraryEx(file, new IntPtr(0L), 32); // 32 = LOAD_LIBRARY_AS_IMAGE_RESOURCE
42 | StringBuilder result = new StringBuilder(2048);
43 | LoadString(lib, number, result, result.Capacity);
44 | FreeLibrary(lib);
45 |
46 | return result.ToString();
47 | }
48 | }
49 | "@
50 |
--------------------------------------------------------------------------------
/examples/WinAPI/SendMessage.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | $winApi = add-type -name user32 -passThru `
4 | -memberDefinition '
5 |
6 | [DllImport("user32.dll")] public static extern
7 | IntPtr FindWindowEx(
8 | IntPtr hwndParent ,
9 | IntPtr hwndChildAfter,
10 | String lpszClass ,
11 | String lpszWindow
12 | );
13 |
14 | [DllImport("User32.dll")] public static extern
15 | IntPtr SendMessage(
16 | IntPtr hWnd ,
17 | int uMsg ,
18 | int wParam ,
19 | string lParam
20 | );'
21 |
22 | $notepad_1 = start-process -passThru notepad
23 | $notepad_2 = start-process -passThru notepad
24 |
25 | #
26 | # Wait for application windows to be created
27 | #
28 | # https://stackoverflow.com/questions/61637460
29 | #
30 | start-sleep 1
31 |
32 | $hwndNotepad_1 = $notepad_1.MainWindowHandle
33 | $hwndNotepad_2 = $notepad_2.MainWindowHandle
34 |
35 | $hwndEdit_1 = $winApi::FindWindowEx($hwndNotepad_1, [IntPtr]::Zero, "Edit", $null)
36 | $hwndEdit_2 = $winApi::FindWindowEx($hwndNotepad_2, [IntPtr]::Zero, "Edit", $null)
37 |
38 | $null = $winApi::SendMessage($hwndEdit_1, 0x000C, 0, "This is the first notepad window.")
39 | $null = $winApi::SendMessage($hwndEdit_2, 0x000C, 0, "This is the second notepad window.")
40 |
--------------------------------------------------------------------------------
/examples/WinAPI/Shell32/Extract/.gitignore:
--------------------------------------------------------------------------------
1 | *.jpg
2 | *.png
3 | *.bmp
4 | *.html
5 |
--------------------------------------------------------------------------------
/examples/WinAPI/Shell32/Extract/Shell32_Extract.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # https://stackoverflow.com/questions/6872957/how-can-i-use-the-images-within-shell32-dll-in-my-c-sharp-project
3 | #
4 | add-type -typeDefinition '
5 |
6 | using System;
7 | using System.Runtime.InteropServices;
8 |
9 | public class Shell32_Extract {
10 |
11 | [DllImport(
12 | "Shell32.dll",
13 | EntryPoint = "ExtractIconExW",
14 | CharSet = CharSet.Unicode,
15 | ExactSpelling = true,
16 | CallingConvention = CallingConvention.StdCall)
17 | ]
18 |
19 | public static extern int ExtractIconEx(
20 | string lpszFile , // Name of the .exe or .dll that contains the icon
21 | int iconIndex , // zero based index of first icon to extract. If iconIndex == 0 and and phiconSmall == null and phiconSmall = null, the number of icons is returnd
22 | out IntPtr phiconLarge,
23 | out IntPtr phiconSmall,
24 | int nIcons
25 | );
26 |
27 | }
28 | ';
29 |
--------------------------------------------------------------------------------
/examples/WinAPI/Shell32/Extract/User32_DestroyIcon.ps1:
--------------------------------------------------------------------------------
1 | add-type -typeDefinition '
2 |
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | public class User32_DestroyIcon {
7 |
8 | [DllImport(
9 | "User32.dll",
10 | EntryPoint = "DestroyIcon"
11 | )]
12 | public static extern int DestroyIcon(IntPtr hIcon);
13 |
14 | }
15 | ';
16 |
--------------------------------------------------------------------------------
/examples/WinAPI/Shell32/Extract/create-html-with-icons-of-dll.ps1:
--------------------------------------------------------------------------------
1 | $dllPath = $args[0]
2 |
3 | if ($dllPath -eq $null) {
4 | write-output "specify a dll";
5 | return;
6 | }
7 |
8 | if (! (test-path $dllPath)) {
9 | write-output "$dllPath is not a file";
10 | return;
11 | }
12 |
13 | $filenameWithoutSuffix = [IO.Path]::GetFileNameWithoutExtension($dllPath)
14 |
15 | . .\Shell32_Extract.ps1
16 | . .\User32_DestroyIcon.ps1
17 |
18 |
19 | "
20 | Icons in $filenameWithoutSuffix.dll
21 | Icons in $filenameWithoutSuffix.dll
22 | These icons were extracted with PowerShell and the WinAPI function ExtractIconEx
23 |
" | out-file "$filenameWithoutSuffix.html";
24 |
25 | $null = [Reflection.Assembly]::LoadWithPartialName('System.Drawing');
26 | $null = [Reflection.Assembly]::LoadWithPartialName('System.Drawing.Imaging');
27 |
28 | [System.IntPtr] $phiconSmall = 0;
29 | [System.IntPtr] $phiconLarge = 0;
30 |
31 | $nofImages = [Shell32_Extract]::ExtractIconEx($dllPath, -1, [ref] $phiconLarge, [ref] $phiconSmall, 0);
32 | $nofImages;
33 |
34 | foreach ($iconIndex in 0 .. ($nofImages-1)) {
35 |
36 | $nofIconsExtracted = [Shell32]::ExtractIconEx($dllPath, $iconIndex, [ref] $phiconLarge, [ref] $phiconSmall, 1)
37 | $iconLarge = [System.Drawing.Icon]::FromHandle($phiconLarge);
38 |
39 | $bmpLarge = $iconLarge.ToBitmap()
40 |
41 | $iconIndex_0 = '{0,3:000}' -f $iconIndex
42 | $imgName = "$filenameWithoutSuffix-$iconIndex_0.png";
43 | $bmpLarge.Save("$(get-location)\$imgName");
44 |
45 | if ($iconIndex -and (! ($iconIndex % 10))) {
46 | "
" | out-file "$filenameWithoutSuffix.html" -append;
47 | }
48 |
49 | "$iconIndex_0 |  | " | out-file "$filenameWithoutSuffix.html" -append;
50 |
51 | $null = [User32_DestroyIcon]::DestroyIcon($phiconSmall);
52 | $null = [User32_DestroyIcon]::DestroyIcon($phiconLarge);
53 |
54 | }
55 |
56 | "
" | out-file "$filenameWithoutSuffix.html" -append;
57 |
--------------------------------------------------------------------------------
/examples/WinAPI/Shell32/Extract/go.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Prevent Error
3 | # Unable to find type [System.Drawing.Icon]
4 | # and
5 | # Unable to find type [System.Drawing.Imaging.ImageFormat].
6 | #
7 | $null = [Reflection.Assembly]::LoadWithPartialName('System.Drawing');
8 | $null = [Reflection.Assembly]::LoadWithPartialName('System.Drawing.Imaging');
9 |
10 | $dllPath = "$env:SystemRoot\System32\imageres.dll"
11 |
12 | [System.IntPtr] $phiconSmall = 0
13 | [System.IntPtr] $phiconLarge = 0
14 |
15 | $nofImages = [Shell32_Extract]::ExtractIconEx($dllPath, -1, [ref] $phiconLarge, [ref] $phiconSmall, 0)
16 |
17 | foreach ($iconIndex in 0 .. ($nofImages-1)) {
18 |
19 | $nofIconsExtracted = [Shell32_Extract]::ExtractIconEx($dllPath, $iconIndex, [ref] $phiconLarge, [ref] $phiconSmall, 1)
20 |
21 | if ($nofIconsExtracted -ne 2) {
22 | write-error "iconsExtracted = $nofIconsExtracted"
23 | }
24 |
25 | $iconSmall = [System.Drawing.Icon]::FromHandle($phiconSmall);
26 | $iconLarge = [System.Drawing.Icon]::FromHandle($phiconLarge);
27 |
28 | $bmpSmall = $iconSmall.ToBitmap()
29 | $bmpLarge = $iconLarge.ToBitmap()
30 |
31 | $iconIndex_0 = '{0,3:000}' -f $iconIndex
32 |
33 | #
34 | # System.Drawing.Image.Save(), without specifying an encoder, stores
35 | # the bitmap in png format.
36 | #
37 | $bmpLarge.Save("$(get-location)\small-$iconIndex_0.png");
38 | $bmpLarge.Save("$(get-location)\large-$iconIndex_0.png");
39 |
40 | #
41 | # Use System.Drawing.Imaging.ImageFormat to specify a
42 | # different format:
43 | #
44 |
45 | $bmpSmall.Save("$(get-location)\small-$iconIndex_0.bmp", [System.Drawing.Imaging.ImageFormat]::Bmp );
46 | $bmpLarge.Save("$(get-location)\large-$iconIndex_0.bmp", [System.Drawing.Imaging.ImageFormat]::Bmp );
47 |
48 | $bmpSmall.Save("$(get-location)\small-$iconIndex_0.jpg", [System.Drawing.Imaging.ImageFormat]::Jpeg);
49 | $bmpLarge.Save("$(get-location)\large-$iconIndex_0.jpg", [System.Drawing.Imaging.ImageFormat]::Jpeg);
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/examples/WinAPI/setMouseSpeed.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [validateRange(1,20)]
3 | [int] $newSpeed
4 | )
5 |
6 | set-strictMode -version latest
7 |
8 | $winApi = add-type -name user32 -namespace tq84 -passThru -memberDefinition '
9 | [DllImport("user32.dll")]
10 | public static extern bool SystemParametersInfo(
11 | uint uiAction,
12 | uint uiParam ,
13 | uint pvParam ,
14 | uint fWinIni
15 | );
16 | '
17 |
18 | $SPI_SETMOUSESPEED = 0x0071
19 |
20 | "MouseSensitivity before WinAPI call: $((get-itemProperty 'hkcu:\Control Panel\Mouse').MouseSensitivity)"
21 |
22 | $null = $winApi::SystemParametersInfo($SPI_SETMOUSESPEED, 0, $newSpeed, 0)
23 |
24 | #
25 | # Calling SystemParametersInfo() does not permanently store the modification
26 | # of the mouse speed. It needs to be changed in the registry as well
27 | #
28 | "MouseSensitivity after WinAPI call: $((get-itemProperty 'hkcu:\Control Panel\Mouse').MouseSensitivity)"
29 |
30 | set-itemProperty 'hkcu:\Control Panel\Mouse' -name MouseSensitivity -value $newSpeed
31 |
--------------------------------------------------------------------------------
/examples/message-box/img/user32-MessageBox.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/examples/message-box/img/user32-MessageBox.png
--------------------------------------------------------------------------------
/examples/message-box/user32-MessageBox.ps1:
--------------------------------------------------------------------------------
1 | add-type -typeDefinition @"
2 | using System;
3 | using System.Runtime.InteropServices;
4 |
5 | public static partial class user32 {
6 |
7 | [DllImport("user32.dll", CharSet=CharSet.Auto)]
8 | public static extern Int32 MessageBox(
9 | IntPtr hWnd,
10 | String text,
11 | String caption,
12 | int options
13 | );
14 | }
15 | "@
16 |
17 | $chosen = [user32]::MessageBox(0, 'Yes or no?' , 'Choose wisely', 4) # 4: MB_OKCANCEL
18 |
19 | if ($chosen -eq 6) { # 6: ID_YES
20 | write-host "Yeah!"
21 | }
22 | else { # 7: ID_NO
23 | write-host "Nay!"
24 | }
25 |
--------------------------------------------------------------------------------
/examples/registry/add-another-value.ps1:
--------------------------------------------------------------------------------
1 | $null = new-itemProperty -path HKCU:\Software\tq84 -name someValue -value 99
2 |
--------------------------------------------------------------------------------
/examples/registry/add-value-num.ps1:
--------------------------------------------------------------------------------
1 | $null = new-itemProperty -path HKCU:\Software\tq84 -name num -value 42 -propertyType DWord
2 |
--------------------------------------------------------------------------------
/examples/registry/add-value-txt.ps1:
--------------------------------------------------------------------------------
1 | $null = new-itemProperty -path HKCU:\Software\tq84 -value "Hello world" -name txt
2 |
--------------------------------------------------------------------------------
/examples/registry/all.ps1:
--------------------------------------------------------------------------------
1 | . ./delete-keys-and-values.ps1
2 |
3 | . ./create-new-key.ps1
4 | . ./default-value.ps1
5 | . ./add-value-txt.ps1
6 | . ./add-another-value.ps1
7 | . ./add-value-num.ps1
8 | . ./use-object.ps1
9 |
10 | . ./get-itemPropertyValue.ps1
11 | . ./get-itemProperty.ps1
12 |
13 | . ./check-if-key-or-value-exists.ps1
14 |
--------------------------------------------------------------------------------
/examples/registry/check-if-key-or-value-exists.ps1:
--------------------------------------------------------------------------------
1 | if (test-path HKCU:\Software\tq84) {
2 |
3 | write-output "The registry key HKCU\Software\tq84 exists"
4 |
5 | $key = get-item HKCU:\Software\tq84
6 |
7 | if ($key.getValue('num ') -ne $null) {
8 | write-output "value num in key HKCU\Software\tq84"
9 | }
10 | else {
11 | write-output 'num does not exist in key HKCU\Software\tq84'
12 | }
13 |
14 | if ($key.getValue("unobtainium") -ne $null) {
15 | write-output "unobtainium exists in key HKCU\Software\tq84"
16 | }
17 | else {
18 | write-output "unobtainium does not exist in key HKCU\Software\tq84"
19 | }
20 |
21 | }
22 | else {
23 | write-output "The registry key HKCU\Software\tq84 does not exist"
24 | }
25 |
26 |
27 | if (test-path HKCU:\a\path\that\likely\does\not\exist) {
28 | write-output "The registry key 'HKCU\a\path\that\likely\does\not\exist' exists"
29 | }
30 | else {
31 | write-output "The registry key 'HKCU\a\path\that\likely\does\not\exist' does not exist"
32 | }
33 |
--------------------------------------------------------------------------------
/examples/registry/create-keys-and-values.ps1:
--------------------------------------------------------------------------------
1 |
2 |
3 | #
4 | # Create a sub key and specify its default value on one go.
5 | # Return registry key object into variable:
6 | #
7 | $subKey = new-item -path HKCU:\Software\tq84 -value 'default value sub key' -name subKey
8 |
9 | #
10 | # The registry object offers a few method that can be used
11 | # to create keys and values so that new-itemProperty
12 | # is not required anymore
13 | #
14 |
--------------------------------------------------------------------------------
/examples/registry/create-new-key.ps1:
--------------------------------------------------------------------------------
1 | $key_tq84 = new-item -path HKCU:\Software -name tq84
2 |
3 | $key_tq84.GetType().FullName
4 |
--------------------------------------------------------------------------------
/examples/registry/default-value.ps1:
--------------------------------------------------------------------------------
1 | $null = set-item -path HKCU:\Software\tq84 -value "This is the default value"
2 |
--------------------------------------------------------------------------------
/examples/registry/delete-keys-and-values.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Delete a value (value three) under a given key (HKCU\Software\tq84)
3 | #
4 | #q remove-itemProperty -path HKCU:\Software\tq84 -name "value three"
5 |
6 | #
7 | # Delete an entire key (with all its remaining values)
8 | #
9 | remove-item -path HKCU:\Software\tq84 -recurse
10 |
--------------------------------------------------------------------------------
/examples/registry/get-itemProperty.ps1:
--------------------------------------------------------------------------------
1 | $values = get-itemProperty HKCU:\Software\tq84 -name num,txt
2 | $values.GetType().FullName
3 | #
4 | # System.Management.Automation.PSCustomObject
5 |
6 | write-host "The value of num is $($values.num)"
7 | write-host "The value of txt is $($values.txt)"
8 |
--------------------------------------------------------------------------------
/examples/registry/get-itemPropertyValue.ps1:
--------------------------------------------------------------------------------
1 | $val_num = get-itemPropertyValue HKCU:\Software\tq84 -name num
2 | write-host "The value of num is $val_num"
3 |
--------------------------------------------------------------------------------
/examples/registry/img/inserted-values.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/examples/registry/img/inserted-values.png
--------------------------------------------------------------------------------
/examples/registry/read-default-value.ps1:
--------------------------------------------------------------------------------
1 | get-itemPropertyValue HKCU:\Software\tq84 -name '(default)'
2 |
--------------------------------------------------------------------------------
/examples/registry/use-object.ps1:
--------------------------------------------------------------------------------
1 | $key_tq84.SetValue('V', 1 )
2 | $key_tq84.SetValue('W', 'xyz')
3 |
4 | $sub_key = $key_tq84.CreateSubKey('subKey')
5 | $sub_key.SetValue('', "sub key's default value")
6 |
--------------------------------------------------------------------------------
/host/ANSI/animated.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | $CSI="$([char]27)[" # PowerShell 6 has `e for [char]27
4 |
5 | "${CSI}2J" # Clear screen
6 |
7 |
8 | while (1) {
9 | foreach ($r_ in -255 .. 255) {
10 |
11 | $r = [Math]::Abs($r_)
12 |
13 | $g = 255-$r
14 | "${CSI}10;15H" + # Move to column 10, row 15
15 | "${CSI}38;2;$r;$g;200m" + # Set foreground coor (38;2) to RGB($r, $g, 200)
16 | "Foo, bar and baz!" # Write some text
17 |
18 | start-sleep -Milliseconds 10
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/host/ANSI/blink.ps1:
--------------------------------------------------------------------------------
1 | clear-host
2 |
3 | $CSI = "$([char]27)["
4 |
5 | "
6 |
7 | ${CSI}5;31mnormal read ${CSI}5;91mintense red${CSI}m
8 |
9 | "
10 |
--------------------------------------------------------------------------------
/host/ANSI/bold-underlined.ps1:
--------------------------------------------------------------------------------
1 | $CSI = "$([char]27)["
2 |
3 | "${CSI}1mbold${CSI}m and ${CSI}4munderlined${CSI}m"
4 |
--------------------------------------------------------------------------------
/host/ANSI/color-output/.gitignore:
--------------------------------------------------------------------------------
1 | xyz.txt
2 |
--------------------------------------------------------------------------------
/host/ANSI/color-output/create-file.ps1:
--------------------------------------------------------------------------------
1 | set-content `
2 | xyz.txt `
3 | -noNewLine `
4 | "one`r`ntwo`nthree`r`nfour`r`nfive`n"
5 |
--------------------------------------------------------------------------------
/host/ANSI/color-output/format-hex.ps1:
--------------------------------------------------------------------------------
1 | format-hex xyz.txt |
2 | out-string -stream |
3 | foreach-object {
4 | $line = $_
5 | #
6 | # Only apply coloring replacement on lines that don't start
7 | # with a white spce;
8 | #
9 | if ($line -match '^\S') {
10 | $line = $line -replace '(\b0[AD]\b)', "$([char]27)[38;5;9m`$1$([char]27)[0m"
11 | }
12 | $line
13 | }
14 |
--------------------------------------------------------------------------------
/host/ANSI/color-output/img/output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/host/ANSI/color-output/img/output.png
--------------------------------------------------------------------------------
/host/ANSI/foreground-background-16.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | $CSI = "$([char] 27)" + "["
4 |
5 | "normal " +
6 | $CSI +
7 | "9" + # high intensity foregroud
8 | "2" + # green
9 | "m" +
10 | "colored text" +
11 | "$CSI" +
12 | "m" + # reset
13 | " normal again"
14 |
15 | "normal " +
16 | $CSI +
17 | "4" + # normal intensity background
18 | "2" + # green
19 | "m" +
20 | "colored text" +
21 | "$CSI" +
22 | "m" + # reset
23 | " normal again"
24 |
--------------------------------------------------------------------------------
/host/ANSI/img/foreground-background-16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneNyffenegger/about-powershell/3cfbff7a93e3edc0d09d7731023bc0e5b9345237/host/ANSI/img/foreground-background-16.png
--------------------------------------------------------------------------------
/language/class/ToString/callToString.ps1:
--------------------------------------------------------------------------------
1 | $obj_with = new-object classWithToString 42, 'hello world'
2 | $obj_without = new-object classWithoutToString 99, 'ninety-nine'
3 |
4 | $obj_with.ToString()
5 | #
6 | # num = 42, text = hello world
7 |
8 | $obj_without.ToString()
9 | #
10 | # classWithoutToString
11 |
--------------------------------------------------------------------------------
/language/class/ToString/classWithToString.ps1:
--------------------------------------------------------------------------------
1 | class classWithToString {
2 |
3 | [int ] $num
4 | [string] $text
5 |
6 | classWithToString ($n, $t) {
7 | $this.num = $n
8 | $this.text = $t
9 | }
10 |
11 | [string] ToString() {
12 | return "num = $($this.num), text = $($this.text)"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/language/class/ToString/classWithoutToString.ps1:
--------------------------------------------------------------------------------
1 | class classWithoutToString {
2 |
3 | [int ] $num
4 | [string] $text
5 |
6 | classWithoutToString ($n, $t) {
7 | $this.num = $n
8 | $this.text = $t
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/language/class/ToString/go.ps1:
--------------------------------------------------------------------------------
1 | . ./classWithToString.ps1
2 | . ./classWithoutToString.ps1
3 | . ./callToString.ps1
4 | . ./stringInterpolation.ps1
5 | . ./select-string.ps1
6 |
--------------------------------------------------------------------------------
/language/class/ToString/select-string.ps1:
--------------------------------------------------------------------------------
1 | $obj_with, $obj_without | select-string o
2 | #
3 | # num = 42, text = hello world
4 | # classWithoutToString
5 |
--------------------------------------------------------------------------------
/language/class/ToString/stringInterpolation.ps1:
--------------------------------------------------------------------------------
1 | write-host "$obj_with"
2 | #
3 | # num = 42, text = hello world
4 |
5 | write-host "$obj_without"
6 | #
7 | # classWithoutToString
8 |
--------------------------------------------------------------------------------
/language/class/inheritance/simple.ps1:
--------------------------------------------------------------------------------
1 | class B {
2 | [int] $num
3 |
4 | B([int] $n) {
5 | $this.num = $n
6 | }
7 |
8 | [void] method() {
9 | write-host "$($this.num)"
10 | }
11 | }
12 |
13 | class D : B {
14 |
15 | [string] $txt
16 |
17 | D([int] $num, [string] $txt) : base($num)
18 | {
19 | $this.txt = $txt
20 | }
21 |
22 | [void] method()
23 | {
24 | write-host "$($this.num): $($this.txt)"
25 | }
26 |
27 | }
28 |
29 | $b = [B]::new(99)
30 | $b.method()
31 |
32 | $d = [D]::new(42, 'hello world')
33 | $d.method()
34 |
--------------------------------------------------------------------------------
/language/class/simple/CLS.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | class CLS {
4 | #
5 | # The class's member variables:
6 | #
7 | [int ] $num
8 | [string] $txt
9 |
10 | static [int] $accumulator = 42
11 |
12 | #
13 | # The class's constructor:
14 | #
15 | CLS($n, $t) {
16 | $this.num = $n
17 | $this.txt = $t
18 | }
19 |
20 | #
21 | # A member method that returns a string.
22 | #
23 | [string] combineNumAndTxt() {
24 | return "$($this.num) - $($this.txt)"
25 | }
26 |
27 | #
28 | # A member method that doesn't return
29 | # a value. It's «return type» can be
30 | # explicitely specified as void:
31 | #
32 | [void] printMembers() {
33 | write-host $this.combineNumAndTxt()
34 | }
35 |
36 | #
37 | # A static method
38 | #
39 | static [Int] add($x) {
40 | [CLS]::accumulator += $x
41 | return [CLS]::accumulator
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/language/class/simple/_run.ps1:
--------------------------------------------------------------------------------
1 | . ./CLS.ps1
2 | . ./create-instance.ps1
3 | . ./call-methods.ps1
4 | . ./call-static-method.ps1
5 | . ./type.ps1
6 |
--------------------------------------------------------------------------------
/language/class/simple/call-methods.ps1:
--------------------------------------------------------------------------------
1 | write-host "obj.num = $($obj.num), obj.txt = $($obj.txt)"
2 | #
3 | # obj.num = 42, obj.txt = hello world
4 |
5 | write-host $obj.combineNumAndTxt()
6 | #
7 | # 42 - hello world
8 |
9 | $obj.printMembers()
10 | #
11 | # 42 - hello world
12 |
--------------------------------------------------------------------------------
/language/class/simple/call-static-method.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Invoke a static method
3 | #
4 | [CLS]::add(57)
5 | #
6 | # 99
7 |
--------------------------------------------------------------------------------
/language/class/simple/create-instance.ps1:
--------------------------------------------------------------------------------
1 | $obj = [CLS]::new(42, 'hello world')
2 | $anotherObj = new-object CLS 99, 'ninety-nine'
3 |
--------------------------------------------------------------------------------
/language/class/simple/type.ps1:
--------------------------------------------------------------------------------
1 | $obj.GetType().FullName
2 | #
3 | # CLS
4 |
5 | $obj.GetType().BaseType.FullName
6 | #
7 | # System.Object
8 |
--------------------------------------------------------------------------------
/language/cmdlet/parameter/common/errorVariable/get-inexisting-item.ps1:
--------------------------------------------------------------------------------
1 | $item = get-item `
2 | inexisting-item `
3 | -errorVariable err `
4 | -errorAction silentlyContinue
5 |
6 |
7 | if ($err) {
8 | write-host $err
9 | }
10 | else {
11 | write-host "item $item found"
12 | }
13 |
--------------------------------------------------------------------------------
/language/cmdlet/parameter/common/informationVariable.ps1:
--------------------------------------------------------------------------------
1 | function do-x {
2 | [cmdletBinding()] param()
3 |
4 | write-information "do-x was called"
5 | }
6 |
7 | function do-y {
8 | [cmdletBinding()] param()
9 |
10 | write-information "do-y was called"
11 | do-x
12 | }
13 |
14 | do-y -informationAction continue -informationVariable informationGathered
15 |
16 | "Type of `$informationGathered: $($informationGathered.GetType().Fullname)"
17 | foreach ($info in $informationGathered) {
18 | "Info: $info"
19 | }
20 |
--------------------------------------------------------------------------------
/language/cmdlet/parameter/set/Test-ParameterSet.cs:
--------------------------------------------------------------------------------
1 | //
2 | // csc -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\system.management.automation.dll" -target:library Test-ParameterSet.cs
3 | //
4 | // import-module .\Test-ParameterSet.dll
5 | //
6 | using System.Management.Automation;
7 |
8 | [Cmdlet(
9 | "Test", "ParameterSet",
10 | DefaultParameterSetName = "paramSetNum"
11 | )]
12 | [OutputType("System.String")]
13 | public class AddStrings : Cmdlet {
14 |
15 | [Parameter(
16 | Position = 0,
17 | Mandatory = true,
18 | ParameterSetName = "paramSetTxt"
19 | )]
20 | public string txt { get; set; }
21 |
22 | [Parameter(
23 | Position = 0,
24 | Mandatory = true,
25 | ParameterSetName = "paramSetNum"
26 | )]
27 | public ulong num { get; set; }
28 |
29 | protected override void ProcessRecord() {
30 | WriteObject("num = " + num + ", txt = " + txt);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/language/enum/base-class.ps1:
--------------------------------------------------------------------------------
1 | enum E {
2 | foo
3 | bar
4 | baz
5 | }
6 |
7 | [E].BaseType.FullName
8 | #
9 | # System.Enum
10 |
--------------------------------------------------------------------------------
/language/enum/flags.ps1:
--------------------------------------------------------------------------------
1 | [flags()] enum fruitAttribute {
2 | big = 0x01
3 | old = 0x02
4 | green = 0x04
5 | sweet = 0x08
6 | }
7 |
8 | enum fruitSelection {
9 | apple
10 | banana
11 | cherries
12 | }
13 |
14 | write-host "value of big: $([fruitAttribute]::big -as [int])"
15 | write-host "value of old: $([fruitAttribute]::old -as [int])"
16 | write-host "value of green: $([fruitAttribute]::green -as [int])"
17 | write-host "value of sweet: $([fruitAttribute]::sweet -as [int])"
18 |
19 | function buy {
20 |
21 | param (
22 | [fruitSelection] $fruit,
23 | [fruitAttribute] $attributes
24 | )
25 |
26 | write-host
27 |
28 | if ($fruit -eq [fruitSelection]::apple ) { write-host "You're buying an apple" }
29 | if ($fruit -eq [fruitSelection]::banana ) { write-host "You're buying a banana" }
30 | if ($fruit -eq [fruitSelection]::cherries) { write-host "You're buying cherries" }
31 |
32 | write-host "The attributes are:" # Alternatively use $attributes in the string
33 |
34 | if ($attributes -band [fruitAttribute]::big ) { write-host ' big' }
35 | if ($attributes -band [fruitAttribute]::old ) { write-host ' old' }
36 | if ($attributes -band [fruitAttribute]::green) { write-host ' green' }
37 | if ($attributes -band [fruitAttribute]::sweet) { write-host ' sweet' }
38 |
39 | #
40 | # Alternatively, use hasFlag() to check for existence of a flag:
41 | #
42 | # if ($attributes.hasFlag([fruitAttribute]::big )) { write-host ' big' }
43 |
44 | }
45 |
46 | buy banana ( [fruitAttribute]::old -bor [fruitAttribute]::green)
47 | buy apple ( [fruitAttribute]::green )
48 | buy cherries ( [fruitAttribute]::green -bor [fruitAttribute]::old -bor [fruitAttribute]::big)
49 | buy apple ( [fruitAttribute]::sweet )
50 |
--------------------------------------------------------------------------------
/language/enum/play-rock-paper-scissors.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | enum roshambo {
4 | rock
5 | paper
6 | scissors
7 | }
8 |
9 | enum outcome {
10 | win
11 | draw
12 | loss
13 | }
14 |
15 | function play-rock-paper-scissors {
16 |
17 | param (
18 | [roshambo] $player_1,
19 | [roshambo] $player_2
20 | )
21 |
22 | if ($player_1 -eq $player_2) { return [outcome]::draw }
23 |
24 | if ( ( $player_1 -eq [roshambo]::rock ) -and ( $player_2 -eq [roshambo]::scissors ) ) { return [outcome]::win }
25 | if ( ( $player_1 -eq [roshambo]::paper ) -and ( $player_2 -eq [roshambo]::rock ) ) { return [outcome]::win }
26 | if ( ( $player_1 -eq [roshambo]::scissors) -and ( $player_2 -eq [roshambo]::paper ) ) { return [outcome]::win }
27 |
28 | return [outcome]::loss
29 |
30 | }
31 |
32 | play-rock-paper-scissors rock rock
33 | play-rock-paper-scissors rock paper
34 | play-rock-paper-scissors rock scissor
35 |
36 | play-rock-paper-scissors paper rock
37 | play-rock-paper-scissors scissor rock
38 | play-rock-paper-scissors roc rock
39 |
--------------------------------------------------------------------------------
/language/function/begin-process-end-block/sum.ps1:
--------------------------------------------------------------------------------
1 | function sum {
2 | begin { $s = 0 }
3 | process { $s += $_ }
4 | end { $s }
5 | }
6 |
7 | 7, 3, 9, 1, 22 | sum
8 | #
9 | # 42
10 |
--------------------------------------------------------------------------------
/language/function/begin-process-end-block/with-without-process.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Define a function with all three blocks:
3 | # begin, process and end
4 | #
5 | function show-beginProcessEnd {
6 | begin { "begin: input = $input" }
7 | process { "process: input = $input" }
8 | end { "end: input = $input" }
9 | }
10 |
11 | #
12 | # Define another function that does not have
13 | # the process block
14 | #
15 | function show-beginEnd {
16 | begin { "begin: input = $input" }
17 | end { "end: input = $input" }
18 | }
19 |
20 | #
21 | # Pipe a few objects into the first function
22 | #
23 | 1 .. 4 | show-beginProcessEnd
24 | #
25 | # begin: input =
26 | # process: input = 1
27 | # process: input = 2
28 | # process: input = 3
29 | # process: input = 4
30 | # end: input =
31 |
32 | #
33 | # Pipe a few objects into the second function
34 | #
35 | 1 .. 4 | show-beginEnd
36 | #
37 | # begin: input =
38 | # end: input = 1 2 3 4
39 |
--------------------------------------------------------------------------------
/language/function/cmdletBinding/write-verbose.ps1:
--------------------------------------------------------------------------------
1 | function wv-with {
2 |
3 | [cmdletBinding()]
4 | param($p)
5 |
6 | write-verbose "param is $p"
7 | }
8 |
9 | function wv-without {
10 |
11 | param($p)
12 |
13 | write-verbose "param is $p"
14 | }
15 |
16 | wv-with XYZ
17 | wv-with XYZ -verbose
18 |
19 | wv-without XYZ
20 | wv-without XYZ -verbose
21 |
--------------------------------------------------------------------------------
/language/function/parameter/default-value.ps1:
--------------------------------------------------------------------------------
1 | function saySomething {
2 |
3 | param(
4 | [string] $text = 'hello world'
5 | )
6 |
7 | write-host $text
8 | }
9 |
10 | saySomething
11 | saySomething 'good bye'
12 |
--------------------------------------------------------------------------------
/language/function/parameter/info.ps1:
--------------------------------------------------------------------------------
1 | $params = (get-command mkdir).parameters
2 |
3 | foreach ($param in $params.keys) {
4 | $paramMeta = $params[$param]
5 | '{0,-20} {1,-6} {2}' -f $paramMeta.name, $paramMeta.aliases[0], $paramMeta.parameterType
6 | }
7 | #
8 | # Path System.String[]
9 | # Name System.String
10 | # Value System.Object
11 | # Force System.Management.Automation.SwitchParameter
12 | # Credential System.Management.Automation.PSCredential
13 | # Verbose vb System.Management.Automation.SwitchParameter
14 | # Debug db System.Management.Automation.SwitchParameter
15 | # ErrorAction ea System.Management.Automation.ActionPreference
16 | # WarningAction wa System.Management.Automation.ActionPreference
17 | # InformationAction infa System.Management.Automation.ActionPreference
18 | # ErrorVariable ev System.String
19 | # WarningVariable wv System.String
20 | # InformationVariable iv System.String
21 | # OutVariable ov System.String
22 | # OutBuffer ob System.Int32
23 | # PipelineVariable pv System.String
24 | # WhatIf wi System.Management.Automation.SwitchParameter
25 | # Confirm cf System.Management.Automation.SwitchParameter
26 | # UseTransaction usetx System.Management.Automation.SwitchParameter
27 |
--------------------------------------------------------------------------------
/language/function/parameter/pass-by-reference/call.ps1:
--------------------------------------------------------------------------------
1 | [string] $xyz = ''
2 |
3 | demonstrate-passing-by-reference ([ref] $xyz)
4 |
5 | write-host "xyz after calling function: $xyz"
6 |
--------------------------------------------------------------------------------
/language/function/parameter/pass-by-reference/func.ps1:
--------------------------------------------------------------------------------
1 | function demonstrate-passing-by-reference {
2 | param (
3 | [ref][string] $result
4 | )
5 |
6 | $result.value = 'value assigned in function'
7 | }
8 |
--------------------------------------------------------------------------------
/language/function/parameter/pass-by-reference/object.ps1:
--------------------------------------------------------------------------------
1 | function change-values {
2 | param (
3 | $p
4 | )
5 |
6 | $p.txt = 'changed'
7 | $p.num = 99
8 | }
9 |
10 | $hash = @{num = 42; txt = 'Hello world'}
11 | $obj = new-object psObject -property @{num = 42; txt = 'Hello world'}
12 |
13 | change-values $hash
14 | change-values $obj
15 |
16 | write-host "num = $($hash.num), txt = $($hash.txt)"
17 | write-host "num = $($obj.num ), txt = $($obj.txt )"
18 |
--------------------------------------------------------------------------------
/language/function/parameter/splatting.ps1:
--------------------------------------------------------------------------------
1 | function splat {
2 | param ($p1, $p2, $p3)
3 |
4 | "`$p1 = $p1, `$p2 = $p2, `$p3 = $p3"
5 | }
6 |
7 | $hashTable = @{p3 = 'baz'; p1 = 'foo'; p2 = 'bar'}
8 |
9 | #
10 | # Invoke splat with a hash table, without splatting
11 | #
12 | splat $hashTable
13 | #
14 | # $p1 = System.Collections.Hashtable, $p2 = , $p3 =
15 |
16 | #
17 | # Invoke splat with a hash table, with splatting. Note the use of @ rather than $:
18 | #
19 | splat @hashTable
20 | #
21 | # $p1 = foo, $p2 = bar, $p3 = baz
22 |
23 | $array = 7, 2, 5
24 |
25 | #
26 | # Invoke splat with an array, without splatting
27 | #
28 | splat $array
29 | #
30 | # $p1 = 7 2 5, $p2 = , $p3 =
31 |
32 | #
33 | # Invoke splat with an array, with splatting
34 | #
35 | splat @array
36 | #
37 | # $p1 = 7, $p2 = 2, $p3 = 5
38 |
39 | #
40 | # Use a splatting AND explicit defined parameter:
41 | #
42 | $ht2 = @{p2 = 'world'; p1 = 'hello'}
43 | splat @ht2 -p3 'P3'
44 | #
45 | # $p1 = hello, $p2 = world, $p3 = P3
46 |
--------------------------------------------------------------------------------
/language/function/parameter/switch/func-with-switch.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | function abc {
4 | param (
5 | [switch] $F,
6 | [string] $T,
7 | [int ] $N
8 | )
9 |
10 | write-host "F = $F, T = $T, N = $N"
11 | }
12 |
13 | function xyz {
14 |
15 | param (
16 | [int ] $num,
17 | [switch] $flg,
18 | [string] $txt
19 | )
20 |
21 | write-host "flg = $flg, num = $num, txt = $txt"
22 |
23 | abc -F:$flg -T $txt -N $num
24 | }
25 |
26 | $xyzParameters = (get-command xyz).parameters
27 |
28 | $xyzParameters['num'].Attributes[0].Position # 0
29 | $xyzParameters['flg'].Attributes[0].Position # -2147483648
30 | $xyzParameters['txt'].Attributes[0].Position # 1
31 |
32 | xyz -flg 42 hello
33 | xyz 42 hello
34 | xyz 42 hello -flg
35 |
--------------------------------------------------------------------------------
/language/lexical-structure/token/literal/expandable-here-string.ps1:
--------------------------------------------------------------------------------
1 | $num = 42
2 | $value = 'forty-two'
3 |
4 | $text = @"
5 | The number is: $num,
6 | and it's value "$value"
7 | "@
8 |
9 | write-host $text
10 |
--------------------------------------------------------------------------------
/language/object/psObject/ToString.ps1:
--------------------------------------------------------------------------------
1 | $psObj_1 = @{ val_1 = 'one' ; val_2 = 'two' ; val_3 = 'three' }
2 | $psObj_2 = @{ val_1 = 'foo' ; val_2 = 'bar' ; val_3 = 'baz' }
3 |
4 | $psObj_2 | add-member `
5 | -memberType scriptMethod `
6 | -name ToString {
7 | "val 1: $($this.val_1), " +
8 | "val 2: $($this.val_2), " +
9 | "val 3: $($this.val_3)"
10 | } `
11 | -force
12 |
13 | $psObj_1.ToString()
14 | #
15 | # System.Collections.Hashtable
16 |
17 | $psObj_2.ToString()
18 | #
19 | # val 1: foo, val 2: bar, val 3: baz
20 |
21 |
22 | #
23 | # Unfortunately, this version of ToString is
24 | # not used when not called explicitetly, as
25 | # for example when strings are interpolated:
26 | #
27 | write-host "psObj_1: $psObj_1"
28 | #
29 | # psObj_1: System.Collections.Hashtable
30 |
31 | write-host "psObj_2: $psObj_2"
32 | #
33 | # psObj_2: System.Collections.Hashtable
34 |
--------------------------------------------------------------------------------
/language/object/psObject/add-member.ps1:
--------------------------------------------------------------------------------
1 | $obj | add-member -memberType noteProperty -name theNumber -value 42
2 | $obj | add-member -memberType noteProperty -name someText -value 'foo, bar, baz'
3 |
4 | write-output "num = $($obj.theNumber), text = $($obj.someText)"
5 | #
6 | # num = 42, text = foo, bar, baz
7 |
--------------------------------------------------------------------------------
/language/object/psObject/create-object.ps1:
--------------------------------------------------------------------------------
1 | $obj = new-object System.Int64
2 |
--------------------------------------------------------------------------------
/language/object/psObject/obj-get-extended-members.ps1:
--------------------------------------------------------------------------------
1 | $obj | get-member -view extended
2 | #
3 | # TypeName: System.Int64
4 | #
5 | # Name MemberType Definition
6 | # ---- ---------- ----------
7 | # someText NoteProperty string someText=foo, bar, baz
8 | # theNumber NoteProperty int theNumber=42
9 |
--------------------------------------------------------------------------------
/language/object/psObject/psObject-baseObject.ps1:
--------------------------------------------------------------------------------
1 | $psObj.baseObject.GetType().FullName
2 | #
3 | # System.Int64
4 |
--------------------------------------------------------------------------------
/language/object/psObject/psObject-properties.ps1:
--------------------------------------------------------------------------------
1 | $psObj.properties
2 | #
3 | # MemberType : NoteProperty
4 | # IsSettable : True
5 | # IsGettable : True
6 | # Value : 42
7 | # TypeNameOfValue : System.Int32
8 | # Name : theNumber
9 | # IsInstance : True
10 | #
11 | # MemberType : NoteProperty
12 | # IsSettable : True
13 | # IsGettable : True
14 | # Value : foo, bar, baz
15 | # TypeNameOfValue : System.String
16 | # Name : someText
17 | # IsInstance : True
18 |
--------------------------------------------------------------------------------
/language/object/psObject/psObject.ps1:
--------------------------------------------------------------------------------
1 | $psObj = $obj.psObject
2 |
3 | $psObj.GetType().FullName
4 | #
5 | # System.Management.Automation.PSObject
6 |
--------------------------------------------------------------------------------
/language/object/type/accelerators/get.ps1:
--------------------------------------------------------------------------------
1 | $accels = [psObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get
2 | $names = $accels.keys | sort-object
3 |
4 | foreach ($name in $names) {
5 | '{0, -30} {1}' -f $name, $accels[$name].FullName
6 | }
7 |
--------------------------------------------------------------------------------
/language/operator/array-subexpression/array-from-funcs.ps1:
--------------------------------------------------------------------------------
1 | $ary_0 = @( func_0 )
2 | $ary_1 = @( func_1 )
3 | $ary_n = @( func_n )
4 |
5 | $ary_0.GetType().FullName # System.Object[]
6 | $ary_1.GetType().FullName # System.Object[]
7 | $ary_n.GetType().FullName # System.Object[]
8 |
9 | $ary_0.length # 0
10 | $ary_1.length # 1
11 | $ary_n.length # 3
12 |
--------------------------------------------------------------------------------
/language/operator/array-subexpression/funcs.ps1:
--------------------------------------------------------------------------------
1 | function func_0 { }
2 | function func_1 { 'one element ' }
3 | function func_n { 'foo', 'bar', 'baz' }
4 |
--------------------------------------------------------------------------------
/language/operator/as.ps1:
--------------------------------------------------------------------------------
1 | 123.45 -as [int] # 123
2 | "42" + "13" # 4213
3 | ("42" -as [int]) + ("13" -as [int]) # 55
4 |
--------------------------------------------------------------------------------
/language/operator/call/access-module-variable.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | import-module ./mdl.psm1
4 |
5 | incVar
6 | incVar
7 | incVar
8 | decVar
9 |
10 | & (get-module mdl) { write-host "value of variable is $private_variable" }
11 |
--------------------------------------------------------------------------------
/language/operator/call/mdl.psm1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | [int] $private_variable = 40
4 |
5 | function incVar {
6 | $script:private_variable++
7 | write-host "var = $script:private_variable"
8 | }
9 |
10 | function decVar {
11 | $script:private_variable
12 | write-host "var = $script:private_variable"
13 | }
14 |
--------------------------------------------------------------------------------
/language/operator/call/no-new-process/call-script.ps1:
--------------------------------------------------------------------------------
1 | write-host "My PID is $PID"
2 |
3 | & ./the-script.ps1
4 |
--------------------------------------------------------------------------------
/language/operator/call/no-new-process/the-script.ps1:
--------------------------------------------------------------------------------
1 | write-host "the-script.ps1 runs with PID = $PID"
2 |
--------------------------------------------------------------------------------
/language/operator/call/printSomething.ps1:
--------------------------------------------------------------------------------
1 | $printSomething = 'write-host'
2 | & $printSomething 'hello World'
3 |
--------------------------------------------------------------------------------
/language/operator/call/script-block/Hello-world.ps1:
--------------------------------------------------------------------------------
1 | $scriptBlock = { write-host 'Hello world' }
2 |
3 | & $scriptBlock
4 |
--------------------------------------------------------------------------------
/language/operator/call/script-block/param.ps1:
--------------------------------------------------------------------------------
1 | $sb = {
2 | param($param_1, $param_2)
3 |
4 | write-output "param_1 = $param_1"
5 | write-output "param_2 = $param_2"
6 | }
7 |
8 | & $sb -param_1 42 -param_2 'hello world'
9 |
--------------------------------------------------------------------------------
/language/operator/call/script-block/variables.ps1:
--------------------------------------------------------------------------------
1 | $num = 99
2 |
3 | $scriptBlock = {
4 |
5 | write-host "num = $num"
6 | write-host "txt = $txt"
7 |
8 | $txt = 'changed'
9 | $num = 0
10 |
11 | }
12 |
13 | $num = 42
14 | $txt ='Hello world'
15 |
16 | & $scriptBlock
17 |
18 | echo "txt (after running scriptBlock): $txt"
19 | echo "num (after running scriptBlock): $num"
20 |
21 | #
22 | # Script output is:
23 | #
24 | # num = 42
25 | # txt = Hello world
26 | # txt (after running scriptBlock): Hello world
27 | # num (after running scriptBlock): 42
28 |
--------------------------------------------------------------------------------
/language/operator/comparison/match_notmatch/matches-variable.ps1:
--------------------------------------------------------------------------------
1 | 'First number: 42, second number: 99, third number 18.' -match '(\d+)\D+(\d+)\D+(\d+)'
2 | #
3 | # True
4 |
5 | # Print entire matching string:
6 | $matches[0]
7 | #
8 | # 42, second number: 99, third number 18
9 |
10 | # First, second and third number:
11 | $matches[1]
12 | #
13 | # 42
14 |
15 | $matches[2]
16 | #
17 | # 99
18 |
19 | $matches[3]
20 | #
21 | # 18
22 |
--------------------------------------------------------------------------------
/language/operator/comparison/match_notmatch/named-capture-group.ps1:
--------------------------------------------------------------------------------
1 | 'First number: 42, second number: 99, third number 18.' -match '(?\d+)\D+(?\d+)\D+(?\d+)'
2 | #
3 | # True
4 |
5 | # Print entire matching string:
6 | $matches[0]
7 | #
8 | # 42, second number: 99, third number 18
9 |
10 | # First, second and third number:
11 | $matches['first']
12 | #
13 | # 42
14 |
15 | $matches['second']
16 | #
17 | # 99
18 |
19 | $matches['third']
20 | #
21 | # 18
22 |
--------------------------------------------------------------------------------
/language/operator/comparison/objects.ps1:
--------------------------------------------------------------------------------
1 | class C {
2 |
3 | [Int32] hidden $val
4 |
5 | C($v) {
6 | $this.val = $v
7 | }
8 | }
9 |
10 |
11 | $obj_1 = [C]::new(4)
12 | $obj_2 = [C]::new(2)
13 | $obj_3 = [C]::new(4)
14 |
15 | $obj_4 = $obj_1
16 |
17 | $obj_1 -eq $obj_4 # $obj_1 and $obj_4 refer to the same object -> operator returns $true
18 | $obj_1 -eq $obj_3 # $obj_1 and $obj_3 refer to different objects -> operator returns $false
19 |
--------------------------------------------------------------------------------
/language/operator/comparison/required-methods.ps1:
--------------------------------------------------------------------------------
1 | class C : IComparable {
2 |
3 | [int] hidden $val
4 |
5 | C([int] $v) {
6 | $this.val = $v
7 | }
8 |
9 | [bool] Equals([Object] $other) {
10 | #
11 | # Equals() is required for the -eq operator.
12 | #
13 | return $this.val -eq $other.val
14 | }
15 |
16 | [int] CompareTo([Object] $other) {
17 | #
18 | # CompareTo() is required for the -lt
19 | # and -gt operator.
20 | #
21 | return $this.val - $other.val
22 | }
23 |
24 | [int] GetHashCode() {
25 | #
26 | # An object that overrides the Equals() method
27 | # should (must?) also override GetHashCode()
28 | #
29 | return $this.val
30 | }
31 | }
32 |
33 |
34 | $four = [C]::new(4)
35 | $seven = [C]::new(7)
36 | $VII = [C]::new(7)
37 |
38 | $four -lt $seven # True
39 | $four -gt $seven # False
40 | $four -eq $seven # False
41 | $seven -eq $seven # True
42 | $seven -eq $VII # True
43 |
--------------------------------------------------------------------------------
/language/operator/comparison/scalar-vs-array.ps1:
--------------------------------------------------------------------------------
1 | 4 -gt 2
2 | #
3 | # True
4 |
5 | 4 -gt 5
6 | #
7 | # False
8 |
9 | 4, 6, 3, 5, 7 -gt 4 -join ', '
10 | #
11 | # 6, 5, 7
12 |
--------------------------------------------------------------------------------
/language/operator/contains/like-vs-contains.ps1:
--------------------------------------------------------------------------------
1 | "hello world" -contains '*llo*' # False
2 | "hello world" -like '*llo*' # True
3 |
4 | $items = 'foo', 'bar', 'baz'
5 | $items -contains 'bar' # True
6 | $items -contains 'xyz' # False
7 |
--------------------------------------------------------------------------------
/language/operator/contains/value-in-array.ps1:
--------------------------------------------------------------------------------
1 | $primes = 'two', 'three', 'five', 'seven', 'eleven', 'thirteen'
2 |
3 | function check($num) {
4 | if ($primes -contains $num) {
5 | echo "$num seems to be a small prime"
6 | }
7 | else {
8 | echo "$num does not seem to be a small prime"
9 | }
10 | }
11 |
12 | check 'one'
13 | check 'two'
14 | check 'three'
15 | check 'four'
16 |
--------------------------------------------------------------------------------
/language/operator/in/is-in-array.ps1:
--------------------------------------------------------------------------------
1 | $value = 'bar'
2 | if ($value -in 'foo', 'bar', 'baz') {
3 | write-host "$value is in array"
4 | }
5 |
6 | $value = 'xxx'
7 | if ($value -notIn 'foo', 'bar', 'baz') {
8 | write-host "$value is not in array"
9 | }
10 |
--------------------------------------------------------------------------------
/language/operator/is.ps1:
--------------------------------------------------------------------------------
1 | 'hello world' -is [string ] # True
2 | 'foo' -is [dateTime] # False
3 | 64 -is [int ] # True
4 | 64 -is [float ] # False
5 |
--------------------------------------------------------------------------------
/language/operator/redirection/.gitignore:
--------------------------------------------------------------------------------
1 | abc.txt
2 |
--------------------------------------------------------------------------------
/language/operator/redirection/encoding.ps1:
--------------------------------------------------------------------------------
1 | 'abc' > abc.txt
2 |
3 | if ($psVersionTable.psEdition -eq 'Desktop') {
4 | $bytes = get-content abc.txt -encoding byte
5 | }
6 | else {
7 | $bytes = get-content abc.txt -asByteStream
8 | }
9 |
10 | foreach ($byte in $bytes) {
11 | ' {0:x2} {1}' -f $byte, [char]$byte
12 | }
13 |
--------------------------------------------------------------------------------
/language/operator/string-manipulation/f/DateTime.ps1:
--------------------------------------------------------------------------------
1 | $dt = new-object dateTime 2021,03,17 , 14,09,53
2 |
3 | write-host "The value of dt is $('{0:yyyy-MM-dd HH:mm:ss}' -f $dt)"
4 |
--------------------------------------------------------------------------------
/language/operator/string-manipulation/f/positional-arguments-and-alignment.ps1:
--------------------------------------------------------------------------------
1 | echo ("0: {0} - 2:{2} - 1: {1}" -f 'zero', 'one', 'two')
2 | #
3 | # 0: zero - 2:two - 1: one
4 |
5 | #
6 | # {x, n) right aligns the xth element with n places
7 | #
8 | # {x,-n) left aligns the xth element with n places
9 | #
10 | forEach ($item in ('five', 5), ('a hundred', 100), ('two', 2), ('forty-two', 42) ) {
11 | echo ("{0,-10}: {1,3}" -f $item[0], $item[1])
12 | }
13 | #
14 | # five : 5
15 | # a hundred : 100
16 | # two : 2
17 | # forty-two : 42
18 |
--------------------------------------------------------------------------------
/language/operator/string-manipulation/replace.ps1:
--------------------------------------------------------------------------------
1 | # Replace in ONE string
2 | #
3 | 'foo, bar and baz' -replace 'ba', 'xyz'
4 | #
5 | # foo, xyzr and xyzz
6 |
7 | # Replace in collection of strings
8 | #
9 | 'foo', 'bar', 'and', 'baz' -replace 'ba', 'xyz'
10 | #
11 | # foo
12 | # xyzr
13 | # and
14 | # xyzz
15 |
16 | # Replace with regular expressions.
17 | # Two adjacent equal letters are replaced
18 | # with the number 2 and the letter:
19 | #
20 | 'apple', 'pear', 'hello' -replace '(.)\1', '2$1' -join ', '
21 | #
22 | # a2ple, pear, he2lo
23 |
24 |
--------------------------------------------------------------------------------
/language/operator/string-manipulation/replace/psObjects.ps1:
--------------------------------------------------------------------------------
1 | $objs = `
2 | ( new-object psObject -property ( [ordered]@{ val_1 = 'one' ; val_2 = 'two' ; val_3 = 'three' } ) ) ,
3 | ( new-object psObject -property ( [ordered]@{ val_1 = 'foo' ; val_2 = 'bar' ; val_3 = 'baz' } ) ) ,
4 | ( new-object psObject -property ( [ordered]@{ val_1 = 'abcde' ; val_2 = 'fghij' ; val_3 = $null } ) ) ;
5 |
6 | $objs | foreach-object {
7 | $_.val_2 = $_.val_2 -replace 'o', 'X'
8 | $_
9 | }
10 |
11 | #
12 | # val_1 val_2 val_3
13 | # ----- ----- -----
14 | # one twX three
15 | # foo bar baz
16 | # abcde fghij
17 |
--------------------------------------------------------------------------------
/language/operator/string-manipulation/split-join.ps1:
--------------------------------------------------------------------------------
1 | $csv_line = 'foo;bar;baz;etc'
2 |
3 | $elems = $csv_line -split ';'
4 |
5 | $elems
6 | #
7 | # foo
8 | # bar
9 | # baz
10 | # etc
11 | #
12 |
13 |
14 | $joined = $elems -join '*'
15 |
16 | $joined
17 | #
18 | # foo*bar*baz*etc
19 | #
20 |
--------------------------------------------------------------------------------
/language/operator/subexpression/dayOfYear.ps1:
--------------------------------------------------------------------------------
1 | $dt = get-date
2 |
3 | write-host "Today is day $($dt.dayOfYear) in the year."
4 |
--------------------------------------------------------------------------------
/language/provider/env/expand.ps1:
--------------------------------------------------------------------------------
1 | write-output ""
2 | write-output "userprofile = $env:userprofile"
3 | write-output "home = $env:home"
4 | write-output ""
5 |
--------------------------------------------------------------------------------
/language/provider/env/show-all.ps1:
--------------------------------------------------------------------------------
1 | get-childItem -path env:
2 |
--------------------------------------------------------------------------------
/language/scope/function.ps1:
--------------------------------------------------------------------------------
1 | $var = 'assigned in script'
2 |
3 | function func() {
4 |
5 | #
6 | # Function did not not create its own $var yet, so
7 | # $var refers to $script:var
8 | #
9 | write-host " in func: var = $var"
10 |
11 | $var = 'assigned in function'
12 | $global:var = 'assigned in function with :global'
13 |
14 | #
15 | # Now, that the function has created its own $var,
16 | # $var refers to the function's $var, not to $script:var
17 | #
18 | write-host " in func: var = $var"
19 |
20 | #
21 | # Use modifiers to explicitely state what variable
22 | # is referred to:
23 | #
24 | write-host " in func: script:var = $script:var"
25 | write-host " in func: global:var = $global:var"
26 |
27 | }
28 |
29 | write-host "var = $var"
30 | write-host "calling func"
31 | func
32 | write-host ""
33 | write-host "var = $var"
34 | write-host "script:var = $script:var"
35 | write-host "global:var = $global:var"
36 |
37 | #
38 | # script prints:
39 | #
40 | # var = assigned in script
41 | # calling func.
42 | # in func: var = assigned in script
43 | # in func: var = assigned in function
44 | # in func: script:var = assigned in script
45 | # in func: global:var = assigned in function with :global
46 | #
47 | # var = assigned in script
48 | # script:var = assigned in script
49 | # global:var = assigned in function with :global
50 |
--------------------------------------------------------------------------------
/language/statement/break/exit-for.ps1:
--------------------------------------------------------------------------------
1 | for ($i=1; $i -le 5; $i++) {
2 | for ($j=1; $j -le 5; $j++) {
3 |
4 | $res = $i * $j
5 | write-output "$i * $j = $res"
6 |
7 | if ($res -ge 8) { # Exit the loop when i * j >= 8
8 | write-output ''
9 | break
10 | }
11 | }
12 | }
13 | #
14 | # 1 * 1 = 1
15 | # 1 * 2 = 2
16 | # 1 * 3 = 3
17 | # 1 * 4 = 4
18 | # 1 * 5 = 5
19 | # 2 * 1 = 2
20 | # 2 * 2 = 4
21 | # 2 * 3 = 6
22 | # 2 * 4 = 8
23 | #
24 | # 3 * 1 = 3
25 | # 3 * 2 = 6
26 | # 3 * 3 = 9
27 | #
28 | # 4 * 1 = 4
29 | # 4 * 2 = 8
30 | #
31 | # 5 * 1 = 5
32 | # 5 * 2 = 10
33 |
--------------------------------------------------------------------------------
/language/statement/for/simple.ps1:
--------------------------------------------------------------------------------
1 | for (
2 | [int] $num = 4 ; # Statement(s) that are executed before the loop is entered
3 | $num -lt 9 ; # Loop is exited when this condition is true at the end of the loop
4 | $num ++ # Statement to be executd if condition is not reached at end of loop
5 | ) {
6 |
7 | write-host("num = $num");
8 |
9 | }
10 | #
11 | # num = 4
12 | # num = 5
13 | # num = 6
14 | # num = 7
15 | # num = 8
16 |
--------------------------------------------------------------------------------
/language/statement/foreach/IEnumerator.ps1:
--------------------------------------------------------------------------------
1 | class tq84Enumerator: System.Collections.IEnumerator {
2 |
3 | [int] $val
4 |
5 | tq84Enumerator() {
6 | $this.Reset()
7 | }
8 |
9 | [object] get_Current() {
10 | return $this.val
11 | }
12 |
13 | [bool] MoveNext() {
14 | $this.val++
15 |
16 | if ($this.val -gt 13) {
17 | return $false
18 | }
19 | return $true
20 | }
21 |
22 | [void] Reset() {
23 | $this.val = 7
24 | }
25 | }
26 |
27 | $e = [tq84Enumerator]::new()
28 | foreach ($num in $e) {
29 | write-host "num = $num"
30 | }
31 |
--------------------------------------------------------------------------------
/language/statement/foreach/array.ps1:
--------------------------------------------------------------------------------
1 | $ar = 10 .. 14
2 |
3 | foreach ($elem in $ar) {
4 | $elem / 3
5 | }
6 |
7 | # 3.33333333333333
8 | # 3.66666666666667
9 | # 4
10 | # 4.33333333333333
11 | # 4.66666666666667
12 |
--------------------------------------------------------------------------------
/language/statement/foreach/break.ps1:
--------------------------------------------------------------------------------
1 | foreach ($num in 1 .. 10) {
2 |
3 | if ($num -eq 5) { break }
4 |
5 | write-host "$($num) * $($num) = $($num * $num)"
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/language/statement/foreach/continue.ps1:
--------------------------------------------------------------------------------
1 | forEach ($val in 'foo', 'bar', 'baz') {
2 |
3 | if ($val -eq 'foo') {
4 | write-host 'Skip processing of foo'
5 | continue
6 | }
7 |
8 | write-host "Processing $($val)"
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/language/statement/foreach/get-childItem.ps1:
--------------------------------------------------------------------------------
1 | foreach ($fileObj in get-childItem '*i*.ps1') {
2 |
3 | #
4 | # Convert the System.IO.FileInfo object to a string:
5 | #
6 | $fileStr = split-path -leaf $fileObj
7 |
8 | write-output $fileStr
9 | }
10 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/args.ps1:
--------------------------------------------------------------------------------
1 | function add {
2 | $args[0] + $args[1]
3 | }
4 |
5 | $sum = add 19 23
6 | write-output "sum is $sum"
7 | #
8 | # sum is 42
9 |
10 | $sum = add "foo" "bar"
11 | write-output "sum is $sum"
12 | #
13 | # sum is foobar
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/alias/qm.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [alias('?')] [switch] $help
3 | )
4 |
5 | if ($help) {
6 | 'help message'
7 | return
8 | }
9 |
10 | 'doing stuff'
11 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/parameter/mandatory/psBoundParameters.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [parameter(mandatory=$true )] $req,
3 | [parameter(mandatory=$false)] $opt
4 | )
5 |
6 | set-strictMode -version latest
7 |
8 | write-host "req = $req"
9 |
10 | if ($opt -eq $null) {
11 | #
12 | # The value of the parameter 'opt' is null
13 | # This is either …
14 | #
15 |
16 | if ($psBoundParameters.containsKey('opt')) {
17 | #
18 | # … because the invoker has explicitely
19 | # passed $null as value for the paramter …
20 | #
21 | write-host "opt was passed as null"
22 | }
23 | else {
24 | #
25 | # … or because
26 | # the paramter was not set (in which
27 | # case it defaults to $null).
28 | #
29 | write-host "opt was not passed (and is therefore null)"
30 | }
31 | }
32 | else {
33 | write-host "opt = $opt"
34 | }
35 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/parameter/valueFromPipeline/show-piped-objects.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 3
2 |
3 | function show-piped-objects {
4 |
5 | param (
6 | [parameter (valueFromPipeline=$true )] [string] $parameterFromPipeline,
7 | [string] $ordinaryParameter
8 | )
9 |
10 |
11 | process {
12 | write-host "ordinaryParameter: $ordinaryParameter, parameterFromPipeline = $parameterFromPipeline"
13 | }
14 |
15 | }
16 |
17 | 'foo', 'bar', 'baz' | show-piped-objects -ordinaryParameter XXX
18 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/parameter/valueFromPipelineByPropertyName/simple.ps1:
--------------------------------------------------------------------------------
1 | function F {
2 |
3 | param (
4 | [parameter(valueFromPipelineByPropertyName)] $foo,
5 | [parameter(valueFromPipelineByPropertyName)] $bar,
6 | [parameter(valueFromPipelineByPropertyName)] $baz
7 | )
8 |
9 | process {
10 | write-host
11 |
12 | if ($foo) { write-host "foo = $foo" }
13 | if ($bar) { write-host "bar = $bar" }
14 | if ($baz) { write-host "baz = $baz" }
15 | }
16 | }
17 |
18 |
19 | class clsX {
20 | [int] $bar = 42
21 | }
22 |
23 |
24 | class clsY {
25 | [string] $baz = 'hello world'
26 | }
27 |
28 |
29 | class clsZ {
30 | [int ] $bar = 99
31 | [string] $foo = 'ninety-nine'
32 | }
33 |
34 |
35 | $objX = new-object clsX
36 | $objY = new-object clsY
37 | $objZ = new-object clsZ
38 |
39 |
40 | $objX, $objY, $objZ | F
41 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/parameter/valueFromRemainingArguments/show-remaining-arguments.ps1:
--------------------------------------------------------------------------------
1 | function show-remaining-arguments {
2 |
3 | param (
4 |
5 | [parameter(
6 | mandatory = $false
7 | )]
8 | [string] $arg_1,
9 |
10 | [parameter(
11 | mandatory = $false,
12 | valueFromRemainingArguments = $true
13 | )]
14 | [string[]] $args
15 | )
16 |
17 | write-host "First Argument: $arg_1"
18 |
19 | $r = 0
20 | foreach($arg in $args) {
21 | $r ++;
22 | write-host "Remaining Argument $r`: $arg"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/validate/Script/ensure-directory.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [parameter ( mandatory=$true )] # make sure parameter exists
3 | [validateScript( { test-path -pathType container $_ } )] # make sure path exists
4 | [string ] $path # finally: the parameter
5 | )
6 |
7 | ls $path
8 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/attributes/validate/Set/intro.ps1:
--------------------------------------------------------------------------------
1 | function do-something {
2 |
3 | param (
4 | [validateSet('foo', 'bar', 'baz')] [string] $doWhat
5 | )
6 |
7 | switch ($doWhat) {
8 |
9 | 'foo' { write-host 'Foo!' }
10 | 'bar' { write-host 'Bar!' }
11 | 'baz' { write-host 'Baz!' }
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/named.ps1:
--------------------------------------------------------------------------------
1 | function add($s1, $s2) {
2 | $sum = $s1 + $s2
3 | return $sum
4 | }
5 |
6 | write-host The sum is (add 19 23)
7 | # The sum is 42
8 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/param.ps1:
--------------------------------------------------------------------------------
1 | function add {
2 |
3 | #
4 | # Parameters can also be specified more explicitely
5 | # within the param() statement:
6 | #
7 |
8 | param (
9 | [int] $param_1,
10 | [int] $param_2
11 | )
12 |
13 | $param_1 + $param_2
14 | }
15 |
16 | $sum = add 19 23
17 | write-output "sum is $sum"
18 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/script.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [parameter(mandatory=$true)] [alias('tx')] [string] $text,
3 | [int ] $optional,
4 | [switch] $flag
5 | )
6 |
7 | write-host "text = $text"
8 | write-host "optional = $optional"
9 | write-host "flag = $flag"
10 | write-host ""
11 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/shift.ps1:
--------------------------------------------------------------------------------
1 | function lispy {
2 | $op, $elems = $args
3 |
4 | invoke-expression ($elems -join $op)
5 | }
6 |
7 | lispy '+' 10 3 2
8 | lispy '*' 10 3 2
9 | lispy '-' 10 3 2
10 | lispy '/' 10 3 2
11 |
--------------------------------------------------------------------------------
/language/statement/function/parameters/typed.ps1:
--------------------------------------------------------------------------------
1 | function add ([int]$param_1, [int]$param_2) {
2 | $param_1 + $param_2
3 | }
4 |
5 | $sum = add 19 23
6 | write-output "sum is $sum"
7 | #
8 | # sum is 42
9 |
10 |
11 | # $sum = add "foo" "bar"
12 | #
13 | # Because add takes typed parameter, trying to
14 | # invoke add with strings resultes in the following
15 | # error:
16 | # Cannot process argument transformation on parameter 'param_1'.
17 | # Cannot convert value "foo" to type "System.Int32".
18 | # Error: "Input string was not in a correct format.
19 | #
20 |
21 |
--------------------------------------------------------------------------------
/language/statement/function/show-definition.ps1:
--------------------------------------------------------------------------------
1 | # define a function ...
2 |
3 | function foo {
4 | echo 'foo'
5 | ls
6 | }
7 |
8 | # ... and show its definition:
9 |
10 | $function:foo
11 |
--------------------------------------------------------------------------------
/language/statement/switch/assignment.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 3
2 |
3 | $num = 2
4 |
5 | $txt = switch ($num) {
6 | 1 { 'one' }
7 | 2 { 'two' }
8 | 3 { 'three' }
9 | }
10 |
11 | write-host "txt = $txt"
12 |
--------------------------------------------------------------------------------
/language/statement/switch/break.ps1:
--------------------------------------------------------------------------------
1 | $num = 42
2 |
3 | switch ($num) {
4 |
5 | { $_ -le 9 } { "$_ has one digit" ; break }
6 | { $_ -le 99 } { "$_ has two digits" ; break }
7 | { $_ -le 999 } { "$_ has three digits" ; break }
8 | default { "$_ has more than three digits" }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/language/statement/switch/eval.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 2
2 |
3 | function category ($thing) {
4 |
5 | switch ($thing) {
6 |
7 | { $_ -in 'apple', 'pear', 'orange' } {
8 | write-host "$_ is a fruit"
9 | }
10 | { $_ -in 'foo', 'bar', 'baz' } {
11 | write-host "$_ is a metasyntactic variable"
12 | }
13 | { $_.GetType().Name -eq 'Int32' } {
14 | write-host "$_ is an int32"
15 | }
16 | default {
17 | write-host "I don't know what $_ is"
18 | }
19 |
20 | }
21 | }
22 |
23 | category baz
24 | # baz is a metasyntactic variable
25 |
26 | category 42
27 | #
28 | # 42 is an int32
29 |
30 | category orange
31 | #
32 | # orange is a fruit
33 |
34 | category ?
35 | #
36 | # I don't know what ? is
37 |
--------------------------------------------------------------------------------
/language/statement/switch/num-to-text.ps1:
--------------------------------------------------------------------------------
1 | $num = 4
2 |
3 | switch ($num) {
4 |
5 | 1 { 'one' }
6 | 2 { 'two' }
7 | 3 { 'three' }
8 | 4 { 'four' }
9 | 5 { 'five' }
10 | default { '?' }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/language/statement/try-catch-finally/catch-type.ps1:
--------------------------------------------------------------------------------
1 | class ExOne : System.Exception {}
2 | class ExTwo {}
3 |
4 | function throwException($num) {
5 |
6 | if ($num -eq 1) {
7 | throw [ExOne]::new()
8 |
9 | }
10 | if ($num -eq 2) {
11 | throw [ExTwo]::new()
12 | }
13 | }
14 |
15 | function tryToCatch($num) {
16 | try {
17 | throwException $num
18 | write-host 'no exception'
19 | }
20 | catch [ExOne] {
21 | write-host "Caught: ExOne"
22 | }
23 | catch [ExTwo] {
24 | write-host "Caught: ExTwo"
25 | }
26 | catch {
27 | write-host "Caught neither ExOne nor ExTwo: `$_ = $_"
28 | }
29 |
30 | }
31 |
32 | tryToCatch 1
33 | #
34 | # Caught: ExOne
35 |
36 | tryToCatch 2
37 | #
38 | # Caught neither ExOne nor ExTwo: $_ = ExTwo
39 |
40 | tryToCatch 3
41 | #
42 | # no exception
43 |
--------------------------------------------------------------------------------
/language/statement/try-catch-finally/simple.ps1:
--------------------------------------------------------------------------------
1 | function divide-by($num) {
2 |
3 | try {
4 |
5 | write-output "42 / $num = $(42/$num)"
6 |
7 | }
8 | catch {
9 |
10 | write-output "Exception $_"
11 |
12 | }
13 | finally {
14 |
15 | write-output "The finally block is always executed";
16 |
17 | }
18 |
19 | }
20 |
21 | divide-by 7
22 | divide-by 6
23 | divide-by 0
24 | divide-by 3
25 |
--------------------------------------------------------------------------------
/language/statement/using/namespace/simple.ps1:
--------------------------------------------------------------------------------
1 | using namespace System.Windows.Forms
2 |
3 | [MessageBox]::Show('Simple example for "using namespace"')
4 |
--------------------------------------------------------------------------------
/language/statement/while/assignment-gt.ps1:
--------------------------------------------------------------------------------
1 | $nums = 42, 99, 17, 0, 12
2 |
3 | $index = -1
4 | function nextNum() {
5 | $script:index ++
6 | return $script:nums[$script:index]
7 | }
8 |
9 | while ( ($num = nextNum) -gt 22) {
10 | write-host "num = $num"
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/language/statement/while/assignment.ps1:
--------------------------------------------------------------------------------
1 | $nums = 42, 99, 17, 0, 12
2 |
3 | $index = -1
4 | function nextNum() {
5 | $script:index ++
6 | return $script:nums[$script:index]
7 | }
8 |
9 | while ($num = nextNum) {
10 | write-host "num = $num"
11 | }
12 |
--------------------------------------------------------------------------------
/language/statement/while/condition.ps1:
--------------------------------------------------------------------------------
1 | $num = 1
2 |
3 | while ($num -lt 6) {
4 | write-host "$num * $num = $($num*$num)"
5 | $num++
6 | }
7 | #
8 | # 1 * 1 = 1
9 | # 2 * 2 = 4
10 | # 3 * 3 = 9
11 | # 4 * 4 = 16
12 | # 5 * 5 = 25
13 |
--------------------------------------------------------------------------------
/language/type/array/OFS.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Create an array:
3 | #
4 | $ary = 'foo', 'bar', 'baz'
5 |
6 | #
7 | # Initially, the variable OFS has not been assigned a value:
8 | #
9 | $OFS -eq $null
10 | #
11 | # True
12 |
13 | #
14 | # Printing the array in a string
15 | #
16 | write-output "$ary"
17 | #
18 | # foo bar baz
19 |
20 | #
21 | # Assign an empty string to OFS and
22 | # print the array again:
23 | #
24 | $OFS = ''
25 | write-output "$ary"
26 | #
27 | # foobarbaz
28 |
29 | #
30 | # Assign a string to OFS and
31 | # print the array again:
32 | #
33 | $OFS = ' -+- '
34 | write-output "$ary"
35 | #
36 | # foo -+- bar -+- baz
37 |
--------------------------------------------------------------------------------
/language/type/array/as-argument/.gitignore:
--------------------------------------------------------------------------------
1 | ShowArgs.exe
2 |
--------------------------------------------------------------------------------
/language/type/array/as-argument/ShowArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | public class ShowArgs {
3 |
4 | static void Main(String[] argv) {
5 | Console.WriteLine($"ShowArgs.exe: argument count is {argv.Length}:");
6 | foreach (var arg in argv) {
7 | Console.WriteLine(" " + arg);
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/language/type/array/as-argument/ShowArgs.ps1:
--------------------------------------------------------------------------------
1 | write-host "ShowArgs.ps1: argument count is $($args.length)"
2 | $args | foreach-object { " $_ ($($_.GetType().FullName))" }
3 |
--------------------------------------------------------------------------------
/language/type/array/as-argument/compile.ps1:
--------------------------------------------------------------------------------
1 | csc ShowArgs.cs
2 |
--------------------------------------------------------------------------------
/language/type/array/assign.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Define an array with five elements…
3 | #
4 | $numbers = 'one', 'two', 'three', 'four', 'five'
5 |
6 | #
7 | # … and assign it to an array with three elements:
8 | #
9 | $eins, $zwei, $rest = $numbers
10 |
11 | #
12 | # $rest will have remaining elements of $numbers:
13 | #
14 | "eins = $eins"
15 | "zwei = $zwei"
16 | "rest = $rest"
17 |
--------------------------------------------------------------------------------
/language/type/array/byte/return-in-function/naive.ps1:
--------------------------------------------------------------------------------
1 | function make-byteArray() {
2 |
3 | [outputType( [byte[]] )]
4 |
5 | [byte[]] $byteArray = new-object byte[] 2
6 |
7 | $byteArray[0] = 0
8 | $byteArray[1] = 1
9 |
10 | write-host "type of byteArray: $($byteArray.GetType().FullName)"
11 |
12 | return $byteArray
13 | }
14 |
15 | $x = make-byteArray
16 | write-host "type of x: $($x.GetType().FullName)"
17 |
--------------------------------------------------------------------------------
/language/type/array/byte/return-in-function/unary-comma.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # https://stackoverflow.com/a/61440166/180275
3 | #
4 | function make-byteArray() {
5 |
6 | [outputType( [byte[]] )]
7 |
8 | [byte[]] $byteArray = new-object byte[] 2
9 |
10 | $byteArray[0] = 0
11 | $byteArray[1] = 1
12 |
13 | ,$byteArray
14 | }
15 |
16 | $x = make-byteArray
17 | write-host "type of x: $($x.GetType().FullName)"
18 |
--------------------------------------------------------------------------------
/language/type/array/byte/return-in-function/write-output.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # https://stackoverflow.com/a/61440506/180275
3 | #
4 | function make-byteArray() {
5 |
6 | [outputType( [byte[]] )]
7 |
8 | [byte[]] $byteArray = new-object byte[] 2
9 |
10 | $byteArray[0] = 0
11 | $byteArray[1] = 1
12 |
13 | write-output -noEnumerate $byteArray
14 | }
15 |
16 | $x = make-byteArray
17 | write-host "type of x: $($x.GetType().FullName)"
18 |
--------------------------------------------------------------------------------
/language/type/array/filter.ps1:
--------------------------------------------------------------------------------
1 | $elems = 'one', 'two', 'three', 'four', 'five', 'six'
2 | $elems -gt 'ghijk' -join ', '
3 | #
4 | # one, two, three, six
5 |
--------------------------------------------------------------------------------
/language/type/array/intro.ps1:
--------------------------------------------------------------------------------
1 | $ary = 'foo', 'bar', 'baz'
2 |
3 | write-output "First element is: $($ary[0])"
4 | write-output "Second element is: $($ary[1])"
5 | write-output "Last element is: $($ary[-1])"
6 | write-output "The array has $($ary.count) elements"
7 | #
8 | # First element is: foo
9 | # Second element is: bar
10 | # Last element is: baz
11 | # The array has 3 elements
12 |
13 | # Iterating over the array using the foreach-object cmdlet …
14 | $ary | foreach-object { $_.ToUpper() }
15 |
16 | # … or the foreach statement:
17 | foreach ($elem in $ary) {
18 | $elem.ToUpper()
19 | }
20 |
--------------------------------------------------------------------------------
/language/type/array/iterate-over-name-value-pairs.ps1:
--------------------------------------------------------------------------------
1 | $name_value_pairs = 'text', 'hello World', 'number', 42, 'fruit', 'apple'
2 |
3 | while ($name_value_pairs) {
4 | $name, $value, $name_value_pairs = $name_value_pairs
5 | write-host('{0,-7}: {1}' -f $name, $value)
6 | }
7 |
--------------------------------------------------------------------------------
/language/type/array/numerically-sort-array.ps1:
--------------------------------------------------------------------------------
1 | $ary = '9', '10', '1', '888'
2 | $ary | sort-object
3 | #
4 | # 1
5 | # 10
6 | # 888
7 | # 9
8 |
9 | $ary | sort-object { [int] $_ }
10 | #
11 | # 1
12 | # 9
13 | # 10
14 | # 888
15 |
--------------------------------------------------------------------------------
/language/type/array/plus-vs-comma.ps1:
--------------------------------------------------------------------------------
1 | $abc = 'a', 'b', 'c'
2 | $abc.length
3 | #
4 | # 3
5 |
6 | # ----- Create an array with the comma operator
7 | #
8 | # $abc is turned into one element so that
9 | # the resulting array consists of 4 elements:
10 |
11 | $ary = $abc, 'd', 'e', 'f'
12 | $ary.length
13 | #
14 | # 4
15 |
16 | $ary | foreach-object { "$_" }
17 | #
18 | # a b c
19 | # d
20 | # e
21 | # f
22 |
23 | # ----- Create an array with the plus operator
24 | #
25 | # The elements in $abc are exploded/expanded
26 | # so that the resulting array consists
27 | # of 6 elements:
28 |
29 | $ary = $abc + 'd', 'e', 'f'
30 | $ary.length
31 | #
32 | # 6
33 |
34 | $ary | foreach-object { "$_" }
35 | #
36 | # a
37 | # b
38 | # c
39 | # d
40 | # e
41 | # f
42 |
--------------------------------------------------------------------------------
/language/type/array/print.ps1:
--------------------------------------------------------------------------------
1 | $days = 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
2 | write-output $days
3 | #
4 | # Sun
5 | # Mon
6 | # Tue
7 | # Wed
8 | # Thu
9 | # Fri
10 | # Sat
11 |
12 | write-output($days -join ' ')
13 | #
14 | # Sun Mon Tue Wed Thu Fri Sat
15 |
--------------------------------------------------------------------------------
/language/type/array/unrolling.ps1:
--------------------------------------------------------------------------------
1 | $ary = [psCustomObject] @{ propA = 'one' ; propB = 'foo' },
2 | [psCustomObject] @{ propA = 'two' ; propB = 'bar' },
3 | [psCustomObject] @{ propA = 'three'; propB = 'baz' }
4 |
5 | echo ($ary.propA -join ' - ')
6 | #
7 | # one - two - three
8 |
9 | echo ($ary.propB -join ' - ')
10 | #
11 | # foo - bar - baz
12 |
--------------------------------------------------------------------------------
/language/type/array/weakly-and-strongly-typed.ps1:
--------------------------------------------------------------------------------
1 | $weakly___typed = 'ONE', 'TWO', 'THREE'
2 | [string[]] $strongly_typed = 'one', 'two', 'three'
3 |
4 | write-output "An weakly typed array is $($weakly___typed.GetType().FullName) and derives from $($weakly___typed.GetType().BaseType.FullName)"
5 | write-output "An strongly typed array is $($strongly_typed.GetType().FullName) and derives from $($strongly_typed.GetType().BaseType.FullName)"
6 | #
7 | # An weakly typed array is System.Object[] and derives from System.Array
8 | # An strongly typed array is System.String[] and derives from System.Array
9 |
--------------------------------------------------------------------------------
/language/type/hash-table/add-remove.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Create hash table with two elements;
3 | #
4 | $htA = @{
5 | a_1 = 'val one';
6 | a_x = 'val X'
7 | }
8 |
9 | #
10 | # Add another element
11 | #
12 | $htA['a_2'] = 'val two'
13 |
14 | #
15 | # Remove an element
16 | #
17 | $htA.remove('a_x')
18 |
19 | write-output $htA
20 | #
21 | # Name Value
22 | # ---- -----
23 | # a_1 val one
24 | # a_2 val two
25 |
26 | #
27 | # Create another hashtable
28 | #
29 | $htB = @{
30 | b_1 = 'VAL ONE';
31 | b_2 = 'VAL TWO'
32 | }
33 |
34 | #
35 | # The + and += operators allow to merge
36 | # two hash tables (IF they don't share a key name):
37 | #
38 | $htA += $htB
39 |
40 | write-output $htA
41 | #
42 | # b_2 VAL TWO
43 | # a_1 val one
44 | # b_1 VAL ONE
45 | # a_2 val two
46 |
--------------------------------------------------------------------------------
/language/type/hash-table/override-members.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Create a hash table
3 | #
4 | $ht = @{}
5 |
6 | #
7 | # Add a couple of key/value pairs:
8 | #
9 | $ht['one'] = 1
10 | $ht['two'] = 2
11 |
12 | #
13 | # Use the 'Keys' property to print the
14 | # hash table's
15 | #
16 | $ht.Keys
17 | #
18 | # one
19 | # two
20 |
21 | #
22 | # Add another key/value pair.
23 | #
24 | $ht['Keys'] = 42
25 |
26 | #
27 | # Adding this key overwrode the
28 | # 'Keys' property:
29 | #
30 | $ht.Keys
31 | #
32 | # 42
33 |
34 | #
35 | # Use psBase.Keys to get the «real»
36 | # Keys property:
37 | #
38 | $ht.psBase.Keys
39 | #
40 | # one
41 | # Keys
42 | # two
43 |
44 |
45 | #
46 | # Can 'psBase' be overridden, too?
47 | #
48 | $ht['psBase'] = $null
49 |
50 | #
51 | # No, it does not:
52 | #
53 | $ht.psBase.Keys
54 | #
55 | # psBase
56 | # one
57 | # Keys
58 | # two
59 |
--------------------------------------------------------------------------------
/language/type/hash-table/sort.ps1:
--------------------------------------------------------------------------------
1 | $ht = @{
2 | 'seven' = 7;
3 | 'eleven' = 11;
4 | 'five' = 5;
5 | 'forty-two' = 42;
6 | 'zero' = 0;
7 | 'eighty-two' = 82;
8 | }
9 |
10 | $ht.GetEnumerator() | sort-object -property name # -property key seems also possible
11 | #
12 | # Name Value
13 | # ---- -----
14 | # eighty-two 82
15 | # eleven 11
16 | # five 5
17 | # forty-two 42
18 | # seven 7
19 | # zero 0
20 |
21 | $ht.GetEnumerator() | sort-object -property value
22 | #
23 | # zero 0
24 | # five 5
25 | # seven 7
26 | # eleven 11
27 | # forty-two 42
28 | # eighty-two 82
29 |
--------------------------------------------------------------------------------
/language/variable/automatic/args/parameters.ps1:
--------------------------------------------------------------------------------
1 | function fOne {
2 | write-host "`$args.length = $($args.length)"
3 | }
4 |
5 | function fTwo($p1, $p2) {
6 | write-host "`$args.length = $($args.length)"
7 | }
8 |
9 | fOne
10 | #
11 | # $args.length = 0
12 |
13 | fOne foo
14 | #
15 | # $args.length = 1
16 |
17 | fOne bar baz
18 | #
19 | # $args.length = 2
20 |
21 | fTwo 42 'hello world'
22 | #
23 | # $args.length = 0
24 |
25 | fTwo A B excess parameters
26 | #
27 | # $args.length = 2
28 |
--------------------------------------------------------------------------------
/language/variable/automatic/matches/simple.ps1:
--------------------------------------------------------------------------------
1 | 'Foo 42 bar 99 baz' -match '\d+' | out-null
2 | write-host "The matched number is $($matches[0])."
3 | #
4 | # The matched number is 42.
5 |
6 | 'Check 999 too' -notmatch '\d+' | out-null
7 | write-host "The matched number is $($matches[0])."
8 | #
9 | # The matched number is 999.
10 |
--------------------------------------------------------------------------------
/language/variable/automatic/myInvocation/script.ps1:
--------------------------------------------------------------------------------
1 |
2 | function func-2 {
3 |
4 | # write-host "`$myInvocation.GetType().FullName = $($myinvocation.GetType().FullName)"
5 | write-host "`$myInvocation.myCommand.GetType().FullName = $($myinvocation.myCommand.GetType().FullName)"
6 | write-host "`$myInvocation.myCommand.name = $($myinvocation.myCommand.name)"
7 | # write-host "`$myInvocation.myCommand.path = $($myinvocation.myCommand.path)"
8 | write-host "`$myInvocation.scriptName = $($myinvocation.scriptName)"
9 | write-host "`$myInvocation.psScriptRoot = $($myinvocation.psScriptRoot)"
10 | write-host "`$myInvocation.psCommandPath = $($myinvocation.psCommandPath)"
11 | write-host "`$myInvocation.commandOrigin = $($myinvocation.commandOrigin)"
12 |
13 | }
14 |
15 | function func-1 {
16 |
17 | # write-host "`$myInvocation.GetType().FullName = $($myinvocation.GetType().FullName)"
18 | write-host "`$myInvocation.myCommand.GetType().FullName = $($myinvocation.myCommand.GetType().FullName)"
19 | write-host "`$myInvocation.myCommand.name = $($myinvocation.myCommand.name)"
20 | # write-host "`$myInvocation.myCommand.path = $($myinvocation.myCommand.path)"
21 | write-host "`$myInvocation.scriptName = $($myinvocation.scriptName)"
22 | write-host "`$myInvocation.psScriptRoot = $($myinvocation.psScriptRoot)"
23 | write-host "`$myInvocation.psCommandPath = $($myinvocation.psCommandPath)"
24 | write-host "`$myInvocation.commandOrigin = $($myinvocation.commandOrigin)"
25 |
26 | write-host
27 |
28 | func-2
29 |
30 | }
31 |
32 | # write-host "`$myInvocation.GetType().FullName = $($myinvocation.GetType().FullName)"
33 | write-host "`$myInvocation.myCommand.GetType().FullName = $($myinvocation.myCommand.GetType().FullName)"
34 | write-host "`$myInvocation.myCommand.name = $($myinvocation.myCommand.name)"
35 | write-host "`$myInvocation.myCommand.path = $($myinvocation.myCommand.path)"
36 | write-host "`$myInvocation.scriptName = $($myinvocation.scriptName)"
37 | write-host "`$myInvocation.psScriptRoot = $($myinvocation.psScriptRoot)"
38 | write-host "`$myInvocation.psCommandPath = $($myinvocation.psCommandPath)"
39 | write-host "`$myInvocation.commandOrigin = $($myinvocation.commandOrigin)"
40 |
41 | write-host
42 |
43 | func-1
44 |
--------------------------------------------------------------------------------
/language/variable/automatic/psBoundParameters/ContainsKey.ps1:
--------------------------------------------------------------------------------
1 | function F {
2 | param (
3 | [int ] $num,
4 | [string] $txt,
5 | [switch] $yes
6 | )
7 |
8 |
9 | if ($psBoundParameters.ContainsKey('num')) {
10 | "parameter num was passed and is $num"
11 | }
12 | if ($psBoundParameters.ContainsKey('txt')) {
13 | "parameter txt was passed and is $txt"
14 | }
15 | if ($psBoundParameters.ContainsKey('yes')) {
16 | "parameter yes was passed and is $yes"
17 | }
18 |
19 | }
20 |
21 |
22 | F -txt 'hello world'
23 | #
24 | # parameter txt was passed and is hello world
25 |
26 |
27 | F -num 42 -yes:$false
28 | #
29 | # parameter num was passed and is 42
30 | # parameter yes was passed and is False
31 |
--------------------------------------------------------------------------------
/language/variable/automatic/psBoundParameters/simple.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version 2
2 |
3 | function F (
4 | $param_1 = 'one' ,
5 | $param_2 = 'two' ,
6 | $param_3 = 'three',
7 | $param_4 = 'four' ,
8 | $param_5 = 'five'
9 | ) {
10 |
11 | write-host "You called F"
12 | write-host " The following arguments were set when F was invoked"
13 | foreach ($passedArgument in $psBoundParameters.Keys) {
14 | write-host " $passedArgument = $($psBoundParameters[$passedArgument])"
15 | }
16 |
17 | write-host " Of these arguments, the following were passed positionally"
18 | foreach ($passedPositionally in $psBoundParameters.BoundPositionally) {
19 | write-host " $passedPositionally"
20 | }
21 |
22 | write-host
23 |
24 | }
25 |
26 |
27 | F 'foo' 'bar' 'baz'
28 | #
29 | # You called F
30 | # The following arguments were set when F was invoked
31 | # param_1 = foo
32 | # param_2 = bar
33 | # param_3 = baz
34 | # Of these arguments, the following were passed positionally
35 | # param_1
36 | # param_2
37 | # param_3
38 | #
39 |
40 |
41 | F 'one' 'TWO' 'xyz'
42 | #
43 | # You called F
44 | # The following arguments were set when F was invoked
45 | # param_1 = one
46 | # param_2 = TWO
47 | # param_3 = xyz
48 | # Of these arguments, the following were passed positionally
49 | # param_1
50 | # param_2
51 | # param_3
52 |
53 | F -param_3 'one' -param_4 'two' -param_1 'three'
54 | #
55 | # You called F
56 | # The following arguments were set when F was invoked
57 | # param_3 = one
58 | # param_4 = two
59 | # param_1 = three
60 | # Of these arguments, the following were passed positionally
61 |
--------------------------------------------------------------------------------
/language/variable/automatic/psCmdLet/cmdletBinding.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Defining a few functions
3 | #
4 | function func_1 {
5 | param($param)
6 | write-output "psCmdlet = $psCmdlet, param = $param"
7 | }
8 |
9 | #
10 | # Define another function with the only difference
11 | # that is has the cmdletBinding attribute:
12 | #
13 | function func_2 {
14 | [cmdletBinding()]
15 | param($param)
16 | write-output "psCmdlet = $psCmdlet, param = $param"
17 | }
18 |
19 | #
20 | # This function does not have a a [cmdletBinding()] instruction.
21 | # However, the param() statement encloses a [parameter(...)] thingy
22 | # which also causes $psCmdlet to be defined:
23 | #
24 | function func_3 {
25 | param([parameter()] [string] $param)
26 | write-output "psCmdlet = $psCmdlet, param = $param"
27 | }
28 |
29 |
30 | #
31 | # Invoking the functions
32 | #
33 |
34 | func_1 one
35 | #
36 | # psCmdlet = , param = one
37 |
38 | func_2 two
39 | #
40 | # psCmdlet = System.Management.Automation.PSScriptCmdlet, param = two
41 |
42 | func_3 three
43 | #
44 | # psCmdlet = System.Management.Automation.PSScriptCmdlet, param = three
45 |
--------------------------------------------------------------------------------
/language/variable/automatic/psCmdLet/getType.ps1:
--------------------------------------------------------------------------------
1 | function typeof-psCmdlet {
2 | [cmdletBinding()] param()
3 |
4 | echo "type of `$psCmdlet is $($psCmdlet.GetType().FullName)"
5 | }
6 |
7 | typeof-psCmdlet
8 | #
9 | # type of $psCmdlet is System.Management.Automation.PSScriptCmdlet
--------------------------------------------------------------------------------
/language/variable/automatic/psItem/equivalency.ps1:
--------------------------------------------------------------------------------
1 | 'foo', 'bar', 'baz' | forEach-object { write-host $_ }
2 | 'foo', 'bar', 'baz' | forEach-object { write-host $psItem }
3 |
--------------------------------------------------------------------------------
/language/variable/create-global-var-in-func.ps1:
--------------------------------------------------------------------------------
1 | function create-global-var() {
2 |
3 | $global:num = 42
4 | $global:txt ='Hello world'
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/language/variable/preference/errorActionPreference/intro.ps1:
--------------------------------------------------------------------------------
1 |
2 | function open-registryKey($name) {
3 | $regKey = get-item $name
4 | write-host "Opened $($regKey.Name)"
5 | }
6 |
7 |
8 | try {
9 |
10 | open-registryKey hklm:\SOFTWARE
11 | open-registryKey hklm:\SAM\SAM
12 | open-registryKey hklm:\SYSTEM
13 |
14 | }
15 | catch {
16 |
17 | write-host "Caught error $_"
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/language/variable/preference/errorActionPreference/param-errorAction.ps1:
--------------------------------------------------------------------------------
1 | function eap {
2 | [cmdletbinding()]
3 | Param()
4 |
5 | write-host "errorActionPreference: $errorActionPreference"
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/language/variable/preference/formatEnumerationLimit/4.ps1:
--------------------------------------------------------------------------------
1 | $formatEnumerationLimit = 4 # Default
2 | $objects | select-object txt, elems
3 | #
4 | # txt elems
5 | # --- -----
6 | # three {A, B, C}
7 | # four {D, E, F, G}
8 | # five {H, I, J, K...}
9 | # six {M, N, O, P...}
10 | # seven {S, T, U, V...}
11 |
--------------------------------------------------------------------------------
/language/variable/preference/formatEnumerationLimit/6.ps1:
--------------------------------------------------------------------------------
1 | $formatEnumerationLimit = 6
2 | $objects | select-object txt, elems
3 | #
4 | # txt elems
5 | # --- -----
6 | # three {A, B, C}
7 | # four {D, E, F, G}
8 | # five {H, I, J, K, L}
9 | # six {M, N, O, P, Q, R}
10 | # seven {S, T, U, V, W, X...}
11 |
--------------------------------------------------------------------------------
/language/variable/preference/formatEnumerationLimit/objects.ps1:
--------------------------------------------------------------------------------
1 | $objects =
2 | [psCustomObject] @{
3 | txt = 'three'
4 | elems = 'A', 'B', 'C'
5 | },
6 | [psCustomObject] @{
7 | txt = 'four'
8 | elems = 'D', 'E', 'F', 'G'
9 | },
10 | [psCustomObject] @{
11 | txt = 'five'
12 | elems = 'H', 'I', 'J', 'K', 'L'
13 | },
14 | [psCustomObject] @{
15 | txt = 'six'
16 | elems = 'M', 'N', 'O', 'P', 'Q', 'R'
17 | },
18 | [psCustomObject] @{
19 | txt = 'seven'
20 | elems = 'S', 'T', 'U', 'V', 'W', 'X', 'Y'
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/language/variable/preference/ofs.ps1:
--------------------------------------------------------------------------------
1 | $ary = 'foo', 'bar', 'baz', 'etc'
2 |
3 | $OFS = ';'
4 |
5 | write-host "$ary" # Note the quotes!
6 | #
7 | # foo;bar;baz;etc
8 | #
9 |
--------------------------------------------------------------------------------
/language/variable/typed-untyped.ps1:
--------------------------------------------------------------------------------
1 | [int] $anInteger = 42
2 | $aVariable = 99
3 |
4 | $anInteger.GetType().FullName # System.Int32
5 | $aVariable.GetType().FullName # System.Int32
6 |
7 | $anInteger = "17"
8 | $aVariable = "32"
9 |
10 | $anInteger.GetType().FullName # System.Int32
11 | $aVariable.GetType().FullName # System.String
12 |
--------------------------------------------------------------------------------
/powershell.exe/command/execute-script.bat:
--------------------------------------------------------------------------------
1 | @powershell -command "" ^
2 | ^
3 | $i = 1; ^
4 | ^
5 | while ($i -le 10) { ^
6 | write-output $i; ^
7 | $i++; ^
8 | } ^
9 | ^
10 | ""
11 |
--------------------------------------------------------------------------------
/script/abort-on-unrecognized-term.ps1:
--------------------------------------------------------------------------------
1 | $errorActionPreference = 'stop'
2 | set-strictMode -version latest
3 |
4 | $v = 5
5 |
6 | foreach ($i in 0 .. 10) {
7 |
8 | if ( $v -gt $i ) {
9 | write-host 'v > i'
10 | }
11 | elsif ($i -lt 7) {
12 | write-host 'i < 7'
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/script/name-and-path.ps1:
--------------------------------------------------------------------------------
1 | set-strictMode -version latest
2 |
3 | write-host
4 | write-host " The name of script's file is : $($myInvocation.myCommand.name)"
5 | write-host " It is located in the directory : $psScriptRoot"
6 | write-host
7 | write-host " Thus, the complete path to the script is: $psCommandPath"
8 | write-host
9 | write-host " The directory can also be evaluated with"
10 | write-host " `$myInvocation.myCommand.path : $($myInvocation.myCommand.path)"
11 | write-host
12 |
--------------------------------------------------------------------------------