Skip to content

PowerShell module creates and runs scripts from the input pipeline.

License

Notifications You must be signed in to change notification settings

rhubarb-geek-nz/ScriptBlock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

61a78b5 · Mar 16, 2025

History

5 Commits
Jun 1, 2024
Mar 16, 2025
Jul 12, 2024
Jun 1, 2024
Jun 1, 2024
Jun 1, 2024

Repository files navigation

ScriptBlock

This PowerShell module creates and runs scripts from the input pipeline.

Command summary

New-ScriptBlock [-InputString] <string>

Invoke-ScriptBlock -InputString <string> [-ArgumentList <Object[]>] [-NoNewScope]

Invoke-ScriptBlock -ScriptBlock <scriptblock> [-ArgumentList <Object[]>] [-NoNewScope]

The instantiation cmdlet uses ScriptBlock.Create to create the script.

The invocation cmdlet uses Invoke-Command to run the script.

Example

Pipe a script and invoke with given arguments.

@'
param($Message)
Write-Output -InputObject $Message
'@ | Invoke-ScriptBlock -ArgumentList 'Hello World'

Build

Build in the ScriptBlock subdirectory with

$ dotnet publish --configuration Release

Install by copying the module into a directory on the PSModulePath

Example simulating POSIX shell behaviour for piped scripts

This uses rhubarb-geek-nz.Console to provide POSIX like stdin, stdout and stderr access.

  • Script is read from stdin using Read-Console
  • It is invoked by Invoke-ScriptBlock.
  • Arguments are passed via $MyInvocation
  • Output is written through Write-Console to split to stdout and stderr.
  • try/catch is used to set LastExitCode on Write-Error
#!/usr/bin/env pwsh

$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop

& {
	try
	{
		Read-Console | Invoke-ScriptBlock -ArgumentList $global:MyInvocation.UnboundArguments

		Set-Variable -Name LastExitCode -Scope Global -Value 0
	}
	catch
	{
		Set-Variable -Name LastExitCode -Scope Global -Value 1

		$PSItem
	}
} *>&1 | Write-Console

Exit $LastExitCode

About

PowerShell module creates and runs scripts from the input pipeline.

Resources

License

Stars

Watchers

Forks

Packages

No packages published