0
votes

I have an Azure Devops deployment pipeline setup which is building and I am able to deploy to a self hosted virtual machine with no issue.

I have the following powershell script that correctly clears down my destination directory leaving 2 folders that are not part of source control

Get-ChildItem -Path  'C:\inetpub\wwwroot\testDeploy\' -Recurse -exclude "pod","photos" |
Select -ExpandProperty FullName |
Where {$_ -notlike  '*\pod\*' -and $_ -notlike '*\photos\*'} |
sort length -Descending |
Remove-Item -force 

I have tried adding a "PowerShell Script" task but i'm don;t know how to get the PowerShell script in to a folder that the task can access i.e. $(System.DefaultWorkingDirectory). Can anyone advise how I should be either generating the file or where to store it in my repo that is then accessible by the self-hosted Windows agent

1
Do you want to access the pre-defined variables in your PowerShell script?Shayki Abramczyk
No, the script can run in isolation. I should have added that I have the process working by adding the script inline but I wanted to understand how it could be maintained within the repo insteadPixelstiltskin
You can create a folder "PowerShell scripts" and put the script there.Shayki Abramczyk
Could you store your script in repos and accessed by self agent now?Merlin Liang - MSFT
@ShaykiAbramczyk - I have tried adding a script in to the root of my repo but it throws the following error when I put the path in as "ClearDirectories.ps1": ##[error]Invalid file path 'C:\azagent\A1_work\r1\a\ClearDirectories.ps1'. A path to a .ps1 file is required.Pixelstiltskin

1 Answers

1
votes

Agree with Shayki, you can create a powershell(.ps1) file in repos and paste your script in it to achieve that. And then, use powershell task to execute the script which in ps1 file.

But, as you said that you want it be maintained within the repos easily. Need made some change on your script:

Param(
    [string]$RootPath,
    [string]$File1,
    [string]$File2,
    [string]$NonLike1,
    [string]$NonLike2
)

Get-ChildItem -Path  $RootPath -Recurse -include $File1,$File2 |
Select -ExpandProperty FullName |
Where {$_ -notlike  $NonLike1 -and $_ -notlike $NonLike2} |
sort length -Descending |
Remove-Item -Recurse -force

The first change is, you need to replace the hard code with variable. Pass the value with task, this is a good way to maintain your script.

The second which also the important change is add -Recurse after Remove-Item, or you will get the error showed below while the value of $RootPath is hard code, such as 'C:\Users\'.

Remove-Item : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.

And then, you can add task in your build pipeline. Add the Script path where the .ps1 file located and input the Arguments with the value:

enter image description here

If you want to access $(System.DefaultWorkingDirectory), pass it to $RootPath.

Hope my sample can help you achieve what you want.