Git Product home page Git Product logo

pwsh-script's Introduction

pwsh-script

GitHub Action to run PowerShell scripts that use the workflow run context - inspired by actions/github-script.

GitHub top language CI GitHub release (latest by date) GitHub commits since latest release (by date)

In order to use this action, script input is required. The value of that input should be the body of a PowerShell script. The following variables are initialized before your script is executed:

Demo

You can try out this action yourself by commenting on a demo issue. Instructions in the issue.

Reading step results

The return value of the script will be made available in the step's outputs under the result key.

- uses: Amadevus/pwsh-script@v2
  id: my-script
  with:
    script: '1 + 1'
- run: echo "${{ steps.my-script.outputs.result }}"
  # should print 2

Result encoding

If the script return value is a single string, it'll be set as the value of the result output directly. In any other case, it'll be passed to ConvertTo-Json $Value -Depth 100 -Compress -EscapeHandling EscapeNonAscii and the string result of that call will be set as the output value.

- uses: Amadevus/pwsh-script@v2
  id: bad-script
  with:
    script: return [ordered]@{ x = 'a1'; y = 'b2' }
  continue-on-error: true
- run: echo '${{ steps.bad-script.outputs.result }}'
  # should print {"x":"a1","y":"b2"}

Error handling

If the script throws an error/exception, it'll be caught, printed to the log and the error message will be set as an error output of the action.

- uses: Amadevus/pwsh-script@v2
  id: bad-script
  with:
    script: 'throw "this fails"'
  continue-on-error: true
- run: echo "${{ steps.bad-script.outputs.error }}"
  # should print 'this fails'

Actions cmdlets

A module called GitHubActionsCore will be imported in the scope of your script. It provides commands that are available for JavaScript Actions by @actions/core package, such as:

  • Add-ActionPath
  • Write-ActionWarning
  • Set-ActionFailed

For module documentation, see GitHubActionsCore README.

The module has a good test suite written in Pester.

Notes

  • This action requires pwsh to actually be available and on PATH of the runner - which is the case for all GitHub-provided runner VMs; for your own runners you need to take care of that yourself.
  • This action is a composite action.
  • This action has an extensive self-testing suite in CI workflow.
  • Although available in the imported module, Get-ActionInput and Set-ActionOutput won't really work when used as part of this action.

Examples

- uses: Amadevus/pwsh-script@v2
  id: script
  with:
    script: |
      Write-ActionDebug "Visible only when ACTIONS_STEP_DEBUG secret is set"

      # access full context objects:
      if ($github.event.repository.full_name -ne $github.repository) {
        # throwing causes the step to fail
        throw "something fishy's going on, repos don't match"
      }

      $someData = Get-MyCustomData
      # data may contain workflow command strings (e.g. '::warning::...')
      # prevent runner interpreting these
      Invoke-ActionNoCommandsBlock -GenerateToken {
        # this won't result in any workflow commands
        Write-Host $someData
        Write-ActionError "not interpreted as error"
      }
      # commands work again

      # set env:BE_AWESOME=always here and for the following steps
      Set-ActionVariable BE_AWESOME always

      # add our custom tool to PATH for the following steps:
      $toolPath = Resolve-Path ./tools/bin
      Add-ActionPath $toolPath

      # warn if it's too late for people to work in Greenwich ;)
      if ([datetime]::UtcNow.Hour -ge 22) {
        Write-ActionWarning "It's time to go to bed. Don't write code late at night! ⚠"
      }

Changelog

Changelog is kept in CHANGELOG.md

License

This action is licensed under MIT license.

pwsh-script's People

Contributors

amis92 avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

pwsh-script's Issues

Az Module request

Any plan of including the Az Module by default in a future release?

Action not finishing

Hi! First of all thanks for sharing this action!
I'm calling a powershell script like this:

- name: Deploy to Umbraco Cloud
  uses: Amadevus/[email protected]
  env:
    GIT_ADDRESS: ${{ secrets.GIT_ADDRESS }}
    GIT_USERNAME: ${{ secrets.GIT_USERNAME }}
    GIT_PASSWORD: ${{ secrets.GIT_PASSWORD }}
  with:
    script: . ".\$env:DEPLOY_SCRIPT" -cloneurl "$env:GIT_ADDRESS" -uaasuser "$env:GIT_USERNAME" -password "$env:GIT_PASSWORD" -sourcepath "$env:PUBLISH_DIR" -destinationpath "$env:CLONE_DIR"

The script is running fine, these are the final lines in the script:

Write-Host "Deployment finished"

Write-Verbose "Leaving script DeployToUmbracoCloud.ps1"

I can see the Deployment finished echo in the logs, but the action isn't finishing, it keeps running forever.
How can I make sure the process finished?

Error: ConvertTo-Json : An item with the same key has already been added. Key: Version

Please, help me with pwsh-script action:

https://github.com/test-st-petersburg/DocTemplates/runs/2487220589?check_suite_focus=true#step:4:70

Code:

<#
.SYNOPSIS
Sanitizes an input into a string so it can be passed into issueCommand safely.
Equivalent of `core.toCommandValue(input)`.
.PARAMETER Value
Input to sanitize into a string.
#>
function ConvertTo-ActionCommandValue {
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory, Position = 0)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[object]$Value
)
if ($null -eq $Value) {
return ''
}
if ($Value -is [string]) {
return $Value
}
return ConvertTo-Json $Value -Depth 100 -Compress -EscapeHandling EscapeNonAscii
}

Demo

There's a slash-command available to try out the action. Simply comment on this issue with /demo in the first line and a PowerShell script in the following lines. If your comment will contain a code-block (fenced or not), contents of it will be executed instead of whole comment body - and it'll look better! :)

For example, comment with:

/demo

```powershell
return (1 + 1)
```

You should get a result (and/or an error) in a comment that will follow.

ℹ Please note, for security $github.token is not available in the demo script. It's available all right in normal action executions. :)

Suggestion to improve $*Preference defaults

One thing I found myself always prepending to all my GitHub action PowerShell script is setting $ProgressPreference and $InformationPreference.

  • $ProgressPreference to 'Silent', because on the GitHub action log PowerShell cannot draw an interactive progress bar and it otherwise causes mangled output
  • $InformationPreference to 'SilentlyContinue' (instead of default 'Silent') because in GitHub actions you usually want to be able to log text with Write-Information (and the pipeline output is used as the action output). And can be a bit of a debugging pitfall to realize that Write-Information is swallowed).

What do you think about adding these two lines to the action itself so they don't have to be added manually? I think it would improve the developer experience and not be harmful (and worse case it can be overridden by the user)

Happy to do a PR.

Error: Invoke-Expression : Cannot bind argument to parameter 'Path' because it is null.

Hi!
When I run action and when the Run Amadevus/pwsh-script@v2 executes - there is an Error

Error: Invoke-Expression : Cannot bind argument to parameter 'Path' because it is null.
At /home/runner/work/_actions/Amadevus/pwsh-script/v2/action.ps1:21 char:23
$Private:result = Invoke-Expression $Private:scriptFile
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
FullyQualifiedErrorId : >ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

Error: Process completed with exit code 1.

Here is the Action yaml:
`
name: Convert Contact List
on:
workflow_dispatch:
schedule:
- cron: "* */3 * * *"

jobs:
build:
name: Run Script
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

  - uses: Amadevus/pwsh-script@v2
    id: script
    env:
      GH_TOKEN: ${{ github.token }}
    with:
      script: |
        # ------ AnyTone ------ #
        $DMRIdsContent = Get-Content ./DMRIds.dat

  - name: Update files in repository
    uses: actions-x/commit@v6
    with:
      email: "[email protected]"
      name: GitHub Actions Autocommitter
      branch: master
      files: Devices_Contact_List/*
      repository: https://github.com/${{ github.repository }}
      token: ${{ github.token }}
      force: true

`

Set-ActionOutput not setting any output

Hi,

The Set-ActionOutput cmdlet seems to not be working for me at all. I have this workflow, and when it gets to the next step the output isn't even there.

name: Test

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: windows-latest

    steps:
      - uses: actions/checkout@v2

      - name: Set output
        id: test
        uses: Amadevus/pwsh-script@v2
        with:
          script: |
            Set-ActionOutput testout igottest

      - name: Run a multi-line script
        run: |
          echo "${{ steps.test.outputs.testout }}"

Thanks for the github action by the way, it's really cool to be able to have all these integrations from within powershell 😄

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.