├── PSGLPI.psm1 └── README.md /PSGLPI.psm1: -------------------------------------------------------------------------------- 1 | # Internal Functions have names WITHOUT dash "-" caracter. 2 | 3 | Function GetGLPISessionToken { 4 | param($Creds) 5 | #Get-Date -f T | write-host -NoNewLine 6 | #Write-Host " Enter Function" 7 | $Creds.AuthorizationType 8 | if (("Basic","user_token") -ccontains $Creds.AuthorizationType) {Invoke-RestMethod "$($Creds.AppURL)/initSession" -Headers @{"Content-Type" = "application/json";"Authorization" = "$($Creds.AuthorizationType) $($Creds.UserToken)";"App-Token"=$Creds.AppToken}} 9 | else {Write-Host 'AuthorizationType MUST be "user_token" or "Basic". This is Case Sensitive.' -ForegroundColor Red} 10 | } 11 | 12 | function Get-GlpiBase64Login { 13 | <# 14 | .SYNOPSIS 15 | The Base64 encoded login & password. 16 | .DESCRIPTION 17 | Generate the Base64 login & password string used to authenticate with GLPI. 18 | .PARAMETER login 19 | User name 20 | .PARAMETER password 21 | Password 22 | .EXAMPLE 23 | Get-GLPILoginBase64 -login "MyGlpiUser" -password "MyGlpiPassword" 24 | .INPUTS 25 | Strings 26 | .OUTPUTS 27 | String 28 | .NOTES 29 | Author: Jean-Christophe Pirmolin #> 30 | param([parameter(Mandatory=$true)][String]$login,[parameter(Mandatory=$true)][String]$password) 31 | $sStringToEncode="$($login):$($password)" 32 | $sEncodedString=[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sStringToEncode)) 33 | return $sEncodedString 34 | } 35 | 36 | 37 | Function Get-GlpiItems { 38 | <# 39 | .SYNOPSIS 40 | Get all items of a specific item type. 41 | .DESCRIPTION 42 | Retrieve all items of a specific item type by range. 43 | Useful for instance, to load a list in memory and avoid multiple call to an existing collection. 44 | .PARAMETER ItemType 45 | Type of item wanted. 46 | Exemples : Computer, Monitor, User, etc. 47 | .PARAMETER Range 48 | Range of the results. 49 | Exemple : 0-199 50 | .PARAMETER Creds 51 | Credetials for the GLPI API. This is an object. 52 | Exemple : $GlpiCreds = @{ 53 | AppURL = "https://[MyGlpiServer]/apirest.php" 54 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 55 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 56 | AuthorizationType = "Basic" or "user_token" 57 | } 58 | .PARAMETER QueryOptions 59 | Options to pass to the query. See API documentation. 60 | Separator is "&" 61 | expand_dropdowns (default: false): show dropdown name instead of id. Optional. 62 | get_hateoas (default: true): Show relation of item in a links attribute. Optional. 63 | only_id (default: false): keep only id keys in returned data. Optional. 64 | sort (default 1): name of the field to sort by. Optional. 65 | order (default ASC): ASC - Ascending sort / DESC Descending sort. Optional. 66 | searchText (default NULL): array of filters to pass on the query (with key = field and value the text to search) 67 | is_deleted (default: false): Return deleted element. Optional. 68 | add_keys_names: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional. 69 | Exemple : expand_dropdowns=true&get_hateoas=false 70 | .EXAMPLE 71 | Get-GlpiItems -ItemType "Location" -Range "0-99" -Creds $GlpiCreds 72 | .INPUTS 73 | None 74 | .OUTPUTS 75 | Array 76 | .NOTES 77 | Author: Jean-Christophe Pirmolin #> 78 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$false)][String]$Range="0-999",[parameter(Mandatory=$true)][Object]$Creds, $QueryOptions="") 79 | 80 | $UserToken = $Creds.UserToken 81 | $SessionToken = GetGLPISessionToken -Creds $Creds 82 | $SearchResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/?range=$($Range)&$($QueryOptions)" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 83 | if ($SearchResult.Count -ge 1) {$SearchResult} 84 | else {$false} 85 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 86 | } 87 | 88 | Function Get-GlpiItem { 89 | <# 90 | .SYNOPSIS 91 | Get a specific item by item type. 92 | .DESCRIPTION 93 | Retrieve a specific item. 94 | Return the instance fields of item identified by id 95 | .PARAMETER ItemType 96 | Type of item wanted. 97 | Exemples : Computer, Monitor, User, etc. 98 | .PARAMETER ID 99 | ID of item wanted. 100 | Exemples : 114 101 | .PARAMETER Creds 102 | Credetials for the GLPI API. This is an object. 103 | Exemple : $GlpiCreds = @{ 104 | AppURL = "https://[MyGlpiServer]/apirest.php" 105 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 106 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 107 | AuthorizationType = "Basic" or "user_token" 108 | } 109 | .PARAMETER QueryOptions 110 | Options to pass to the query. See API documentation. 111 | Separator is "&" 112 | expand_dropdowns (default: false): show dropdown name instead of id. Optional. 113 | get_hateoas (default: true): Show relation of item in a links attribute. Optional. 114 | only_id (default: false): keep only id keys in returned data. Optional. 115 | sort (default 1): name of the field to sort by. Optional. 116 | order (default ASC): ASC - Ascending sort / DESC Descending sort. Optional. 117 | searchText (default NULL): array of filters to pass on the query (with key = field and value the text to search) 118 | is_deleted (default: false): Return deleted element. Optional. 119 | add_keys_names: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional. 120 | Exemple : expand_dropdowns=true&get_hateoas=false 121 | .EXAMPLE 122 | Get-GlpiItem -ItemType "Monitor" -ID 114 -Creds $GlpiCreds 123 | .INPUTS 124 | None 125 | .OUTPUTS 126 | Array 127 | .NOTES 128 | Author: Jean-Christophe Pirmolin #> 129 | param([parameter(Mandatory=$true)][String]$ItemType, [parameter(Mandatory=$true)][Int]$ID, $QueryOptions="", [parameter(Mandatory=$true)][object]$Creds) 130 | $SessionToken = GetGLPISessionToken -Creds $Creds 131 | $SearchResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/$($ID)?$QueryOptions" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -ErrorAction Ignore 132 | if ($SearchResult) {$SearchResult} 133 | else {$false} 134 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 135 | } 136 | 137 | Function Get-GlpiSubItems { 138 | <# 139 | .SYNOPSIS 140 | Get a specific item by item type. 141 | .DESCRIPTION 142 | Retrieve a specific item. 143 | Return the instance fields of item identified by id 144 | .PARAMETER ItemType 145 | Type of item wanted. 146 | Exemples : Computer, Monitor, User, etc. 147 | .PARAMETER ID 148 | ID of item wanted. 149 | Exemples : 114 150 | .PARAMETER Creds 151 | Credetials for the GLPI API. This is an object. 152 | Exemple : $GlpiCreds = @{ 153 | AppURL = "https://[MyGlpiServer]/apirest.php" 154 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 155 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 156 | AuthorizationType = "Basic" or "user_token" 157 | } 158 | .EXAMPLE 159 | Get-GlpiItem -ItemType "Monitor" -ID 114 -Creds $GlpiCreds 160 | .INPUTS 161 | None 162 | .OUTPUTS 163 | Array 164 | .NOTES 165 | Author: Jean-Christophe Pirmolin #> 166 | param([parameter(Mandatory=$true)][String]$ItemType, [parameter(Mandatory=$true)][Int]$ID, [String]$QueryOptions="", [parameter(Mandatory=$true)][Object]$Creds, [parameter(Mandatory=$true)][String]$Relation) 167 | $SessionToken = GetGLPISessionToken -Creds $Creds 168 | $SearchResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/$($ID)/$($Relation)?$QueryOptions" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -ErrorAction Ignore 169 | if ($SearchResult) {$SearchResult} 170 | else {$false} 171 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 172 | } 173 | 174 | Function Search-GlpiItem { 175 | <# 176 | .SYNOPSIS 177 | Use the GLPI Search Engine. 178 | .DESCRIPTION 179 | Expose the GLPI searchEngine and combine criteria to retrieve a list of elements of specified itemtype. 180 | .PARAMETER ItemType 181 | Type of item wanted. 182 | Note : you can use 'AllAssets' itemtype to retrieve a combination of all asset's types. 183 | Exemples : Computer, Monitor, User, etc. 184 | .PARAMETER SearchOptions 185 | SearchOptions should be given in a form of array of arrays. 186 | It contains 187 | - link: logical operator in [AND, OR, AND NOT, AND NOT]. 188 | - field: id of the searchoption. 189 | - searchtype: type of search in [contains, equals, notequals, lessthan, morethan, under, notunder]. 190 | - value: the value to search. 191 | Notes : 192 | "Contains" will use a wildcard search per default. You can restrict at the beginning using the ^ character, and/or at the end using the $ character. 193 | "equals" and "notequals" are designed to be used with dropdowns. Do not expect those operators to search for a strictly equal value (see above). 194 | ("AND",1,"contains","AMC0132"),("OR",1,"contains","AMC0176) 195 | 196 | If only ONE criteria is present, start with a COMA and put all between brakets! 197 | (,("OR",1,"contains","AMC0176")) 198 | BE CAREFULL the first coma in the SearchOption definition!! 199 | 200 | You can use Get-GlpiSearchOptions to display the list of search options (fields) available for a specific item type. 201 | 202 | If you want to retreive a specific field that is missing the default result view, you can use the ForceDisplay parameter. 203 | Exemples : ("AND",1,"contains","AMC"),("AND",105,"is","Luxembourg") to find items that contains "AMC" in the name AND are located in "Luxembourg". 204 | ,("OR",1,"contains","AMC0176") to find items that contains "AMC0176" in the name. 205 | .PARAMETER ForceDisplay 206 | Array of columns to display (default empty = use display preferences and searched criteria). Some columns will be always presents (1: id, 2: name, 80: Entity). Optional. 207 | If only ONE column id is needed, the input needs to be an array anyway. You need to enter it like this (,12) with a COMA. 208 | Exemple : (,12) or (118,154,12) 209 | .PARAMETER Range 210 | Range of the results. (Optional, default is 0-999) 211 | Exemple : 0-199 212 | .PARAMETER Creds 213 | Credetials for the GLPI API. This is an object. 214 | Exemple : $GlpiCreds = @{ 215 | AppURL = "https://[MyGlpiServer]/apirest.php" 216 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 217 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 218 | AuthorizationType = "Basic" or "user_token" 219 | } 220 | .EXAMPLE 221 | Search-GlpiItem -ItemType "Monitor" -SearchOptions (,("AND",21,"contains","^737386")) -ForceDisplay(,13) -Creds $GlpiCreds 222 | .INPUTS 223 | None 224 | .OUTPUTS 225 | Array 226 | .NOTES 227 | Author: Jean-Christophe Pirmolin #> 228 | param([Parameter(Mandatory=$true)][String] $ItemType,[Parameter(Mandatory=$true)][array] $SearchOptions,[Parameter(Mandatory=$false)][array] $ForceDisplay,[String]$Range="0-999",[Parameter(Mandatory=$true)][Object] $Creds) 229 | 230 | # Building the SearchOptions String 231 | $i=0 232 | foreach ($Criteria in $SearchOptions) { 233 | if ($i -eq 0) {$StrSearchOptions = "criteria[$($i)][link]=$($Criteria[0])&criteria[$($i)][field]=$($Criteria[1])&criteria[$($i)][searchtype]=$($Criteria[2])&criteria[$($i)][value]=$($Criteria[3].replace("'","''"))" 234 | } 235 | else {$StrSearchOptions = "$($StrSearchOptions)&criteria[$($i)][link]=$($Criteria[0])&criteria[$($i)][field]=$($Criteria[1])&criteria[$($i)][searchtype]=$($Criteria[2])&criteria[$($i)][value]=$($Criteria[3].replace("'","''"))" 236 | } 237 | $i++ 238 | } 239 | $i=0 240 | foreach ($FieldToDisplay in $ForceDisplay) { 241 | if ($i -eq 0) { 242 | $StrSearchOptions = "forcedisplay[0]=$FieldToDisplay" 243 | } 244 | else { 245 | $StrSearchOptions = "$($StrSearchOptions)&forcedisplay[$i]=$FieldToDisplay" 246 | } 247 | $i++ 248 | } 249 | $SessionToken = GetGLPISessionToken -Creds $Creds 250 | $SearchResult = Invoke-RestMethod "$($Creds.AppUrl)/search/$($ItemType)?$StrSearchOptions&range=$($Range)&forcedisplay[2]=1" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -ErrorAction Ignore 251 | if ($SearchResult) {$SearchResult.data} 252 | else {return $false} 253 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 254 | } 255 | 256 | Function Get-GlpiSearchOptions { 257 | <#.SYNOPSIS 258 | List search option for GLPI Search Engine. 259 | .DESCRIPTION 260 | Expose the GLPI searchEngine options / fields for a specified item type. 261 | .PARAMETER ItemType 262 | Type of item wanted. 263 | Note : you can use 'AllAssets' itemtype to retrieve a combination of all asset's types. 264 | Exemples : Computer, Monitor, User, etc. 265 | .PARAMETER Creds 266 | Credetials for the GLPI API. This is an object. 267 | Exemple : $GlpiCreds = @{ 268 | AppURL = "https://[MyGlpiServer]/apirest.php" 269 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 270 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 271 | AuthorizationType = "Basic" or "user_token" 272 | } 273 | .EXAMPLE 274 | Get-GlpiSearchOptions -ItemType "Monitor" -Creds $GlpiCreds 275 | .INPUTS 276 | None 277 | .OUTPUTS 278 | Array 279 | .NOTES 280 | Author: Jean-Christophe Pirmolin #> 281 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Object]$Creds) 282 | $SessionToken = GetGLPISessionToken -Creds $Creds 283 | $SearchResult = Invoke-RestMethod "$($Creds.AppURL)/listSearchOptions/$($ItemType)" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -ErrorAction Ignore 284 | if ($SearchResult) { 285 | $SearchOptions = $SearchResult.PSObject.Properties #| Select-Object -property Value | Select-Object -Property * 286 | $Result = @() 287 | foreach ($Option in $SearchOptions) { 288 | $item = New-Object psobject 289 | $Item | Add-Member -Type NoteProperty -Name ID -Value $Option.name 290 | $Item | Add-Member -Type NoteProperty -Name "Field Name" -Value $Option.value.field 291 | $Item | Add-Member -Type NoteProperty -Name Name -Value $Option.value.name 292 | $Result += $item 293 | } 294 | $Result 295 | } 296 | else {return $false} 297 | Invoke-RestMethod "$($Creds.AppURL)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 298 | } 299 | 300 | 301 | Function Add-GlpiItem { 302 | <# 303 | .SYNOPSIS 304 | Add an object into GLPI. 305 | .DESCRIPTION 306 | Add an object (or multiple objects) into GLPI. 307 | .PARAMETER ItemType 308 | Type of item wanted. 309 | Note : you can use 'AllAssets' itemtype to retrieve a combination of all asset's types. 310 | Exemples : Computer, Monitor, User, etc. 311 | .PARAMETER Details 312 | Describe the details of the object you wan to add into GLPI. 313 | It is expected to be an object that you can create using : 314 | $Details = @{ 315 | name="PC99999" 316 | serial="01.02.03.04.05"} 317 | .PARAMETER Creds 318 | Credetials for the GLPI API. This is an object. 319 | Exemple : $GlpiCreds = @{ 320 | AppURL = "https://[MyGlpiServer]/apirest.php" 321 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 322 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 323 | AuthorizationType = "Basic" or "user_token" 324 | } 325 | .EXAMPLE 326 | $Details = @{ 327 | name="PC99999" 328 | serial="01.02.03.04.05"} 329 | Add-GlpiItem -ItemType "computer" -Details $Details -Creds $GlpiCreds 330 | .INPUTS 331 | None 332 | .OUTPUTS 333 | Array 334 | .NOTES 335 | Author: Jean-Christophe Pirmolin #> 336 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Object]$Details,[parameter(Mandatory=$true)][Object]$Creds) 337 | $Details = @{input=$Details} 338 | $SessionToken = GetGLPISessionToken -Creds $Creds 339 | $json = ConvertTo-Json $Details 340 | $AddResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)" -Method Post -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) -ContentType 'application/json' 341 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 342 | return $AddResult 343 | } 344 | 345 | Function Add-GlpiSubItem { 346 | <# 347 | .SYNOPSIS 348 | Add a sub object into GLPI. 349 | .DESCRIPTION 350 | Add a sub object (or multiple objects) into GLPI. 351 | .PARAMETER ItemType 352 | Type of PARENT item. 353 | Exemples : Computer, Monitor, User, Ticket, etc. 354 | .PARAMETER ID 355 | ID of the PARENT item. 356 | Exemples : 114 357 | .PARAMETER Details 358 | Describe the details of the sub object you wan to add into GLPI. 359 | It is expected to be a sub object that you can create using : 360 | $Details = @{ 361 | name="internal" 362 | IP="127.0.0.1"} 363 | .PARAMETER SubItemType 364 | Type of SUB item you want to add. 365 | Exemple : ITILFolowup for a ticket, Networkname for a network device, etc. 366 | Note : If the SubItemType is a "Document_Item", "name" and "_filename" are requested details. 367 | .PARAMETER Creds 368 | Credetials for the GLPI API. This is an object. 369 | Exemple : $GlpiCreds = @{ 370 | AppURL = "https://[MyGlpiServer]/apirest.php" 371 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 372 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 373 | AuthorizationType = "Basic" or "user_token" 374 | } 375 | .EXAMPLE 376 | $Details = @{ 377 | name="PC99999" 378 | serial="01.02.03.04.05"} 379 | Add-GlpiItem -ItemType "computer" -Details $Details -Creds $GlpiCreds 380 | .INPUTS 381 | None 382 | .OUTPUTS 383 | Array 384 | .NOTES 385 | Author: Jean-Christophe Pirmolin #> 386 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][String]$SubItemType,[parameter(Mandatory=$true)][Object]$Details,[parameter(Mandatory=$true)][Object]$Creds) 387 | $SessionToken = GetGLPISessionToken -Creds $Creds 388 | if ($SubItemType -eq "Document") { 389 | $FileContent = [System.IO.File]::ReadAllBytes($Details._filename) 390 | $uploadManifest = @{ 391 | uploadManifest= @{input = $Details} 392 | filename= @($FileContent) 393 | } 394 | $json = ConvertTo-Json $uploadManifest 395 | Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/$($ID)/$($SubItemType)" -Method Post -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) -ContentType 'multipart/data' 396 | } 397 | else { 398 | $Details = @{input=$Details} 399 | $json = ConvertTo-Json $Details 400 | $AddResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/$($ID)/$($SubItemType)" -Method Post -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) -ContentType 'application/json' 401 | } 402 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 403 | return $AddResult 404 | } 405 | 406 | 407 | Function Update-GlpiItem { 408 | <# 409 | .SYNOPSIS 410 | Update an object into GLPI. 411 | .DESCRIPTION 412 | Update an object into GLPI. 413 | .PARAMETER ItemType 414 | Type of item want to update. 415 | Exemples : Computer, Monitor, User, etc. 416 | .PARAMETER ID 417 | ID of item you want to update. 418 | Exemples : 117 419 | .PARAMETER Details 420 | Describe the details of the object you wan to update into GLPI. 421 | It is expected to be an object that you can create using : 422 | $Details = @{ 423 | name="PC99999" 424 | serial="01.02.03.04.05"} 425 | .PARAMETER Creds 426 | Credetials for the GLPI API. This is an object. 427 | Exemple : $GlpiCreds = @{ 428 | AppURL = "https://[MyGlpiServer]/apirest.php" 429 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 430 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 431 | AuthorizationType = "Basic" or "user_token" 432 | } 433 | .EXAMPLE 434 | $Details = @{ 435 | name="PC99999" 436 | serial="01.02.03.04.05"} 437 | Update-GlpiItem -ItemType "computer" -Details $Details -Creds $GlpiCreds -ID 117 438 | .INPUTS 439 | None 440 | .OUTPUTS 441 | Array 442 | .NOTES 443 | Author: Jean-Christophe Pirmolin #> 444 | param($ItemType, $Details, $Creds) 445 | $Details = @{input=$Details} 446 | $SessionToken = GetGLPISessionToken -Creds $Creds 447 | $json = $Details | ConvertTo-Json 448 | $AddResult = Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)/$($ID)" -Method Put -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) -ContentType 'application/json' 449 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} 450 | return $AddResult 451 | } 452 | 453 | 454 | Function Remove-GlpiItems { 455 | <# 456 | .SYNOPSIS 457 | Remove a specific item by item type. 458 | .DESCRIPTION 459 | Remove a specific item. 460 | .PARAMETER ItemType 461 | Type of item wanted. 462 | Exemples : Computer, Monitor, User, etc. 463 | .PARAMETER IDs 464 | Array of IDs of item to remove. If only ONE criteria is present, start with a COMA! 465 | Exemples : ,(114) or (110,114) 466 | .PARAMETER Creds 467 | Credetials for the GLPI API. This is an object. 468 | Exemple : $GlpiCreds = @{ 469 | AppURL = "https://[MyGlpiServer]/apirest.php" 470 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 471 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 472 | AuthorizationType = "Basic" or "user_token" 473 | } 474 | .PARAMETRE Purge 475 | If the itemtype have a trashbin, you can force purge (delete finally).Default: False 476 | Exemple : false, true 477 | .PARAMETRE History 478 | Set to false to disable saving of deletion in global history. Default: True. 479 | Exemple : false, true 480 | .EXAMPLE 481 | Remove-GlpiItems -ItemType "Monitor" -IDs 114 -Purge $true -History $false -Creds $GlpiCreds 482 | .INPUTS 483 | None 484 | .OUTPUTS 485 | Array 486 | .NOTES 487 | Author: Jean-Christophe Pirmolin #> 488 | param( 489 | [parameter(Mandatory=$true)][String]$ItemType, 490 | [parameter(Mandatory=$true)][Array]$IDs, 491 | [parameter(Mandatory=$true)][object]$Creds, 492 | [parameter(Mandatory=$false)][string]$Purge="false", 493 | [parameter(Mandatory=$false)][string]$History="true") 494 | 495 | # Build array of IDs. 496 | if ($IDs -notcontains "ID"){ 497 | $ids2 = @() 498 | foreach ($ID in $IDs){ 499 | $hash = [ordered]@{} 500 | $hash.add("id" , $ID) 501 | $ids2 += [pscustomobject]$hash 502 | } 503 | $IDs = $ids2 504 | } 505 | $Details = @{ 506 | input=$IDs 507 | force_purge = $Purge 508 | history = $History} 509 | $json = $Details | ConvertTo-Json 510 | #if (($Details["input"] | Get-Member -MemberType Properties).Count -eq 1){ 511 | # $json = $json.Remove(($lastIndex = $json.LastIndexOf("]")),1).Insert($lastIndex,"").Remove(($firstIndex = $json.IndexOf("[")),1).Insert($firstIndex,"") 512 | # } 513 | $SessionToken = GetGLPISessionToken -Creds $Creds 514 | Invoke-RestMethod "$($Creds.AppUrl)/$($ItemType)" -Method Delete -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -Body $json -ContentType 'application/json' 515 | Invoke-RestMethod "$($Creds.AppUrl)/killSession" -Headers @{"session-token"=$SessionToken.session_token; "App-Token" = "$($Creds.AppToken)"} -ErrorAction SilentlyContinue| Out-Null 516 | } 517 | 518 | Function Get-GlpiFieldLock { 519 | <# 520 | .SYNOPSIS 521 | List a field lock(s) of an item. 522 | .DESCRIPTION 523 | Get the list of field locks of an item. This requires that FusionInventory plugin is installed. 524 | .PARAMETER ItemType 525 | Type of item to retrieve the list of field locks on. 526 | Exemples : Computer, Monitor, Printer, etc. 527 | .PARAMETER Id 528 | ID of item to retrieve the list of field locks on. 529 | Exemple : 1600 530 | .PARAMETER Creds 531 | Credetials for the GLPI API. This is an object. 532 | Exemple : $GlpiCreds = @{ 533 | AppURL = "https://[MyGlpiServer]/apirest.php" 534 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 535 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 536 | AuthorizationType = "Basic" or "user_token" 537 | } 538 | .EXAMPLE 539 | Get-GlpiFieldLock -ItemType "printer" -ID 1600 -Creds $GlpiCreds 540 | .INPUTS 541 | None 542 | .OUTPUTS 543 | Array of strings 544 | .NOTES 545 | Author: Jean-Christophe Pirmolin #> 546 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][Object]$Creds) 547 | $tablename = "glpi_$($ItemType)s" 548 | $ExistingLocks = Get-GlpiItems -Creds $GlpiCreds -ItemType PluginFusioninventoryLock -Range 0-999999999 | ? {$_.tablename -eq $tablename -and $_.items_id -eq $id} 549 | if ($ExistingLocks) { 550 | $LocksArray=$ExistingLocks.tablefields.trim(@("[","]")).split(",")#.trim('"') 551 | $LocksArray = $LocksArray.ForEach({$_ -replace '"'}) 552 | return $LocksArray 553 | } 554 | } 555 | 556 | Function Add-GlpiFieldLock { 557 | <# 558 | .SYNOPSIS 559 | Add a lock on a field of an item. 560 | .DESCRIPTION 561 | Add a lock on a field of an item. This requires that FusionInventory plugin is installed. 562 | .PARAMETER ItemType 563 | Type of item to manipulate. 564 | Exemples : Computer, Monitor, Printer, etc. 565 | .PARAMETER Id 566 | ID of item to manipulate. 567 | Exemple : 1600 568 | .PARAMETER Field 569 | The field you want to lock. 570 | Exemples : serial, comment, otherserial, etc. 571 | .PARAMETER Creds 572 | Credetials for the GLPI API. This is an object. 573 | Exemple : $GlpiCreds = @{ 574 | AppURL = "https://[MyGlpiServer]/apirest.php" 575 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 576 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 577 | AuthorizationType = "Basic" or "user_token" 578 | } 579 | .EXAMPLE 580 | Add-GlpiFieldLock -ItemType "printer" -ID 1600 -Field otherserial -Creds $GlpiCreds 581 | .INPUTS 582 | None 583 | .OUTPUTS 584 | None 585 | .NOTES 586 | Author: Jean-Christophe Pirmolin #> 587 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][String]$Field,[parameter(Mandatory=$true)][Object]$Creds) 588 | $tablename = "glpi_$($ItemType)s" 589 | $ExistingLocks = Get-GlpiItems -Creds $GlpiCreds -ItemType PluginFusioninventoryLock -Range 0-999999999 | ? {$_.tablename -eq $tablename -and $_.items_id -eq $id} 590 | if ($ExistingLocks) { 591 | $LocksArray=$ExistingLocks.tablefields.trim(@("[","]")).split(",")#.trim('"') 592 | $LocksArray = $LocksArray.ForEach({$_ -replace '"'}) 593 | if ($LocksArray -icontains $Field) { 594 | return "already locked" 595 | } 596 | else { 597 | $LocksArray.Add($Field) 598 | $LocksString = "[" + (($LocksArray.ForEach({ '"' + $_ + '"' })) -join ",") + "]" 599 | $Details = @{ 600 | id=$ExistingLocks.id 601 | tablefields=$LocksString} 602 | $return = Update-GlpiItem -ItemType "PluginFusioninventoryLock" -Details $Details -Creds $GlpiCreds 603 | return $return 604 | } 605 | } 606 | else { 607 | $LocksArray = @($Field) 608 | $LocksString = "[" + (($LocksArray.ForEach({ '"' + $_ + '"' })) -join ",") + "]" 609 | $Details = @{ 610 | tablename=$tablename 611 | items_id=$ID 612 | tablefields=$LocksString} 613 | $return = Add-GlpiItem -ItemType "PluginFusioninventoryLock" -Details $Details -Creds $GlpiCreds 614 | return $return 615 | } 616 | } 617 | 618 | Function Remove-GlpiFieldLock { 619 | <# 620 | .SYNOPSIS 621 | Remove a lock on a field of an item. 622 | .DESCRIPTION 623 | Remove a lock on a field of an item. This requires that FusionInventory plugin is installed. 624 | .PARAMETER ItemType 625 | Type of item to manipulate. 626 | Exemples : Computer, Monitor, Printer, etc. 627 | .PARAMETER Id 628 | ID of item to manipulate. 629 | Exemple : 1600 630 | .PARAMETER Field 631 | The field you want to unlock. 632 | Exemples : serial, comment, otherserial, etc. 633 | .PARAMETER Creds 634 | Credetials for the GLPI API. This is an object. 635 | Exemple : $GlpiCreds = @{ 636 | AppURL = "https://[MyGlpiServer]/apirest.php" 637 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 638 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 639 | AuthorizationType = "Basic" or "user_token" 640 | } 641 | .EXAMPLE 642 | Remove-GlpiFieldLock -ItemType "printer" -ID 1600 -Field otherserial -Creds $GlpiCreds 643 | .INPUTS 644 | None 645 | .OUTPUTS 646 | None 647 | .NOTES 648 | Author: Jean-Christophe Pirmolin #> 649 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][String]$Field,[parameter(Mandatory=$true)][Object]$Creds) 650 | $tablename = "glpi_$($ItemType)s" 651 | $ExistingLocks = Get-GlpiItems -Creds $GlpiCreds -ItemType PluginFusioninventoryLock -Range 0-999999999 | ? {$_.tablename -eq $tablename -and $_.items_id -eq $id} 652 | if ($ExistingLocks) { 653 | $LocksArray=$ExistingLocks.tablefields.trim(@("[","]")).split(",")#.trim('"') 654 | $LocksArray = $LocksArray.ForEach({$_ -replace '"'}) 655 | if ($LocksArray -icontains $Field) { 656 | # Need to unlock 657 | $LocksArray.remove($field) 658 | if ($LocksArray.Count -gt 0) { 659 | $LocksString = "[" + (($LocksArray.ForEach({ '"' + $_ + '"' })) -join ",") + "]" 660 | $Details = @{ 661 | id=$ExistingLocks.id 662 | tablefields=$LocksString} 663 | $return = Update-GlpiItem -ItemType "PluginFusioninventoryLock" -Details $Details -Creds $GlpiCreds 664 | } 665 | else { 666 | $return = Remove-GlpiItems -ItemType "PluginFusioninventoryLock" -Creds $GlpiCreds -IDs $ExistingLocks.id 667 | } 668 | return $return 669 | } 670 | else { 671 | return "No lock on this field" 672 | } 673 | } 674 | else { return "No field lock on the item"} 675 | } 676 | 677 | Function Set-GlpiFieldLock { 678 | <# 679 | .SYNOPSIS 680 | Apply a set of locks on one or more field of an item, removing all the others. 681 | .DESCRIPTION 682 | Apply a set of locks on one or more field of an item, removing all the others. This requires that FusionInventory plugin is installed. 683 | .PARAMETER ItemType 684 | Type of item to manipulate. 685 | Exemples : Computer, Monitor, Printer, etc. 686 | .PARAMETER Id 687 | ID of item to manipulate. 688 | Exemple : 1600 689 | .PARAMETER Locks 690 | The lock(s) you want to apply. 691 | This is an array. 692 | Exemples : @(serial,comment), @(otherserial), etc. 693 | .PARAMETER Creds 694 | Credetials for the GLPI API. This is an object. 695 | Exemple : $GlpiCreds = @{ 696 | AppURL = "https://[MyGlpiServer]/apirest.php" 697 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 698 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 699 | AuthorizationType = "Basic" or "user_token" 700 | } 701 | .EXAMPLE 702 | Set-GlpiFieldLock -ItemType "printer" -ID 1600 -Locks $(otherserial -Creds $GlpiCreds 703 | .INPUTS 704 | None 705 | .OUTPUTS 706 | None 707 | .NOTES 708 | Author: Jean-Christophe Pirmolin #> 709 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][Array]$Locks,[parameter(Mandatory=$true)][Object]$Creds) 710 | $tablename = "glpi_$($ItemType)s" 711 | $ExistingLocks = Get-GlpiItems -Creds $GlpiCreds -ItemType PluginFusioninventoryLock -Range 0-999999999 | ? {$_.tablename -eq $tablename -and $_.items_id -eq $id} 712 | if ($ExistingLocks) { 713 | $LocksString = "[" + (($Locks.ForEach({ '"' + $_ + '"' })) -join ",") + "]" 714 | $Details = @{ 715 | id=$ExistingLocks.id 716 | tablefields=$LocksString} 717 | $return = Update-GlpiItem -ItemType "PluginFusioninventoryLock" -Details $Details -Creds $GlpiCreds 718 | return $return 719 | } 720 | else { 721 | $LocksString = "[" + (($Locks.ForEach({ '"' + $_ + '"' })) -join ",") + "]" 722 | $Details = @{ 723 | tablename=$tablename 724 | items_id=$ID 725 | tablefields=$LocksString} 726 | $return = Add-GlpiItem -ItemType "PluginFusioninventoryLock" -Details $Details -Creds $GlpiCreds 727 | return $return 728 | } 729 | } 730 | 731 | Function Clear-GlpiFieldLocks { 732 | <# 733 | .SYNOPSIS 734 | Clear all locks on all field of an item. 735 | .DESCRIPTION 736 | Clear all locks on all field of an item. This requires that FusionInventory plugin is installed. 737 | .PARAMETER ItemType 738 | Type of item to manipulate. 739 | Exemples : Computer, Monitor, Printer, etc. 740 | .PARAMETER Id 741 | ID of item to manipulate. 742 | Exemple : 1600 743 | .PARAMETER Creds 744 | Credetials for the GLPI API. This is an object. 745 | Exemple : $GlpiCreds = @{ 746 | AppURL = "https://[MyGlpiServer]/apirest.php" 747 | UserToken = "c8BRf8uJHPDr1AyDTgt2zm95S6EdMAHPXK6qTxlA" 748 | AppToken = "EaNdrm33jKDFVdK8gvFQtOf1XHki2Y4BVtPKssgl" 749 | AuthorizationType = "Basic" or "user_token" 750 | } 751 | .EXAMPLE 752 | Clear-GlpiFieldLocks -creds $GlpiCreds -ItemType "printer" -ID 1600 753 | .INPUTS 754 | None 755 | .OUTPUTS 756 | None 757 | .NOTES 758 | Author: Jean-Christophe Pirmolin #> 759 | param([parameter(Mandatory=$true)][String]$ItemType,[parameter(Mandatory=$true)][Int]$ID,[parameter(Mandatory=$true)][Object]$Creds) 760 | $tablename = "glpi_$($ItemType)s" 761 | $ExistingLocks = Get-GlpiItems -Creds $GlpiCreds -ItemType PluginFusioninventoryLock -Range 0-999999999 | ? {$_.tablename -eq $tablename -and $_.items_id -eq $id} 762 | if ($ExistingLocks) { 763 | $return = Remove-GlpiItems -ItemType "PluginFusioninventoryLock" -IDs $ExistingLocks.id -Creds $GlpiCreds 764 | return $return 765 | } 766 | else {return "no lock on this item's fields" 767 | } 768 | } 769 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PSGLPI 2 | 3 | This Powershell module makes easy the manipulation of the GLPI database thru the Rest API of GLPI. 4 | Search, add, modify, delete items has never be so easy. 5 | Native object and plugin objects are available. 6 | 7 | Use the module integrated help to see how it works. 8 | 9 | Enjoy! :-) 10 | 11 | ## Prerequisites 12 | - Rest API needs to be enabled in GLPI (GLPI Setup -> General -> API). 13 | - An APP token (GLPI Setup -> General -> API -> API Client) 14 | - username-password or a API token (See GLPI user management) 15 | 16 | ## Install the Module 17 | Donwload the module. 18 | Follow Microsoft directions : https://docs.microsoft.com/en-us/powershell/scripting/developer/module/installing-a-powershell-module 19 | 20 | ## Or use it directly from GITHUB 21 | Insert the folowwing lines in your script. It will download the module from GitHub and import it in your Powershell session. 22 | 23 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 24 | Invoke-WebRequest -Uri "https://raw.githubusercontent.com/J-C-P/PSGLPI/master/PSGLPI.psm1" -OutFile "$env:TEMP\PSGLPI.psm1" 25 | Import-Module "$env:TEMP\PSGLPI.psm1" -Force 26 | 27 | 28 | ## Exemples 29 | ### Generate your Basic user token 30 | Use this to generate your Basic token in case you don't want to use the API token associated with your GLPI account. 31 | `Get-GlpiBase64Login -login mysusername -password MySuperComplicatedPassw0rd 32 | bXlzdXNlcm5hbWU6TXlTdXBlckNvbXBsaWNhdGVkUGFzc3cwcmQ=` 33 | 34 | 35 | 36 | 37 | Update in progress... 38 | --------------------------------------------------------------------------------