Jenkins.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 |
$moduleRoot = Split-Path ` -Path $MyInvocation.MyCommand.Path ` -Parent #region LocalizedData $Culture = 'en-us' if (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath $PSUICulture)) { $Culture = $PSUICulture } Import-LocalizedData ` -BindingVariable LocalizedData ` -Filename Jenkins_LocalizationData.psd1 ` -BaseDirectory $moduleRoot ` -UICulture $Culture #endregion <# .SYNOPSIS Throws a custom exception. .DESCRIPTION This cmdlet throws a terminating or non-terminating exception. .PARAMETER errorId The Id of the exception. .PARAMETER errorCategory The category of the exception. It must be a valid [System.Management.Automation.ErrorCategory] value. .PARAMETER errorMessage The exception message. .PARAMETER terminate This switch will cause the exception to terminate the cmdlet. .EXAMPLE $ExceptionParameters = @{ errorId = 'ConnectionFailure' errorCategory = 'ConnectionError' errorMessage = 'Could not connect' } New-Exception @ExceptionParameters Throw a ConnectionError exception with the message 'Could not connect'. .OUTPUTS None #> function New-Exception { [CmdLetBinding()] param ( [Parameter(Mandatory)] [String] $errorId, [Parameter(Mandatory)] [System.Management.Automation.ErrorCategory] $errorCategory, [Parameter(Mandatory)] [String] $errorMessage, [Switch] $terminate ) $exception = New-Object -TypeName System.Exception ` -ArgumentList $errorMessage $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $exception, $errorId, $errorCategory, $null if ($true -or $()) { if ($Terminate) { # This is a terminating exception. throw $errorRecord } else { # Note: Although this method is called ThrowTerminatingError, it doesn't terminate. $PSCmdlet.ThrowTerminatingError($errorRecord) } } # if } # function New-Exception <# .SYNOPSIS Enables PowerShell to support TLS1.2 for communicating with newer versions of Jenkins. .DESCRIPTION This support cmdlet enables connecting to newer versions of Jenkins over HTTPS. Newer versions of Jenkins have deprecated support for SSL3/TLS, which are the default supported HTTPS protocols. .OUTPUTS None #> function Set-JenkinsTLSSupport { [CmdLetBinding()] param ( ) if (-not ([Net.ServicePointManager]::SecurityProtocol).ToString().Contains([Net.SecurityProtocolType]::Tls12)) { [Net.ServicePointManager]::SecurityProtocol = ` [Net.ServicePointManager]::SecurityProtocol + [Net.SecurityProtocolType]::Tls12 } } # function Set-JenkinsTLSSupport <# .SYNOPSIS Assembles the tree request component for a Jenkins request. .DESCRIPTION This cmdlet will assemble the ?tree= component of a Jenkins Rest API call to limit the return of specific types and levels of information. .PARAMETER Depth The maximum number of levels of the tree to return. .PARAMETER Type The category of elements to return. Can be: jobs, views. .PARAMETER Attribute An array of attributes to return for each level of the tree. The attributes available will depend on the type specified. .EXAMPLE $request = Get-JenkinsTreeRequest -Depth 4 -Type 'Jobs' -Attribute 'Name' Invoke-JenkinsCommand -Uri 'https://jenkins.contoso.com/' -Command $request This will return all Jobs within 4 levels of the tree. Only the name attribute will be returned. .OUTPUTS String containing tree request. #> function Get-JenkinsTreeRequest() { [CmdLetBinding()] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$false)] [Int] $Depth = 1, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Type = 'jobs', [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $Attribute = @( 'name','buildable','url','color' ) ) $AllAttributes = $Attribute -join ',' $TreeRequest = "?tree=$Type[$AllAttributes" for ($level = 1; $level -lt $Depth; $level++) { $TreeRequest += ",$Type[$AllAttributes" } # foreach $TreeRequest += ']' * $Depth return $TreeRequest } # Get-JenkinsTreeRequest <# .SYNOPSIS Gets a Jenkins Crumb. .DESCRIPTION This cmdlet is used to obtain a crumb that must be passed to all other commands to a Jenkins Server if CSRF is enabled in Global Settings of the server. The crumb must be added to the header of any commands or requests sent to this master. .PARAMETER Uri Contains the Uri to the Jenkins Master server to obtain the crumb from. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .EXAMPLE Get-JenkinsCrumb ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) Returns a Jenkins Crumb. .OUTPUTS The crumb string. #> function Get-JenkinsCrumb() { [CmdLetBinding()] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential ) if ($PSBoundParameters.ContainsKey('Credential')) { # Jenkins Credentials were passed so create the Authorization Header $Username = $Credential.Username # Decrypt the secure string password $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password) $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $Bytes = [System.Text.Encoding]::UTF8.GetBytes($Username + ':' + $Password) $Base64Bytes = [System.Convert]::ToBase64String($Bytes) $Headers += @{ "Authorization" = "Basic $Base64Bytes" } } # if $null = $PSBoundParameters.remove('Uri') $null = $PSBoundParameters.remove('Credential') $FullUri = '{0}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' -f $Uri try { Write-Verbose -Message $($LocalizedData.GetCrumbMessage -f $FullUri) Set-JenkinsTLSSupport $Result = Invoke-WebRequest ` -Uri $FullUri ` -Headers $Headers ` -ErrorAction Stop } catch { # Todo: Improve error handling. Throw $_ } # catch $Regex = '^Jenkins-Crumb:([A-Z0-9]*)' $Matches = @([regex]::matches($Result.Content, $Regex, 'IgnoreCase')) if (-not $Matches.Groups) { # Attempt to match the alternate Jenkins Crumb format $Regex = '^.crumb:([A-Z0-9]*)' $Matches = @([regex]::matches($Result.Content, $Regex, 'IgnoreCase')) if (-not $Matches.Groups) { $ExceptionParameters = @{ errorId = 'CrumbResponseFormatError' errorCategory = 'InvalidArgument' errorMessage = $($LocalizedData.CrumbResponseFormatError -f ` $Result.Content) } New-Exception @ExceptionParameters } # if } # if $Crumb = $Matches.Groups[1].Value Return $Crumb } # Get-JenkinsCrumb <# .SYNOPSIS Execute a Jenkins command or request via the Jenkins Rest API. .DESCRIPTION This cmdlet is used to issue a command or request to a Jenkins Master via the Rest API. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Type The type of endpoint to invoke the command on. Can be set to: Rest,Command. .PARAMETER Api The API to use. Only used if type is 'rest'. Can be XML, JSON or Python. Defaults to JSON. .PARAMETER Command This is the command and any other URI parameters that need to be passed to the API. Should always be set if the Type is set to Command. .PARAMETER Method The method of the web request to use. Defaults to default for the type of command. .PARAMETER Headers Allows additional header values to be specified. .EXAMPLE Invoke-JenkinsCommand ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Crumb $Crumb ` -Api 'json' ` -Command 'job/MuleTest/build' Triggers the MuleTest job on https://jenkins.contoso.com to run using the credentials provided by the user. .EXAMPLE Invoke-JenkinsCommand ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Api 'json' Returns the list of jobs in the root of the https://jenkins.contoso.com using credentials provided by the user. .EXAMPLE Invoke-JenkinsCommand ` -Uri 'https://jenkins.contoso.com' Returns the list of jobs in the root of the https://jenkins.contoso.com using no credentials for authorization. .EXAMPLE Invoke-JenkinsCommand ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Type 'Command' ` -Command 'job/Build My App/config.xml' Returns the job config XML for the 'Build My App' job in https://jenkins.contoso.com using credentials provided by the user. .OUTPUTS The result of the Api as a string. #> function Invoke-JenkinsCommand() { [CmdLetBinding()] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateSet('rest','command','restcommand','pluginmanager')] [String] $Type = 'rest', [parameter( Position=5, Mandatory=$false)] [String] $Api = 'json', [parameter( Position=6, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Command, [parameter( Position=7, Mandatory=$false)] [ValidateSet('default','delete','get','head','merge','options','patch','post','put','trace')] [String] $Method, [parameter( Position=8, Mandatory=$false)] [System.Collections.Hashtable] $Headers = @{}, [parameter( Position=9, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $ContentType, [parameter( Position=10, Mandatory=$false)] [ValidateNotNullOrEmpty()] $Body ) if ($PSBoundParameters.ContainsKey('Credential') -and $Credential -ne [System.Management.Automation.PSCredential]::Empty) { # Jenkins Credentials were passed so create the Authorization Header $Username = $Credential.Username # Decrypt the secure string password $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password) $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $Bytes = [System.Text.Encoding]::UTF8.GetBytes($Username + ':' + $Password) $Base64Bytes = [System.Convert]::ToBase64String($Bytes) $Headers += @{ "Authorization" = "Basic $Base64Bytes" } } # if if ($PSBoundParameters.ContainsKey('Crumb')) { Write-Verbose -Message $($LocalizedData.UsingCrumbMessage -f $Crumb) # Support both Jenkins and Cloudbees Jenkins Enterprise $Headers += @{ "Jenkins-Crumb" = $Crumb } $Headers += @{ ".crumb" = $Crumb } } # if $null = $PSBoundParameters.remove('Uri') $null = $PSBoundParameters.remove('Credential') $null = $PSBoundParameters.remove('Crumb') $null = $PSBoundParameters.remove('Type') $null = $PSBoundParameters.remove('Headers') switch ($Type) { 'rest' { $FullUri = "$Uri/api/$Api" if ($PSBoundParameters.ContainsKey('Command')) { $FullUri = $FullUri + '/' + $Command } # if $null = $PSBoundParameters.remove('Command') $null = $PSBoundParameters.remove('Api') try { Write-Verbose -Message $($LocalizedData.InvokingRestApiCommandMessage -f $FullUri) Set-JenkinsTLSSupport $Result = Invoke-RestMethod ` -Uri $FullUri ` -Headers $Headers ` @PSBoundParameters ` -ErrorAction Stop } catch { # Todo: Improve error handling. Throw $_ } # catch } # 'rest' 'restcommand' { $FullUri = "$Uri/$Command" $null = $PSBoundParameters.remove('Command') $null = $PSBoundParameters.remove('Api') try { Write-Verbose -Message $($LocalizedData.InvokingRestApiCommandMessage -f $FullUri) Set-JenkinsTLSSupport $Result = Invoke-RestMethod ` -Uri $FullUri ` -Headers $Headers ` @PSBoundParameters ` -ErrorAction Stop } catch { # Todo: Improve error handling. Throw $_ } # catch } # 'restcommand' 'command' { $FullUri = $Uri if ($PSBoundParameters.ContainsKey('Command')) { $FullUri = $FullUri + '/' + $Command } # if $null = $PSBoundParameters.remove('Command') $null = $PSBoundParameters.remove('Api') Write-Verbose -Message $($LocalizedData.InvokingCommandMessage -f $FullUri) Set-JenkinsTLSSupport $Result = Invoke-WebRequest ` -Uri $FullUri ` -Headers $Headers ` -MaximumRedirection 0 ` @PSBoundParameters ` -ErrorAction SilentlyContinue ` -ErrorVariable RequestErrors if ($RequestErrors.Count -eq 1 -and $Result.StatusCode -eq 302 ` -and $RequestErrors[0].FullyQualifiedErrorId -like "MaximumRedirectExceeded,*") { Write-Verbose -Message $($LocalizedData.SuppressingRedirectMessage -f $Result.Headers.Location) } elseif ($RequestErrors.Count -ge 1) { # Todo: Improve error handling. throw $RequestErrors[0].Exception } } # 'command' 'pluginmanager' { $FullUri = $Uri if ($PSBoundParameters.ContainsKey('Command')) { $FullUri = "$FullUri/pluginManager/api/$api/?$Command" } # if (condition) { $null = $PSBoundParameters.remove('Command') $null = $PSBoundParameters.remove('Api') try { Write-Verbose -Message $($LocalizedData.InvokingCommandMessage -f $FullUri) Set-JenkinsTLSSupport $Result = Invoke-WebRequest ` -Uri $FullUri ` -Headers $Headers ` @PSBoundParameters ` -ErrorAction Stop } catch { # Todo: Improve error handling. Throw $_ } # catch } # 'pluginmanager' } # switch Return $Result } # Invoke-JenkinsCommand <# .SYNOPSIS Get a list of installed plugins in a Jenkins master server. .DESCRIPTION Returns the list of installed plugins from a jenkins server, the list containing the name and version of each plugin. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Api The API to use. Can be XML, JSON or Python. Defaults to JSON. .PARAMETER Depth The depth of the tree to return (must be at least 1). Defaults to 1. .EXAMPLE $Plugins = Get-JenkinsPluginsList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Verbose Returns the list of installed plugins on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS An array of Jenkins objects. #> function Get-JenkinsPluginsList() { [CmdLetBinding()] [OutputType([Object[]])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [String] $Api = 'json', [parameter( Position=5, Mandatory=$false)] [String] $Depth = '1' ) # Add/Remove PSBoundParameters so they can be splatted $null = $PSBoundParameters.Add('Type','pluginmanager') $null = $PSBoundParameters.Add('Command',"depth=$Depth") $null = $PSBoundParameters.Remove('Depth') # Invoke the Command to Get the Plugin List $Result = Invoke-JenkinsCommand @PSBoundParameters $Objects = ConvertFrom-Json -InputObject $Result.Content # Returns the list of plugins, selecting just the name and version. Return ($Objects.plugins | Select-Object shortName,version) } # Get-JenkinsPluginsList <# .SYNOPSIS Triggers a reload on a jenkins server .DESCRIPTION Triggers a reload on a jenkins server, e.g. if the job configs are altered on disk. .PARAMETER Uri The uri of the Jenkins server to trigger the reload on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .EXAMPLE Invoke-JenkinsJobReload ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Verbose Triggers a reload of the jenkins server 'https://jenkins.contoso.com' #> function Invoke-JenkinsJobReload { [CmdLetBinding()] param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb ) # Invoke-JenkinsCommand with the 'reload' rest command Invoke-JenkinsCommand ` -Uri $uri ` -Credential $Credential ` -Crumb $Crumb ` -Type 'restcommand' ` -Command 'reload' ` -Method 'post' ` -Verbose } # function Invoke-JenkinsJobReload <# .SYNOPSIS Get a list of objects in a Jenkins master server. .DESCRIPTION Returns a list of objects within a specific level of the Jenkins tree. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Type The type of object to return. Defaults to jobs. .PARAMETER Attribute The list of attribute to return. .PARAMETER Folder The optional job folder to retrieve the jobs from. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER IncludeClass This allows the class of objects that are returned to be limited to only these types. .PARAMETER ExcludeClass This allows the class of objects that are returned to exclude these types. .EXAMPLE $Jobs = Get-JenkinsObject ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Type 'jobs' ` -Attribute 'name','buildable','url','color' ` -Verbose Returns the list of jobs on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Jobs = Get-JenkinsObject ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Type 'jobs' ` -Attribute 'name','buildable','url','color' ` -Verbose Returns the list of jobs in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS An array of Jenkins objects. #> function Get-JenkinsObject() { [CmdLetBinding()] [OutputType([Object[]])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Type, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String[]] $Attribute, [parameter( Position=6, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=7, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $IncludeClass, [parameter( Position=8, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $ExcludeClass ) $null = $PSBoundParameters.Remove('Type') $null = $PSBoundParameters.Remove('Attribute') $null = $PSBoundParameters.Remove('IncludeClass') $null = $PSBoundParameters.Remove('ExcludeClass') $null = $PSBoundParameters.Remove('Folder') # To support the Folders plugin we have to create a tree # request that is limited to the depth of the folder we're looking for. $TreeRequestSplat = @{ Type = $Type Attribute = $Attribute } if ($Folder) { $FolderItems = $Folder -split '\\' $TreeRequestSplat = @{ Depth = ($FolderItems.Count + 1) Attribute = $Attribute } } # if $Command = Get-JenkinsTreeRequest @TreeRequestSplat $PSBoundParameters.Add('Command',$Command) $Result = Invoke-JenkinsCommand @PSBoundParameters $Objects = $Result.$Type if ($Folder) { # A folder was specified, so find it foreach ($FolderItem in $FolderItems) { foreach ($Object in $Objects) { if ($FolderItem -eq $Object.Name) { $Objects = $Object.$Type } # if } # foreach } # foreach } # if if ($IncludeClass) { $Objects = $Objects | Where-Object -Property _class -In $IncludeClass } # if if ($ExcludeClass) { $Objects = $Objects | Where-Object -Property _class -NotIn $ExcludeClass } # if Return $Objects } # Get-JenkinsObject <# .SYNOPSIS Get a list of jobs in a Jenkins master server. .DESCRIPTION Returns the list of jobs registered on a Jenkins Master server in either the root folder or a specified subfolder. The list of jobs returned can be filtered by setting the IncludeClass or ExcludeClass parameters. By default any folders will be filtered from this list. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder to retrieve the jobs from. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER IncludeClass This allows the class of objects that are returned to be limited to only these types. .PARAMETER ExcludeClass This allows the class of objects that are returned to exclude these types. .EXAMPLE $Jobs = Get-JenkinsJobList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Verbose Returns the list of jobs on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Jobs = Get-JenkinsJobList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Verbose Returns the list of jobs in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Folders = Get-JenkinsJobList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -IncludeClass 'hudson.model.FreeStyleProject' ` -Verbose Returns the list of freestyle Jenknins jobs in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Folders = Get-JenkinsJobList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc\Builds' ` -Verbose Returns the list of jobs in the 'Builds' folder within the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS An array of Jenkins Job objects. #> function Get-JenkinsJobList() { [CmdLetBinding()] [OutputType([Object[]])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $IncludeClass, [parameter( Position=6, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $ExcludeClass ) $null = $PSBoundParameters.Add( 'Type', 'jobs') $null = $PSBoundParameters.Add( 'Attribute', @( 'name','buildable','url','color' ) ) # If a class was not explicitly excluded or included then excluded then # set the function to excluded folders. if (-not $PSBoundParameters.ContainsKey('ExcludeClass') ` -and -not $PSBoundParameters.ContainsKey('IncludeClass')) { $PSBoundParameters.Add('ExcludeClass',@('com.cloudbees.hudson.plugins.folder.Folder')) } # if return Get-JenkinsObject ` @PSBoundParameters } # Get-JenkinsJobList <# .SYNOPSIS Get a Jenkins Job Definition. .DESCRIPTION Gets the config.xml of a Jenkins job if it exists on the Jenkins Master server. If the job does not exist an error will occur. If a folder is specified it will find the job in the specified folder. .PARAMETER Uri Contains the Uri to the Jenkins Master server to get the Job definition from. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder to look for the job in. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER Name The name of the job definition to get. .EXAMPLE Get-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -Verbose Returns the XML config of the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Get-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -Verbose Returns the XML config of the 'My App Build' job in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Get-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc/Build' ` -Name 'My App Build' ` -Verbose Returns the XML config of the 'My App Build' job in the 'Build' folder in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS A string containing the Jenkins Job config XML. #> function Get-JenkinsJob() { [CmdLetBinding()] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name ) $null = $PSBoundParameters.Add('Type','Command') if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' $Command = 'job/' foreach ($Folder in $Folders) { $Command += "$Folder/job/" } # foreach $Command += "$Name/config.xml" } else { $Command = "job/$Name/config.xml" } # if $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Add('Command',$Command) return (Invoke-JenkinsCommand @PSBoundParameters).Content } # Get-JenkinsJob <# .SYNOPSIS Set a Jenkins Job definition. .DESCRIPTION Sets a Jenkins Job config.xml on a Jenkins Master server. If a folder is specified it will update the job in the specified folder. If the job does not exist an error will occur. If the job already exists the definition will be overwritten. .PARAMETER Uri Contains the Uri to the Jenkins Master server to set the Job definition on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder the job is in. This requires the Jobs Plugin to be installed on Jenkins. If the folder does not exist then an error will occur. .PARAMETER Name The name of the job to set the definition on. .PARAMETER XML The config XML of the job to import. .EXAMPLE Set-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -XML $MyAppBuildConfig ` -Verbose Sets the job definition of the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Set-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -XML $MyAppBuildConfig ` -Verbose Sets the job definition of the 'My App Build' job in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS None. #> function Set-JenkinsJob() { [CmdLetBinding(SupportsShouldProcess=$true)] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [parameter( Position=6, Mandatory=$true, ValueFromPipeline=$True)] [ValidateNotNullOrEmpty()] [String] $XML ) $null = $PSBoundParameters.Add('Type','Command') if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' $Command = 'job/' foreach ($Folder in $Folders) { $Command += "$Folder/job/" } # foreach $Command += "$Name/config.xml" } else { $Command = "job/$Name/config.xml" } # if $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Remove('XML') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Add('Command',$Command) $null = $PSBoundParameters.Add('Method','post') $null = $PSBoundParameters.Add('ContentType','application/xml') $null = $PSBoundParameters.Add('Body',$XML) if ($PSCmdlet.ShouldProcess(` $URI,` $($LocalizedData.SetJobDefinitionMessage -f $Name))) { $null = Invoke-JenkinsCommand @PSBoundParameters } # if } # Set-JenkinsJob <# .SYNOPSIS Determines if a Jenkins Job exists. .DESCRIPTION Returns true if a Job exists in the specified Jenkins Master server with a matching Name. It will search inside a specific folder if one is passed. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder to look for the job in. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER Name The name of the job to check for. .EXAMPLE Test-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -Verbose Returns true if the 'My App Build' job is found on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Test-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -Verbose Returns true if the 'My App Build' job is found in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS A boolean indicating if the job was found or not. #> function Test-JenkinsJob() { [CmdLetBinding()] [OutputType([Boolean])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Name ) $null = $PSBoundParameters.Add( 'Type', 'jobs') $null = $PSBoundParameters.Add( 'Attribute', @( 'name' ) ) $null = $PSBoundParameters.Remove( 'Name' ) return ((@(Get-JenkinsObject @PSBoundParameters | Where-Object -Property Name -eq $Name)).Count -gt 0) } # Test-JenkinsJob <# .SYNOPSIS Renames an existing Jenkins Job. .DESCRIPTION Renames an existing Jenkins Job in the specified Jenkins Master server. If the job does not exist or a job with the new name exists already an error will occur. .PARAMETER Uri Contains the Uri to the Jenkins Master server that contains the existing job. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Name The name of the job to rename. .PARAMETER NewName The new name to rename the job to. .EXAMPLE Rename-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -NewName 'My Renamed Build' ` -Verbose Rename the 'My App Build' job on https://jenkins.contoso.com to 'My Renamed Build' using the credentials provided by the user. .OUTPUTS None. #> function Rename-JenkinsJob() { [CmdLetBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $NewName, [Switch] $Force ) $null = $PSBoundParameters.Add('Type','Command') $Command = "job/$Name/doRename?newName={0}" -f [System.Uri]::EscapeDataString($NewName) $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('NewName') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Remove('Force') $null = $PSBoundParameters.Add('Command', $Command) $null = $PSBoundParameters.Add('Method', 'post') if ($Force -or $PSCmdlet.ShouldProcess( ` $URI, ` $($LocalizedData.RenameJobMessage -f $Name, $NewName))) { $null = Invoke-JenkinsCommand @PSBoundParameters } # if } # Rename-JenkinsJob <# .SYNOPSIS Create a new Jenkins Job. .DESCRIPTION Creates a new Jenkins Job using the provided XML. If a folder is specified it will create the job in the specified folder. If the job already exists an error will occur. .PARAMETER Uri Contains the Uri to the Jenkins Master server to set the Job definition on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder the job is in. This requires the Jobs Plugin to be installed on Jenkins. If the folder does not exist then an error will occur. .PARAMETER Name The name of the job to add. .PARAMETER XML The config XML of the job to import. .EXAMPLE New-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -XML $MyAppBuildConfig ` -Verbose Sets the job definition of the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE New-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -XML $MyAppBuildConfig ` -Verbose Sets the job definition of the 'My App Build' job in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS None. #> function New-JenkinsJob() { [CmdLetBinding(SupportsShouldProcess=$true)] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [parameter( Position=6, Mandatory=$true, ValueFromPipeline=$True)] [ValidateNotNullOrEmpty()] [String] $XML ) $null = $PSBoundParameters.Add('Type','Command') $Command = '' if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' foreach ($Folder in $Folders) { $Command += "job/$Folder/" } # foreach } # if $Command += "createItem?name={0}" -f [System.Uri]::EscapeDataString($Name) $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Remove('XML') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Add('Command',$Command) $null = $PSBoundParameters.Add('Method','post') $null = $PSBoundParameters.Add('ContentType','application/xml') $null = $PSBoundParameters.Add('Body',$XML) if ($PSCmdlet.ShouldProcess(` $URI,` $($LocalizedData.NewJobMessage -f $Name))) { $null = Invoke-JenkinsCommand @PSBoundParameters } # if } # New-JenkinsJob <# .SYNOPSIS Remove an existing Jenkins Job. .DESCRIPTION Deletes an existing Jenkins Job in the specified Jenkins Master server. If a folder is specified it will remove the job in the specified folder. If the job does not exist an error will occur. .PARAMETER Uri Contains the Uri to the Jenkins Master server to set the Job definition on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder the job is in. This requires the Jobs Plugin to be installed on Jenkins. If the folder does not exist then an error will occur. .PARAMETER Name The name of the job to remove. .EXAMPLE Remove-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -Verbose Remove the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Remove-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -Verbose Remove the 'My App Build' job from the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS None. #> function Remove-JenkinsJob() { [CmdLetBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [Switch] $Force ) $null = $PSBoundParameters.Add('Type','Command') if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' $Command = 'job/' foreach ($Folder in $Folders) { $Command += "$Folder/job/" } # foreach $Command += "$Name/doDelete" } else { $Command = "job/$Name/doDelete" } # if $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Remove('Force') $null = $PSBoundParameters.Add('Command',$Command) $null = $PSBoundParameters.Add('Method','post') if ($Force -or $PSCmdlet.ShouldProcess(` $URI,` $($LocalizedData.RemoveJobMessage -f $Name))) { $null = Invoke-JenkinsCommand @PSBoundParameters } # if } # Remove-JenkinsJob <# .SYNOPSIS Invoke an existing Jenkins Job. .DESCRIPTION Runs an existing Jenkins Job. If a folder is specified it will run the job in the specified folder. If the job does not exist an error will occur. .PARAMETER Uri Contains the Uri to the Jenkins Master server to set the Job definition on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder the job is in. This requires the Jobs Plugin to be installed on Jenkins. If the folder does not exist then an error will occur. .PARAMETER Name The name of the job to set the definition on. .PARAMETER Parameters This is a hash table containg the job parameters for a parameterized job. The parameter names are case sensitive. If the job is a parameterized then this parameter must be passed even if it is empty. .EXAMPLE Invoke-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -Verbose Invoke the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Invoke-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My App Build' ` -Verbose Invoke the 'My App Build' job from the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Invoke-JenkinsJob ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My App Build' ` -Parameters @{ verbosity = 'full'; buildtitle = 'test build' } ` -Verbose Invoke the 'My App Build' job on https://jenkins.contoso.com using the credentials provided by the user and passing the build parameters verbosity and buildtitle. .OUTPUTS None. #> function Invoke-JenkinsJob() { [CmdLetBinding()] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [parameter( Position=6, Mandatory=$false)] [Hashtable] $Parameters ) $null = $PSBoundParameters.Add('Type','RestCommand') if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' $Command = 'job/' foreach ($Folder in $Folders) { $Command += "$Folder/job/" } # foreach $Command += "$Name/build" } else { $Command = "job/$Name/build" } # if $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Remove('Parameters') $null = $PSBoundParameters.Add('Command',$Command) $null = $PSBoundParameters.Add('Method','post') if ($Parameters) { $postValues = @() foreach ($key in $Parameters.Keys) { $postValues += @( @{ name = $key; value = $Parameters[$key] } ) } # foreach $postObject = @{ parameter = $postValues } $body = @{ json = (ConvertTo-JSON -InputObject $postObject) } $null = $PSBoundParameters.Add('Body',$body) } $null = Invoke-JenkinsCommand @PSBoundParameters } # Invoke-JenkinsJob <# .SYNOPSIS Get a list of views in a Jenkins master server. .DESCRIPTION Returns the list of views registered on a Jenkins Master server. The list of views returned can be filtered by setting the IncludeClass or ExcludeClass parameters. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER IncludeClass This allows the class of objects that are returned to be limited to only these types. .PARAMETER ExcludeClass This allows the class of objects that are returned to exclude these types. .EXAMPLE $Views = Get-JenkinsViewList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Verbose Returns the list of views on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Views = Get-JenkinsViewList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -ExcludeClass 'hudson.model.AllView' ` -Verbose Returns the list of views except for the AllView on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS An array of Jenkins View objects. #> function Get-JenkinsViewList() { [CmdLetBinding()] [OutputType([Object[]])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $IncludeClass, [parameter( Position=5, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $ExcludeClass ) $null = $PSBoundParameters.Add( 'Type', 'views') $null = $PSBoundParameters.Add( 'Attribute', @( 'name','url' ) ) return Get-JenkinsObject ` @PSBoundParameters } # Get-JenkinsViewList <# .SYNOPSIS Determines if a Jenkins View exists. .DESCRIPTION Returns true if a View exists in the specified Jenkins Master server with a matching Name. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Name The name of the view to check for. .EXAMPLE Test-JenkinsView ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My View' ` -Verbose Returns true if the 'My View' view is found on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS A boolean indicating if the View was found or not. #> function Test-JenkinsView() { [CmdLetBinding()] [OutputType([Boolean])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Name ) $null = $PSBoundParameters.Add( 'Type', 'views') $null = $PSBoundParameters.Add( 'Attribute', @( 'name' ) ) $null = $PSBoundParameters.Remove( 'Name' ) return ((@(Get-JenkinsObject @PSBoundParameters | Where-Object -Property Name -eq $Name)).Count -gt 0) } # Test-JenkinsView <# .SYNOPSIS Get a list of folders in a Jenkins master server. .DESCRIPTION Returns the list of folders registered on a Jenkins Master server in either the root folder or a specified subfolder. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional job folder to retrieve the folders from. .EXAMPLE $Folders = Get-JenkinsFolderList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Verbose Returns the list of job folders on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE $Folders = Get-JenkinsFolderList ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'My Builds' ` -Verbose Returns the list of job folders in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS An array of Jenkins Folder objects. #> function Get-JenkinsFolderList() { [CmdLetBinding()] [OutputType([Object[]])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder ) $null = $PSBoundParameters.Add( 'Type', 'jobs') $null = $PSBoundParameters.Add( 'Attribute', @( 'name','url','color' ) ) $null = $PSBoundParameters.Add( 'IncludeClass', 'com.cloudbees.hudson.plugins.folder.Folder') return Get-JenkinsObject ` @PSBoundParameters } # Get-JenkinsFolderList <# .SYNOPSIS Create a new Jenkins Folder. .DESCRIPTION Creates a new Jenkins Folder with the specifed Name and optional Description. If a folder is specified it will create the new folder inside the specified folder. If the folder already exists an error will occur. If XML is provided then the XML will be used instead of being generated automatically from the Name and description. This requires the Jobs Plugin to be installed on Jenkins. .PARAMETER Uri Contains the Uri to the Jenkins Master server to set the Job definition on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional folder the new folder will be created in. If the folder does not exist then an error will occur. .PARAMETER Name The name of the new folder to create. .PARAMETER Description The optional description of the new folder to create. .PARAMETER XML The optional config XML for the new folder. This allows additional properties to be set on the folder. .EXAMPLE New-JenkinsFolder ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'Management' ` -Description 'Management jobs' ` -Verbose Creates a new folder on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE New-JenkinsFolder ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Apps' ` -Name 'Management' ` -Description 'Management jobs' ` -Verbose Creates a new folder in the 'Apps' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS None. #> function New-JenkinsFolder() { [CmdLetBinding(SupportsShouldProcess=$true)] [OutputType([String])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Name, [parameter( Position=6, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Description, [parameter( Position=7, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $XML ) $null = $PSBoundParameters.Add('Type','Command') if (-not ($PSBoundParameters.ContainsKey('XML'))) { # Generate the XML we need to use to create the job $XML = @" <?xml version='1.0' encoding='UTF-8'?> <com.cloudbees.hudson.plugins.folder.Folder plugin="cloudbees-folder"> <actions/> <description>$Description</description> <properties/> </com.cloudbees.hudson.plugins.folder.Folder> "@ } $null = $PSBoundParameters.Remove('XML') $Command = '' if ($PSBoundParameters.ContainsKey('Folder')) { $Folders = ($Folder -split '\\') -split '/' foreach ($Folder in $Folders) { $Command += "job/$Folder/" } # foreach } # if $Command += "createItem?name=$Name" $null = $PSBoundParameters.Remove('Name') $null = $PSBoundParameters.Remove('Description') $null = $PSBoundParameters.Remove('Folder') $null = $PSBoundParameters.Remove('Confirm') $null = $PSBoundParameters.Add('Command',$Command) $null = $PSBoundParameters.Add('Method','post') $null = $PSBoundParameters.Add('ContentType','application/xml') $null = $PSBoundParameters.Add('Body',$XML) if ($PSCmdlet.ShouldProcess(` $URI,` $($LocalizedData.NewFolderMessage -f $Name))) { $null = Invoke-JenkinsCommand @PSBoundParameters } # if } # New-JenkinsFolder <# .SYNOPSIS Determines if a Jenkins Folder exists. .DESCRIPTION Returns true if a Folder exists in the specified Jenkins Master server with a matching Name. This requires the Jobs Plugin to be installed on Jenkins. It will search inside a specific folder if one is passed. .PARAMETER Uri Contains the Uri to the Jenkins Master server to execute the command on. .PARAMETER Credential Contains the credentials to use to authenticate with the Jenkins Master server. .PARAMETER Crumb Contains a Crumb to pass to the Jenkins Master Server if CSRF is enabled. .PARAMETER Folder The optional folder to look for the folder in. .PARAMETER Name The name of the folder to check for. .EXAMPLE Test-JenkinsFolder ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Name 'My Builds' ` -Verbose Returns true if the 'My Builds' folder is found on https://jenkins.contoso.com using the credentials provided by the user. .EXAMPLE Test-JenkinsFolder ` -Uri 'https://jenkins.contoso.com' ` -Credential (Get-Credential) ` -Folder 'Misc' ` -Name 'My Builds' ` -Verbose Returns true if the 'My Builds' folder is found in the 'Misc' folder on https://jenkins.contoso.com using the credentials provided by the user. .OUTPUTS A boolean indicating if the was found or not. #> function Test-JenkinsFolder() { [CmdLetBinding()] [OutputType([Boolean])] Param ( [parameter( Position=1, Mandatory=$true)] [String] $Uri, [parameter( Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [parameter( Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Crumb, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Folder, [parameter( Position=5, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String] $Name ) $null = $PSBoundParameters.Add( 'Type', 'jobs') $null = $PSBoundParameters.Add( 'Attribute', @( 'name' ) ) $null = $PSBoundParameters.Add( 'IncludeClass', 'com.cloudbees.hudson.plugins.folder.Folder') $null = $PSBoundParameters.Remove( 'Name' ) return ((@(Get-JenkinsObject @PSBoundParameters | Where-Object -Property Name -eq $Name)).Count -gt 0) } # Test-JenkinsFolder <# .SYNOPSIS This function creates or updates a local Jenkins Update cache. .DESCRIPTION The purpose of this function is to make a local copy of the standard Jenkins plugins found on Update-Center. It can also cache the Jenkins WAR file. This can allow an administrator to centrally control the plugins that are available to local Jenkins Masters. It can also control the Jenkins WAR file version that is available. It also allows creating a Jenkins Plugin cache inside DMZ or restrictive proxy to allow plugins to be made available to internal Jenkins servers. .PARAMETER Uri Contains the Uri to the Jenkins Update Center JSON file. This defaults to http://updates.jenkins-ci.org/update-center.json and should usually not need to be changed. .PARAMETER CacheUri Contains the Uri that the local Jenkins Update Cache will be accesible on. .PARAMETER Path The path to the folder that the Jenkins Update Cache will be stored in. .PARAMETER Include The optional list of plugins to include in the cache. Wildcards supported. If neither Include or Exclude are specified then no plugins will be cached. This allows just caching of the Jenkins core file. .PARAMETER Include The optional list of plugins to exclude from the cache. Wildcards supported. If neither Include or Exclude are specified then no plugins will be cached. This allows just caching of the Jenkins core file. .PARAMETER UpdateCore Setting this switch will cause the Jenkins WAR core to be cached. If this switch is not specified and this is a new cache then the core will still be available, but it will point to the external URI to download the core. .EXAMPLE Initialize-JenkinsUpdateCache ` -Path d:\JenkinsCache ` -CacheUri 'http:\\jenkinscache.contoso.com\cache' -Include '*' ` -UpdateCore Add or update all plugins and the Jenkins Core in the Jenkins Cache folder in d:\JenkinsCache. .EXAMPLE Initialize-JenkinsUpdateCache ` -Path d:\JenkinsCache ` -CacheUri 'http:\\jenkinscache.contoso.com\cache' -Include 'Yammer' Add or update the Yammer plugin in the Jenkins Cache folder in d:\JenkinsCache. .EXAMPLE Initialize-JenkinsUpdateCache ` -Path d:\JenkinsCache ` -CacheUri 'http:\\jenkinscache.contoso.com\cache' -Include 'A*' ` -UpdateCore Add or update all plugins in the Jenkins Cache folder in d:\JenkinsCache. Also, update the Jenkins Core WAR file if required. .OUTPUTS A list of plugin files that were downloaded to the Plugin cache. #> function Initialize-JenkinsUpdateCache() { [CmdLetBinding(SupportsShouldProcess=$true)] [OutputType([System.IO.FileInfo])] Param ( [parameter( Position=1, Mandatory=$false)] [String] $Uri = 'http://updates.jenkins-ci.org/update-center.json', [parameter( Position=2, Mandatory=$true)] [ValidateNotNullOrEmpty()] [ValidateScript({ Test-Path -Path $_ })] [String] $Path, [parameter( Position=3, Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $CacheUri, [parameter( Position=4, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $Include, [parameter( Position=5, Mandatory=$false)] [ValidateNotNullOrEmpty()] [String[]] $Exclude, [Switch] $UpdateCore, [Switch] $Force ) if ($CacheUri.EndsWith('/')) { $CacheUri = $CacheUri.Substring(0,$CacheUri.Length - 1) } # if # Download the Remote Update Center JSON Write-Verbose -Message $($LocalizedData.DownloadingRemoteUpdateListMessage -f $Uri) Set-JenkinsTLSSupport $remotePluginJSON = Invoke-WebRequest ` -Uri $Uri ` -UseBasicParsing $result = $remotePluginJSON.Content -match 'updateCenter.post\(\r?\n(.*)\r?\n\);' if (-not $result) { $ExceptionParameters = @{ errorId = 'UpdateListBadFormatError' errorCategory = 'InvalidArgument' errorMessage = $($LocalizedData.UpdateListBadFormatError -f ` 'remote',$Uri) } New-Exception @ExceptionParameters } $remoteJSON = ConvertFrom-Json -InputObject $Matches[1] # Generate an array of the Remote plugins and versions Write-Verbose -Message $($LocalizedData.ProcessingRemoteUpdateListMessage -f $Uri) $remotePlugins = [System.Collections.ArrayList] @() $remotePluginList = ($remoteJSON.Plugins | Get-Member -MemberType NoteProperty).Name foreach ($plugin in $remotePluginList) { if ($Include) { $addIt = $false # Includes only the entries that match the $Include array foreach ($item in $Include) { if ($plugin -like $item) { $addIt = $true } } } elseif ($Exclude) { # Excludes the entries that match the $Exclude array $addIt = $true foreach ($item in $Exclude) { if ($plugin -notlike $item) { $addIt = $false } } } # if if ($addIt) { $null = $remotePlugins.Add( $remoteJSON.Plugins.$plugin ) } } # foreach $localUpdateListPath = Join-Path -Path $Path -ChildPath 'update-center.json' if (Test-Path -Path $localUpdateListPath) { $localPluginJSON = Get-Content -Path $localUpdateListPath -Raw $result = $localPluginJSON -match 'updateCenter.post\(\r?\n(.*)\r?\n\);' if (-not $result) { $exceptionParameters = @{ errorId = 'UpdateListBadFormatError' errorCategory = 'InvalidArgument' errorMessage = $($LocalizedData.UpdateListBadFormatError -f ` 'local',$localUpdateListPath) } New-Exception @exceptionParameters } $localJSON = ConvertFrom-Json -InputObject $Matches[1] # Generate an array of the Remote plugins and versions Write-Verbose -Message $($LocalizedData.ProcessingLocalUpdateListMessage -f $localUpdateListPath) $localPlugins = [System.Collections.ArrayList] @() $localPluginList = ($LocalJSON.Plugins | Get-Member -MemberType NoteProperty).Name foreach ($plugin in $localPluginList) { if ($Include) { $addIt = $false # Includes only the entries that match the $Include array foreach ($item in $Include) { if ($plugin -like $item) { $addIt = $true } } } elseif ($Exclude) { # Excludes the entries that match the $Exclude array $addIt = $true foreach ($item in $Exclude) { if ($plugin -notlike $item) { $addIt = $false } } } # if if ($addIt) { $null = $localPlugins.Add( $localJSON.Plugins.$plugin ) } } # foreach } else { $localPlugins = [System.Collections.ArrayList] @() } # if # Now perform the comparison between the plugins that exist and the ones # that need to be downloaded and download any missing ones. # Step down the list of remote plugins in reverse so that we can remove # elements from the array. $cacheUpdated = $false for ($pluginNumber = $RemotePlugins.Count-1; $pluginNumber -ge 0; $pluginNumber--) { $remotePlugin = $RemotePlugins[$pluginNumber] Write-Verbose -Message $($LocalizedData.ProcessingPluginMessage -f $remotePlugin.name,$remotePlugin.version ) $pluginFilename = Split-Path -Path $remotePlugin.url -Leaf # Find out if the plugin already exists. $needsUpdate = $true $foundPlugin = $null foreach ($localPlugin in $LocalPlugins) { if ($localPlugin.name -eq $remotePlugin.name) { $foundPlugin = $localPlugin if ($localPlugin.version -eq $remotePlugin.version) { # TODO: Add hash check to validate cached file $needsUpdate = $false break } # if } # if } # foreach if ($foundPlugin) { Write-Verbose -Message $($LocalizedData.ExistingPluginFoundMessage -f $foundPlugin.name,$foundPlugin.version) } if ($needsUpdate) { $downloadOK = $false if ($Force -or $PSCmdlet.ShouldProcess(` $remotePlugin.name,` $($LocalizedData.UpdateJenkinsPluginMessage -f $remotePlugin.name,$remotePlugin.verion))) { # A new version of the plugin needs to be downloaded $PluginFilePath = Join-Path -Path $Path -ChildPath $pluginFilename if (Test-Path -Path $PluginFilePath) { # The plugin file already exists so remove it Write-Verbose -Message $($LocalizedData.RemovingPluginFileMessage -f $PluginFilePath) $null = Remove-Item -Path $PluginFilePath -Force } # if Write-Verbose -Message $($LocalizedData.DownloadingPluginMessage -f $remotePlugin.name,$remotePlugin.url,$PluginFilePath) # Download the plugin try { Invoke-WebRequest ` -Uri $remotePlugin.url ` -UseBasicParsing ` -OutFile $PluginFilePath ` -ErrorAction Stop $downloadOK = $true } catch { Write-Error -Exception $_ } # try if ($downloadOk) { $cacheUpdated = $true } # if } # if if ($downloadOk) { if ($foundPlugin) { # The plugin already exists so remove the entry before adding a new one $null = $localPlugins.Remove($foundPlugin) } # if # Add the plugin to the local plugins list $remotePlugin.url = "$CacheUri/$pluginFilename" $null = $localPlugins.Add( $remotePlugin ) # Report that the file was downloaded Get-ChildItem -Path $pluginFilePath } # if } # if } # foreach if ($cacheUpdated) { # Generate new Local Plugin JSON object $newPlugins = New-Object PSCustomObject foreach ($plugin in $localPlugins | Sort-Object -Property name) { $null = Add-Member ` -InputObject $newPlugins ` -Type NoteProperty ` -Name $plugin.name ` -Value $plugin } # foreach $remoteJSON.plugins = $newPlugins } # if if ($UpdateCore) { # Need to see if the Jenkins Core needs to be updated $coreFilename = Split-Path -Path $remoteJSON.Core.url -Leaf if (($localJSON.Core.version -ne $remoteJSON.Core.version) -or ` ($localJSON.Core.url -ne "$CacheUri/$coreFilename")) { $downloadOK = $false if ($Force -or $PSCmdlet.ShouldProcess(` $remoteJSON.Core.version,` $($LocalizedData.UpdateJenkinsCoreMessage -f $remoteJSON.Core.version))) { # A new version of the plugin needs to be downloaded $coreFilePath = Join-Path -Path $Path -ChildPath $coreFilename if (Test-Path -Path $coreFilePath) { # The plugin file already exists so remove it Write-Verbose -Message $($LocalizedData.RemovingJenkinsCoreFileMessage -f $coreFilePath) $null = Remove-Item -Path $coreFilePath -Force } # if Write-Verbose -Message $($LocalizedData.DownloadingJenkinsCoreMessage -f $remoteJSON.Core.url,$coreFilePath) try { Invoke-WebRequest ` -Uri $remoteJSON.Core.url ` -UseBasicParsing ` -OutFile $coreFilePath ` -ErrorAction Stop $downloadOK = $true } catch { Write-Error -Exception $_ } # try if ($downloadOk) { # Update the Cache List file $remoteJSON.Core.Url = "$CacheUri/$coreFilename" $cacheUpdated = $true # Report that the file was downloaded Get-ChildItem -Path $coreFilePath } # if } # if } else { Write-Verbose -Message $($LocalizedData.ExistingJenkinsCoreFoundMessage -f $remoteJSON.Core.version) } # if } # if if ($cacheUpdated) { # Convert the JSON object into JSON $newJSON = ConvertTo-Json -InputObject $remoteJSON -Compress # Create the new Local Plugin JSON file content $localPluginJSON = "updateCenter.post(`n$newJSON`n);" if ($Force -or $PSCmdlet.ShouldProcess(` $localUpdateListPath, ` $($LocalizedData.CreateJenkinsUpdateListMessage -f $localUpdateListPath))) { # Write out the new Local Update List file if (Test-Path -Path $localUpdateListPath) { $null = Remove-Item -Path $localUpdateListPath -Force } # if $null = Set-Content -Path $localUpdateListPath -Value $localPluginJSON -NoNewline } # if } # if } # Initialize-JenkinsUpdateCache |