0. 修改执行策略
Jenkins执行PowerShell脚本,需要修改其执行策略。以管理员身份运行PowerShell,执行以下脚本:
Set-ExecutionPolicy Unrestricted
1. Test-Path
确定文件或文件夹是否存在,如:
$testDir="D:\NewDir"
if((Test-Path $testDir) -ne $true)
{
md $testDir
}
2. Copy-Item/Remove-Item
拷贝/删除文件或文件夹,如:
$testDir="D:\NewDir"
if(Test-Path $testDir)
{
Remove-Item $testDir -Recurse -Force
}
3. Cmd
调用Cmd.exe,如通过Cmd调用7z进行压缩/解压缩:
$projectDir="D:\NewDir";
$compressedName="NewDir.7z"; cd $projectDir $cmdargs = "7z a "+$compressedName+" -w .\*"
cmd /c $cmdargs
4. Net use
访问共享文件夹,如:
$username="Victor";
$password="******"; $serverDrive = "\\ServerA\D$"; net use $serverDrive $password /user:$username Copy-Item $serverDrive\test.txt -Destination D:\NewDir net use $serverDrive /delete /y
5. Invoke-Command
在本地或远程主机执行命令,如:
$username="Victor";
$password="******"; $pass = ConvertTo-SecureString -AsPlainText $password -Force
$credential= New-Object System.Management.Automation.PSCredential -ArgumentList $username,$pass $serverName="ServerA"
Invoke-Command -ComputerName $serverName -Credential $credential -FilePath "D:\CI\Script\test.ps1"
其中“test.ps1”的内容为:
$copyDir="D:\"+(Get-Date -format yyyy.MM.dd)+".txt"; Copy-Item D:\test.txt -Destination $copyDir
注意:运行此命令需要添加信任主机
Step 1:在主机B上Run as Administrator打开PowerShell Step 1.1:启用远程:Enable-PSRemoting -Force Step 1.2:添加信任主机:下面a为允许所有主机,b为添加单个主机或主机列表 a:Set-Item wsman:\localhost\client\trustedhosts * b:Set-item wsman:localhost\client\trustedhosts –value 主机名 Step 1.3:重启WinRM服务:Restart-Service WinRM Step 2:在主机A上打开PowerShell Step 2.1:测试连接:Test-WsMan B Step 2.2:如果连接成功即可使用”Invoke-Command“命令执行相应脚本 |
6. System.Net.WebClient.DownloadString
使用该方法可以间接实现通过Jenkins访问url,示例:
$url="http://blog.ityes.net" (New-Object System.Net.WebClient).DownloadString($url);
7. System.Xml.XmlDocument.Load
读取XML文件,如:
[String]$xmlDocDir = "D:\CI\Config\Credential.xml";
$xmlDoc = New-Object "System.Xml.XmlDocument";
$xmlDoc.Load($xmlDocDir); $username=$xmlDoc.Root.Credential.GetAttribute("Username");
$password=$xmlDoc.Root.Credential.GetAttribute("Password");
其中“Credential.xml”的内容为:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Credential Username="Victor" Password="******"></Credential>
</Root>
8. Sqlcmd
使用 ODBC 执行 Transact-SQL 批处理,如:
$server="DbServer";
$databaseName="DbName";
$username="Victor";
$password="******"; $sqlScriptDir="D:\CI\Script\tes.sql"; Sqlcmd -S $server -d $databaseName -U $username -P $password -i $sqlScriptDir