首页 > 解决方案 > Azure Devops - 自托管代理上的 PowerShell 任务

问题描述

我有一个正在构建的 Azure Devops 部署管道设置,我能够毫无问题地部署到自托管虚拟机。

我有以下 powershell 脚本可以正确清除我的目标目录,留下 2 个不属于源代码控制的文件夹

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 

我尝试添加“PowerShell 脚本”任务,但我不知道如何将 PowerShell 脚本放入任务可以访问的文件夹中,即 $(System.DefaultWorkingDirectory)。谁能建议我应该如何生成文件或将其存储在我的存储库中,然后自托管 Windows 代理可以访问

标签: azure-devopsazure-pipelinesazure-pipelines-release-pipelineazure-devops-self-hosted-agent

解决方案


同意 Shayki,您可以在 repos 中创建一个 powershell( .ps1 ) 文件并将您的脚本粘贴到其中来实现。然后,使用 powershell 任务执行 ps1 文件中的脚本。

但是,正如您所说,您希望它可以轻松地在存储库中维护。需要对您的脚本进行一些更改:

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

第一个变化是,您需要用变量替换硬代码。通过任务传递值,这是维护脚本的好方法。

第二个也是重要的更改是在-Recurse后面添加Remove-Item,否则你会得到下面显示的错误,而 $RootPath 的值是硬代码,例如 'C:\Users\'。

Remove-Item :Windows PowerShell 处于非交互模式。阅读和提示功能不可用。

然后,您可以在构建管道中添加任务。添加.ps1Script path文件所在的位置并输入带有值的参数:

在此处输入图像描述

如果要访问$(System.DefaultWorkingDirectory),请将其传递给$RootPath.

希望我的样本可以帮助您实现您想要的。


推荐阅读