Home > Net >  How to create and save files using PowerShell in GitHub action?
How to create and save files using PowerShell in GitHub action?

Time:02-02

I'm new to GitHub actions, I want to use PowerShell and save the output of a command to a file in my repository, but I don't know what's the right way to do it.

name: get hash
on: [workflow_dispatch]

jobs:
    build:
      name: Run Script
      runs-on: windows-latest
      steps:
        - uses: actions/checkout@v3
        - name: Script
          run: ./script.ps1
          shell: pwsh

and using get-filehash command I'm trying to learn creating a simple Github workflow that saves the hash of a file to a text file in my repository.

this is the script.ps1 file content

$wc = [System.Net.WebClient]::new()
$pkgurl = 'File on the web'
$FileHashSHA512 = Get-FileHash -Algorithm SHA512 -InputStream ($wc.OpenRead($pkgurl))    
$FileHashSHA512.Hash > .\sss.txt

I know it's not practical but I want to learn basics of workflows. the command works on my computer but I just don't get how Github workflows work when it comes to saving files on my repository.

I also want to make this command work in the same workflow:

Invoke-WebRequest -Uri $pkgurl -OutFile .\file.zip

but again don't know how to make the workflow save the file in the repository's root.

since these are very basic, I'm trying to create/write the workflow files myself and not use other people's pre-made actions.

CodePudding user response:

The actions runner is just a PC that clones the repo and runs a few commands in it. So when you create a new file on the runner, you have to add it to the repo on the runner, create a commit and push that to the repo over on GitHub.

It might help to understand that the repo in GitHub and the runner in GitHub actions are two completely seperate things. It's not like the actions runner somehow runs 'inside' your repo.

So one way to save filer is to run:

git add fileyoujustcreated.txt
git commit -m "updating file"
git push

Here is a sample GitHub action I use to update a file in my repo each time the content changes:

https://github.com/jessehouwing/jessehouwing/blob/3ff5f5567734197a945022d3544ab0ea8c32bef4/.github/actions/update-scrum-classes/action.yml

Alternatively, you can edit files in GitHub using the REST API, so you could invoke:

curl \
  -X PUT \
  -H "Accept: application/vnd.github json" \
  -H "Authorization: Bearer <YOUR-TOKEN>"\
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/contents/PATH \
  -d '{"message":"my commit message","committer":{"name":"Monalisa Octocat","email":"[email protected]"},"content":"bXkgbmV3IGZpbGUgY29udGVudHM="}'

Or the equivalent in PowerRhell.

You can use the ${{ GitHub.token }} variable to authenticate.

See:

  • Related