From 82fe5f297cc185526ed08b62f8bbde4857c5e2d5 Mon Sep 17 00:00:00 2001 From: JJ Fullmer Date: Sat, 14 Sep 2024 15:18:37 -0600 Subject: [PATCH] add publishing chocolatey package to release flow (#22) * Updated docs to be more unified in their appearance where information is purposely duplicated. * Added icon to module files and included staically.io cdn version of icon in manifest. Unified the manifest description with the Readme as the manifest description is used in choco package description. Want to be sure any new user gets the same information now matter how they find the module. * Added chocolatey packaging that includes the psgetmoduleinfo.xml to install the module in an alternative method outside of psget and psresourceget while maintaining compatibility with psget and psresourceget. Also reordered some functions in the build script and made other various improvements to the build process. * Added comment in the set-fogserversettings function help and a warning when running in linux about paste issues that sometimes occur when running set-fogserversettings -interactive. * Updated and unified various docs, added icon packaging with best practicies for chocolatey and psgallery. Updated chocolatey packaging and build functions. Updated docs for set-fogserversettings.md and added psresourceget methods to invoke-modulebuild for test builds to use the same methodology as prod builds * use '-' instead of '*' in markdown formats * verbage fix and add forums link * unify the overview docs * Fix choco template issue of typo of folder name sources vs files * Shortened the manifest and nuspec description * Update files section of nuspec to properly include the module files * Added gpu properties to get-foginventory for upcoming add of gpu info to fog inventory records and fixed missing functions in in get-winbcdpxeid * Added nuspec and psgetmodule info templates * Updates to release note formatting, manifest description format, and build script improvements * Updated Send-FogImage with params for 1.6 and added switch options and autocomplete for available fog images. Also added a basic Set-FogHostImage function, needs to be further flushes out but the basic functionality is there. * Filter out rdp display driver when getting host inventory details and append video memory in GB to each adapter name * revert change of appending gpu ram as it doesn't work for all gpus equally * Update tag-and-release.yml - Comment out the choco community publish, will continue to have the choco nupkg attached to the release until the first version is approved. --- .github/workflows/tag-and-release.yml | 12 +- .gitignore | 3 +- FogApi/FogApi.psd1 | 119 ++--- FogApi/Public/Get-FogInventory.ps1 | 13 +- FogApi/Public/Get-WinBcdPxeID.ps1 | 66 ++- FogApi/Public/Send-FogImage.ps1 | 140 ++++- FogApi/Public/Set-FogHostImage.ps1 | 31 ++ FogApi/Public/Set-FogServerSettings.ps1 | 16 +- FogApi/Public/Test-StringNotNullOrEmpty.ps1 | 64 +++ README.md | 173 ++++--- build-choco.ps1 | 97 +++- build.ps1 | 79 +-- chocoTemplate/PSGetModule/FogApi.nuspec | 38 ++ chocoTemplate/PSGetModule/README.MD | 9 + .../PSGetModule/tools/chocolateyInstall.ps1 | 33 +- .../tools/files/PSGetModuleInfo-ps5.xml | 108 ++++ .../tools/files/PSGetModuleInfo-ps7.xml | 108 ++++ docs/ReleaseNotes.md | 73 ++- docs/about_FogApi.md | 205 +++++--- docs/commands/Get-FogInventory.md | 2 +- docs/commands/Get-WinBcdPxeId.md | 2 +- docs/commands/Send-FogImage.md | 92 +++- docs/commands/Set-FogHostImage.md | 89 ++++ docs/commands/Set-FogServerSettings.md | 1 + docs/commands/Test-StringNotNullOrEmpty.md | 89 ++++ docs/commands/index.md | 4 + docs/en-us/FogApi-help.xml | 490 +++++++++++++++++- docs/en-us/about_FogApi.help.txt | 241 +++++---- docs/index.md | 20 +- invoke-modulebuild.ps1 | 12 +- 30 files changed, 2024 insertions(+), 405 deletions(-) create mode 100644 FogApi/Public/Set-FogHostImage.ps1 create mode 100644 FogApi/Public/Test-StringNotNullOrEmpty.ps1 create mode 100644 chocoTemplate/PSGetModule/FogApi.nuspec create mode 100644 chocoTemplate/PSGetModule/README.MD create mode 100644 chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps5.xml create mode 100644 chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps7.xml create mode 100644 docs/commands/Set-FogHostImage.md create mode 100644 docs/commands/Test-StringNotNullOrEmpty.md diff --git a/.github/workflows/tag-and-release.yml b/.github/workflows/tag-and-release.yml index 8dc1508..bfb73de 100644 --- a/.github/workflows/tag-and-release.yml +++ b/.github/workflows/tag-and-release.yml @@ -93,18 +93,18 @@ jobs: gh release upload $version ".\_module_build\FogApi.$version.psgallery.nupkg" gh release upload $version ".\_module_build\FogApi.$version.BuiltModule.zip" - "building choco package..." | out-host; - .\build-choco.ps1; + "building choco package from local build and temp psresource repo..." | out-host; + .\build-choco.ps1 -uselocal; "adding choco package to release" | out-host; copy-item ".\FogApi.$version.nupkg" ".\FogApi.$version.chocolatey.nupkg" gh release upload $version ".\FogApi.$version.chocolatey.nupkg" remove-item ".\FogApi.$version.chocolatey.nupkg" -force -recurse -ea 0; - "publishing choco package..." | out-host; - choco apikey add -s "https://push.chocolatey.org/" -k="$env:ChocoKey" - choco apikey add -s "https://community.chocolatey.org/api/v2/" -k="$env:ChocoKey" - choco push "FogApi.$version.nupkg" --source https://push.chocolatey.org/ + #"publishing choco package..." | out-host; + #choco apikey add -s "https://push.chocolatey.org/" -k="$env:ChocoKey" + #choco apikey add -s "https://community.chocolatey.org/api/v2/" -k="$env:ChocoKey" + #choco push "FogApi.$version.nupkg" --source https://push.chocolatey.org/ diff --git a/.gitignore b/.gitignore index f056e47..8f18bb9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ _build _module_build .lastprereqrun -.vscode \ No newline at end of file +.vscode +.nupkg \ No newline at end of file diff --git a/FogApi/FogApi.psd1 b/FogApi/FogApi.psd1 index 34be0cf..1b70c73 100644 --- a/FogApi/FogApi.psd1 +++ b/FogApi/FogApi.psd1 @@ -3,7 +3,7 @@ # # Generated by: JJ Fullmer # -# Generated on: 9/4/2024 +# Generated on: 9/11/2024 # @{ @@ -12,7 +12,7 @@ RootModule = 'FogApi.psm1' # Version number of this module. -ModuleVersion = '2409.9.4' +ModuleVersion = '2409.9.15' # Supported PSEditions # CompatiblePSEditions = @() @@ -30,64 +30,63 @@ CompanyName = 'FOG Project' Copyright = '2018-2024' # Description of the functionality provided by this module -Description = 'This module is used to easily run Fog API commands on your fogserver from a powershell console or script. - This essentially gives you a crossplatform commandline interface for fog tasks and makes many things easier to automate. - You can install FOG Project from https://github.com/FogProject/fogproject +Description = ' +# FOG Api Powershell Module - The documentation is hosted on readthedocs at https://fogapi.readthedocs.io/en/latest/ +This is a powershell module to simplify the use of the Fog Project API. +This module is used to easily run Fog API commands on your fogserver from a powershell console or script. +FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to +perform almost any operation you can do in the GUI of Fog and provides you with the ability to extend things further. +It can be used to create more automation or to simply have a command line method of controlling fog operations. +This essentially gives you a crossplatform commandline interface for fog tasks and makes many things easier to automate. - To install this module you need at least powershell v3, was created with 5.1 and intended to be cross platform compatible with powershell v6 - To Install this module follow these steps - - * Easiest method: Install from PSGallery https://www.powershellgallery.com/packages/FogApi `Install-Module -name fogApi` or `Install-PSResource -Name FogApi -TrustRepository -repository PSGallery` +Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/ - * Install with chocolatey (will install the module by copying the built version to the powershell core and windows powershell paths, will remove any existing versions) - `choco upgrade fogapi -y` +For more information about FOG see - * Manual Method: - * download the zip of this repo and extract it and use Import-Module on the extracted path +- https://FOGProject.org +- https://docs.fogproject.org +- https://github.com/FOGProject +- https://github.com/FOGProject/fogproject +- https://forums.fogproject.org - The module is now installed. - You can use Set-fogserverSettings to set your fogserver hostname and api keys. - The first time you try to run a command the settings.json file will automatically open - in notepad on windows, nano on linux, or TextEdit on Mac - You can also open the settings.json file and edit it manually before running your first command. - The default settings are explanations of where to find the proper settings since json can''''t have comments +# Versioning - Once the settings are set you can have a jolly good time utilzing the fog documentation - found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters +The versioning of this module follows this pattern - i.e. +`{Year|Month}.{Major Version}.{Revision #}` - Get-FogObject has a type param that validates to object, objectactivetasktype, and search as those are the options given in the documentation. - Each of those types validates (which means autocompletion) to the core types listed in the documentation. - So if you typed in Get-FogObject -Type object -Object h and then started hitting tab, it would loop through the possible core objects you can get from the api that start with ''''h'''' such as history, host, etc. +## Year/Month - Unless you filter a get with a json body it will return all the results into a powershell object. That object is easy to work with to create other commands. Note: Full Pipeline support will come at a later time - i.e. +This versioning shows you first the Year and month this version of the module was published, giving you an idea of when it was last updated. +i.e. 2208 would be august 2022. - hosts = Get-FogObject -Type Object -CoreObject Host # calls GET on {your-fog-server}/fog/host to list all hosts - Now you can search all your hosts for the one or ones you''''re looking for with powershell - maybe you want to find all the hosts with ''''IT'''' in the name (note ''''?'''' is an alias for Where-Object) - ITHosts = hosts.hosts | ? name -match ''''IT''''; +## Major - Now maybe you want to change the image all of these computers use to one named ''''IT-Image'''' - You can edit the object in powershell with a foreach-object (''''%'''' is an alias for foreach-object) - updatedITHosts = ITHosts | % { _.imagename = ''''IT-image''''} +The Major version follows the typical major versioning where any major changes will increment this version number, especially possible breaking changes or structural changes, etc. - Then you need to convert that object to json and pass each object into one api call at a time. Which sounds complicated, but it''''s not, it''''s as easy as - - updateITHosts | % { - jsonData = _ | ConvertTo-Json; - Update-FogObject -Type object -CoreObject host -objectID _.id -jsonData jsonData; - #successful result of updated objects properties - #or any error messages will output to screen for each object - } - - This is just one small example of the limitless things you can do with the api and powershell objects. +## Minor/Revision - see also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 - ' +Any time I publish a new version that isn''t a major change I''ll increment the revision. This may also be incremented for each build test and increment by more than one for each published version + +# Usage + +You can use Set-fogserverSettings to set your fogserver hostname and api keys. +The first time you try to run a command the settings.json file will automatically open +in notepad on windows, nano on linux, or TextEdit on Mac +You can also open the settings.json file and edit it manually before running your first command. +The default settings are explanations of where to find the proper settings since json can''''t have comments + +Once the settings are set you can have a jolly good time utilzing the fog documentation +found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters + +See https://github.com/darksidemilk/FogApi/blob/master/README.md for more examples and see https://fogapi.readthedocs.io/en/latest/commands/ for a list of all the commands + +# Additional info + +See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 +Full change log available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/ +' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '3.0' @@ -142,10 +141,11 @@ FunctionsToExport = 'Add-FogHostMac', 'Add-FogResultData', 'Approve-FogPendingMa 'New-FogObject', 'Receive-FogImage', 'Remove-FogObject', 'Remove-UsbMac', 'Repair-FogSnapinAssociations', 'Reset-HostEncryption', 'Resolve-HostID', 'Send-FogImage', - 'Send-FogWolTask', 'Set-FogInventory', 'Set-FogServerSettings', - 'Set-FogServerSettingsFileSecurity', 'Set-FogSetting', - 'Set-FogSnapins', 'Set-WinToBootToPxe', 'Start-FogSnapin', - 'Start-FogSnapins', 'Test-FogVerAbove1dot6', 'Update-FogObject' + 'Send-FogWolTask', 'Set-FogHostImage', 'Set-FogInventory', + 'Set-FogServerSettings', 'Set-FogServerSettingsFileSecurity', + 'Set-FogSetting', 'Set-FogSnapins', 'Set-WinToBootToPxe', + 'Start-FogSnapin', 'Start-FogSnapins', 'Test-FogVerAbove1dot6', + 'Test-StringNotNullOrEmpty', 'Update-FogObject' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() @@ -173,13 +173,10 @@ AliasesToExport = 'Add-FogHost', 'Add-FogObject', 'Add-FogSnapins', 'Capture-Fog # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ - #Title of this module - Title = 'FogApi' - PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. - Tags = 'fog','fogapi','imaging','provisioning','fogproject' + Tags = 'fog', 'fogapi', 'imaging', 'provisioning', 'fogproject' # A URL to the license for this module. LicenseUri = 'https://github.com/darksidemilk/FogApi/blob/master/LICENSE' @@ -188,15 +185,15 @@ PrivateData = @{ ProjectUri = 'https://github.com/darksidemilk/FogApi' # A URL to an icon representing this module. - IconUri = 'https://fogapi.readthedocs.io/en/latest/assets/favicon.png' + IconUri = 'https://cdn.statically.io/gh/darksidemilk/FogApi/0ed5e87e/FogApi/icons/favicon.png' # ReleaseNotes of this module ReleaseNotes = ' -# 2409.9.4 +# 2409.9.15 - "Adding Chocolatey package and updates to auto adding various assets to each release. Also updated some manifest things. No Code changes, really just a maintenance release" + revert change of appending gpu ram -' +Full change log history available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/' # Prerelease string of this module # Prerelease = '' @@ -209,6 +206,10 @@ PrivateData = @{ } # End of PSData hashtable + + # Title + Title = 'FogApi' + } # End of PrivateData hashtable # HelpInfo URI of this module diff --git a/FogApi/Public/Get-FogInventory.ps1 b/FogApi/Public/Get-FogInventory.ps1 index f79b7ce..82621ed 100644 --- a/FogApi/Public/Get-FogInventory.ps1 +++ b/FogApi/Public/Get-FogInventory.ps1 @@ -10,7 +10,7 @@ function Get-FogInventory { .PARAMETER hostObj the host to get the model of the inventory object from This is used for the inventory structure of the object - It defaults to the current host + It defx`aults to the current host .PARAMETER fromFog Switch param to simply return the currently set inventory of the fog host @@ -58,6 +58,7 @@ function Get-FogInventory { $cpu = Get-CimInstance -ClassName Win32_processor; $bios = Get-CimInstance -ClassName Win32_Bios; $hdd = Get-CimInstance -ClassName Win32_DiskDrive | Where-Object DeviceID -match '0'; #get just drive 0 in case of multiple drives + $gpu = Get-CimInstance -ClassName Win32_VideoController | Where-Object name -notmatch 'Microsoft Remote Display Adapter'; #filter out rdp display adapter $baseBoard = Get-CimInstance -ClassName Win32_BaseBoard; $case = Get-CimInstance -ClassName Win32_SystemEnclosure; $info = Get-ComputerInfo; @@ -98,6 +99,16 @@ function Get-FogInventory { $hostObj.inventory.caseserial = $case.SerialNumber; $hostObj.inventory.caseasset = $case.SMBIOSAssetTag; $hostObj.inventory.memory = "$([MATH]::Round($(($comp.TotalPhysicalMemory) / 1GB),2)) GiB"; + if ($null -ne $hostObj.inventory.gpuvendors) { + $hostObj.inventory.gpuvendors = $gpu.AdapterCompatibility; + } + if ($null -ne $hostObj.inventory.gpuproducts) { + $hostObj.inventory.gpuproducts = $gpu.VideoProcessor + #below is an attempt to append the video memoery of each gpu, but it gave wrong values on some cards + <# $hostObj.inventory.gpuproducts = $gpu | Foreach-Object { + "$($_.VideoProcessor) - ($([math]::round($_.AdapterRAM/1GB))GB)"; + } #> + } $jsonData = $hostObj.inventory | ConvertTo-Json; return $jsonData; } diff --git a/FogApi/Public/Get-WinBcdPxeID.ps1 b/FogApi/Public/Get-WinBcdPxeID.ps1 index 93ebfd6..167a42e 100644 --- a/FogApi/Public/Get-WinBcdPxeID.ps1 +++ b/FogApi/Public/Get-WinBcdPxeID.ps1 @@ -14,7 +14,7 @@ function Get-WinBcdPxeId { switch param to not return the main bootmgr entry if it is returned .EXAMPLE - Get-BcdPxeBootID + Get-WinBcdPxeId Will return the guid of the native pxe boot option if one is found. @@ -29,33 +29,55 @@ function Get-WinBcdPxeId { if ($IsLinux -or $IsMacOS) { Write-Warning "This is currently only implemented for windows" } else { - if (!(Test-String $searchString)) { - $searchString = "IPV4" - $searchString2 = "Network" - $searchString3 = "LAN" - $searchString4 = (Get-NetAdapter -ea 0 | Where-Object status -eq up | Where-Object name -match 'Ethernet' | Select-Object -First 1) + if (!(Test-StringNotNullOrEmpty $searchString)) { + [object]$searchString = (Get-NetAdapter -ea 0 | Where-Object status -eq up | Where-Object name -match 'Ethernet')[0] + $searchString2 = "IPV4" + $searchString3 = "Network" + $searchString4 = "LAN" $searchString5 = "PXE" } - Write-Verbose "Searching bcd firmware boot options for description that matches $searchString" - $search = (bcdedit /enum firmware | select-string $searchString -Context 3,0 -ea 0); - if ($null -ne $searchString2) { - #search for PXE string that doesn't match ipxe that might match 'Network' (or 'EFI Network' on a surface go 2) + # $searchString; + # pause; + if ((Test-StringNotNullOrEmpty "$($searchString.InterfaceDescription)" -ea 0)) { + #search for PXE string that doesn't match ipxe but does match the interface description of the first ethernet adapter that is currently up + $searchString = $searchString.InterfaceDescription; + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString" + $search = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString -Context 3,0 -SimpleMatch -ea 0); + Write-Verbose "Result of search: $($search | out-string)" + } else { + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString" + $search = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString -Context 3,0 -ea 0); + Write-Verbose "Result of search: $($search | out-string)" + } + if (($null -eq $search) -and ($null -ne $searchString2)) { + + #search for PXE string that doesn't match ipxe that might match 'ipv4' + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString2" $search2 = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString2 -Context 3,0 -ea 0); + Write-Verbose "Result of search: $($search2 | out-string)" } - if (($null -eq $search2) -and ($null -ne $searchString3)) { - #search for PXE string that doesn't match ipxe but does match 'LAN' + if (($null -eq $search) -and ($null -eq $search2) -and ($null -ne $searchString3)) { + #search for PXE string that doesn't match ipxe that might match 'Network' (or 'EFI Network' on a surface go 2) + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString3" $search3 = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString3 -Context 3,0 -ea 0); + Write-Verbose "Result of search: $($search3 | out-string)" } - if (($null -eq $search3) -and ($null -ne $searchString4)) { - #search for PXE string that doesn't match ipxe but does match the interface description of the first ethernet adapter that is currently up - if ($null -ne $searchString4.InterfaceDescription) { - $searchString4 = $searchString4.InterfaceDescription - $search4 = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString4 -Context 3,0 -ea 0); - } + if (($null -eq $search) -and ($null -eq $search2) -and ($null -eq $search3) -and ($null -ne $searchString4)) { + #search for PXE string that doesn't match ipxe but does match 'LAN' + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString4" + $search4 = (bcdedit /enum firmware | select-string $searchString4 -Context 3,0 -ea 0); + Write-Verbose "Result of search: $($search4 | out-string)" + + # if ($null -ne $searchString4.InterfaceDescription) { + # $searchString4 = $searchString4.InterfaceDescription + # $search4 = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString4 -Context 3,0 -ea 0); + # } } - if (($null -eq $search4) -and ($null -ne $searchString5)) { + if (($null -eq $search) -and ($null -eq $search2) -and ($null -eq $search3) -and ($null -eq $search4) -and ($null -ne $searchString5)) { #search for PXE string that doesn't match ipxe but does match 'PXE' + Write-Verbose "Searching bcd firmware boot options for description that matches $searchString5" $search5 = (bcdedit /enum firmware | Where-Object { $_ -notmatch 'ipxe'} | select-string $searchString5 -Context 3,0 -ea 0); + Write-Verbose "Result of search: $($search5 | out-string)" } if ($null -ne $search) { @@ -63,30 +85,35 @@ function Get-WinBcdPxeId { $pxeID = ($search.Context.PreContext | Where-Object { $_ -match "identifier"}) if ($null -ne $pxeID) { $pxeID = $pxeID.trimstart("identifier").trim() + $vbOut = $search; } } elseif($null -ne $search2) { Write-verbose "Found $($search2 | Out-String) returning just identifier" $pxeID = ($search2.Context.PreContext | Where-Object { $_ -match "identifier"}) if ($null -ne $pxeID) { $pxeID = $pxeID.trimstart("identifier").trim() + $vbOut = $search2; } } elseif($null -ne $search3) { Write-verbose "Found $($search3 | Out-String) returning just identifier" $pxeID = ($search3.Context.PreContext | Where-Object { $_ -match "identifier"}) if ($null -ne $pxeID) { $pxeID = $pxeID.trimstart("identifier").trim() + $vbOut = $search3; } } elseif($null -ne $search4) { Write-verbose "Found $($search4 | Out-String) returning just identifier" $pxeID = ($search4.Context.PreContext | Where-Object { $_ -match "identifier"}) if ($null -ne $pxeID) { $pxeID = $pxeID.trimstart("identifier").trim() + $vbOut = $search4; } } elseif($null -ne $search5) { Write-verbose "Found $($search5 | Out-String) returning just identifier" $pxeID = ($search5.Context.PreContext | Where-Object { $_ -match "identifier"}) if ($null -ne $pxeID) { $pxeID = $pxeID.trimstart("identifier").trim() + $vbOut = $search5; } } else { Write-Warning "no pxe boot options found in bcdedit matching $searchString!" @@ -105,6 +132,7 @@ function Get-WinBcdPxeId { $pxeID = $null } } + "pxeID found is $pxeID full context is $($vbOut | Out-String)" | Out-Host; return $pxeID } diff --git a/FogApi/Public/Send-FogImage.ps1 b/FogApi/Public/Send-FogImage.ps1 index bb4b4ca..f50181e 100644 --- a/FogApi/Public/Send-FogImage.ps1 +++ b/FogApi/Public/Send-FogImage.ps1 @@ -14,6 +14,23 @@ function Send-FogImage { .PARAMETER fogHost fogHost object (get-foghost) that can be brought in from pipeline + + .PARAMETER debugMode + Switch param to mark the task as a debug task + + .PARAMETER imageName + The name of the image to deploy, uses currently set image if not specified + Tab completion of your fog server's image names if you're on pwsh 7+ + + .PARAMETER NoWol + Switch param to not use wake on lan in the task, default is to use wake on lan + + .PARAMETER shutdown + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + .PARAMETER NoSnapins + Switch param for when running a scheduled task, you can choose to set deploysnapins to false so the + assigned snapins aren't auto scheduled too. Only works in FOG 1.6+ .EXAMPLE Deploy-FogImage -hostID "1234" @@ -46,7 +63,43 @@ function Send-FogImage { $fogHost, [Parameter(ParameterSetName='schedule')] [Parameter(ParameterSetName='schedule-byhost')] - [datetime]$StartAtTime + [datetime]$StartAtTime, + [Parameter(ParameterSetName='now')] + [Parameter(ParameterSetName='now-byhost')] + [Parameter(ParameterSetName='schedule')] + [Parameter(ParameterSetName='schedule-byhost')] + [ArgumentCompleter({ + param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParams) + + $r = Get-FogImages; + + if ($WordToComplete) { + $r.Name.Where{ $_ -match "^$WordToComplete" } + } + else { + $r.Name + } + + })] + [string]$imageName, + [Parameter(ParameterSetName='now')] + [Parameter(ParameterSetName='now-byhost')] + [Parameter(ParameterSetName='schedule')] + [Parameter(ParameterSetName='schedule-byhost')] + [switch]$debugMode, + [Parameter(ParameterSetName='now')] + [Parameter(ParameterSetName='now-byhost')] + [Parameter(ParameterSetName='schedule')] + [Parameter(ParameterSetName='schedule-byhost')] + [switch]$NoWol, + [Parameter(ParameterSetName='now')] + [Parameter(ParameterSetName='now-byhost')] + [Parameter(ParameterSetName='schedule')] + [Parameter(ParameterSetName='schedule-byhost')] + [switch]$shutdown, + [Parameter(ParameterSetName='schedule')] + [Parameter(ParameterSetName='schedule-byhost')] + [switch]$NoSnapins ) @@ -62,19 +115,93 @@ function Send-FogImage { $fogHost = Get-FogHost -hostID $hostId; } # $fogHost = Get-FogHost -hostID $hostId; + if (Test-FogVerAbove1dot6) { + $debugstr = "$($debugMode.IsPresent)" + } else { + if ($debugMode) { + $debugStr = "0" + } else { + $debugStr = "1" + } + } + if ($Nowol) { + $wolstr = "0" + } else { + $wolStr = "1" + } + if ($shutdown) { + $shutdownStr = "1" + } else { + $shutdownStr = "0" + } + if ($NoSnapins) { + $deploySnapins = $false; + } else { + $deploySnapins = $true; + } + + $currentImage = $fogHost.imageName; $fogImages = Get-FogImages; + if ($null -ne $imageName) { + if ($currentImage -eq $imageName) { + Write-Verbose "Image $imageName already set on host" + } else { + "Host $($foghost.name) has image $currentImage set, changing image to $imageName!" | out-host; + $fogHost = Set-FogImage -hostId $fogHost.id -fogImage ($fogImages | Where-Object name -eq $imageName) + $currentImage = $fogHost.imageName; + } + } $fogImage = ($fogImages | Where-Object name -eq $currentImage) "Creating Deploy Task for fog host of id $($hostID) named $($fogHost.name)" | Out-Host; "Will deploy the assigned image $($fogImage.name) - $($fogImage.id) which will install the os $($fogImage.osname)" | Out-host; if ($PSCmdlet.ParameterSetName -eq 'now') { "No Time was specified, queuing the task to start now" | out-host; - $jsonData = "{`"taskTypeID`": `"1`", `"shutdown`":`"0`",`"other2`":`"0`",`"other4`":`"1`",`"isActive`":`"1`" }"; + if (Test-FogVerAbove1dot6) { + $jsonData = @" + { + "taskName":"Deploy Task for $($fogHost.name) id $($foghost.id)", + "taskTypeID":"1", + "shutdown":"$shutDownStr", + "debug":"$debugStr", + "wol":"$wolStr", + "isActive":"1" + } +"@ + } else { + $jsonData = @" + { + "taskTypeID":"1", + "shutdown":"$shutDownStr", + "other2":"$debugStr", + "other4":"$wolStr", + "isActive":"1" + } +"@ + } } else { "Start time of $($StartAtTime) specified, scheduling the task to start at that time" | out-host; $scheduleTime = Get-FogSecsSinceEpoch -scheduleDate $StartAtTime $runTime = get-date $StartAtTime -Format "yyyy-M-d HH:MM" - $jsonData = @" + if (Test-FogVerAbove1dot6) { + $jsonData = @" + { + "taskName":"Deploy Task", + "type":"S", + "taskTypeID":"1", + "runTime":"$runTime", + "scheduleTime":"$scheduleTime", + "isGroupTask":"0", + "hostID":"$($hostId)", + "shutdown":"$shutdownStr", + "debug":"$debugStr", + "wol":"$wolStr", + "isActive":"1", + "deploySnapins":"$deploySnapins" + } +"@ + } else { + $jsonData = @" { "name":"Deploy Task", "type":"S", @@ -83,12 +210,13 @@ function Send-FogImage { "scheduleTime":"$scheduleTime", "isGroupTask":"0", "hostID":"$($hostId)", - "shutdown":"0", - "other2":"0", - "other4":"1", + "shutdown":"$shutdownStr", + "other2":"$debugStr", + "other4":"$wolStr", "isActive":"1" } "@ + } } return New-FogObject -type objecttasktype -coreTaskObject host -jsonData $jsonData -IDofObject "$hostId"; } diff --git a/FogApi/Public/Set-FogHostImage.ps1 b/FogApi/Public/Set-FogHostImage.ps1 new file mode 100644 index 0000000..6c52820 --- /dev/null +++ b/FogApi/Public/Set-FogHostImage.ps1 @@ -0,0 +1,31 @@ +function Set-FogHostImage { + <# + .SYNOPSIS + Function to set a given image object to a host by its id + + .DESCRIPTION + Function to set a given image object to a host by its id + Will be expanded for better usability in the future + + .PARAMETER hostID + the host id to set an image on + + .PARAMETER fogImage + the image object gotten from get-fogimages + + #> + [CmdletBinding()] + param ( + [parameter(Mandatory=$true)] + $hostID, + [parameter(ValueFromPipeline=$true)] + $fogImage + ) + + process { + $jsonImageData = $fogimage | select-object @{N="imageID";E={$_.id}} | convertto-json + $updatedHost = Set-FogObject -type object -coreObject host -IDofObject "$($hostid)" -jsonData $jsonImageData + return $updatedHost; + } + +} \ No newline at end of file diff --git a/FogApi/Public/Set-FogServerSettings.ps1 b/FogApi/Public/Set-FogServerSettings.ps1 index 6515594..5be8fa2 100644 --- a/FogApi/Public/Set-FogServerSettings.ps1 +++ b/FogApi/Public/Set-FogServerSettings.ps1 @@ -22,6 +22,7 @@ You can enforce the use of http or https in api calls by specifying the serverna .PARAMETER interactive switch to make setting these an interactive process, if you set no values this is the default +Warning, this can have issues in linux, especially when working in a remote shell, the paste into read-host can behave odd. .EXAMPLE Set-FogServerSettings -fogapiToken "12345abcdefg" -fogUserToken "abcdefg12345" -fogServer "fog" @@ -55,6 +56,9 @@ This will set the current users FogApi/settings.json file to have the given api fogServer = "your fog server hostname or ip address to be used for created the url used in api calls default is fog-server or fogServer, to enforce http/https input this as https://fogserver or http://fogserver, you can also use Enable-FogApiHTTPS later"; } if($interactive -or $PSCmdlet.ParameterSetName -eq 'prompt') { + if ($IsLinux) { + Write-Warning "If you have issues with pasting your apikeys into these prompts (issue with read-host in some linux instances of pwsh), try again without -interactive and paste into each param. i.e. `Set-FogServerSettings -fogapiToken '12345abcdefg' -fogUserToken 'abcdefg12345' -fogServer 'fog'" + } ($serverSettings.psobject.properties).Name | ForEach-Object { $var = (Get-Variable -Name $_); if ($null -eq $var.Value -OR $var.Value -eq "") { @@ -106,13 +110,21 @@ This will set the current users FogApi/settings.json file to have the given api Write-Host -BackgroundColor Yellow -ForegroundColor Red -Object "a fog setting is either null or still set to its default help text, opening the settings file for you to set the settings" Write-Host -BackgroundColor Yellow -ForegroundColor Red -Object "This script will close after opening settings in notepad, please re-run command after updating settings file"; if ($isLinux) { - $editor = 'nano'; + if (Get-Command nano) { + $editor = 'nano'; + } else { + $editor = 'vi'; + } } elseif($IsMacOS) { $editor = 'TextEdit'; } else { - $editor = 'notepad.exe'; + if ((Get-Command 'code.exe')) { + $editor = 'code.exe'; + } else { + $editor = 'notepad.exe'; + } } Start-Process -FilePath $editor -ArgumentList "$SettingsFile" -NoNewWindow -PassThru; return; diff --git a/FogApi/Public/Test-StringNotNullOrEmpty.ps1 b/FogApi/Public/Test-StringNotNullOrEmpty.ps1 new file mode 100644 index 0000000..dbb4e23 --- /dev/null +++ b/FogApi/Public/Test-StringNotNullOrEmpty.ps1 @@ -0,0 +1,64 @@ +function Test-StringNotNullOrEmpty { + <# + .SYNOPSIS + Returns true if passed in object is a string that is not null, empty, or whitespace + + .DESCRIPTION + Uses built in string functions to test if a given string is null, empty or whitespace + if it is not any of these things and has valid content, this returns true otherwise false + + .PARAMETER str + String to test + + .EXAMPLE + Test-StringNotNullOrEmpty "An example" + + Will return true as it is a valid string with content + + .EXAMPLE + $s = ""; Test-StringNotNullOrEmpty $s; + + Will return false as this is an empty string. + + .EXAMPLE + $str = " "; $str | Test-StringNotNullOrEmpty + + Will return false as this string is just whitespace + + + .NOTES + Meant to simplify input validation tests as test-string $param or $value | test-string is easier to type in an if statement than + doing [string]::isnullorempty($str) along with [string]::isnullorwhitespace($str) + + #> + [CmdletBinding()] + param ( + [parameter(ValueFromPipeline=$true)] + $str + ) + + + process { + $valid = $false; + if ($null -eq $str) { + $isString = $false; + } elseif (($str.gettype().name) -eq "String") { + $isString = $true; + } else { + $isString = $false; + } + if ($isString) { + $empty = [string]::IsNullOrEmpty($str) + $whitespace = [string]::IsNullOrWhiteSpace($str) + } else { + $valid = $false; + } + + if (!$empty -and !$whitespace -and $isString) { + $valid = $True; + } + return $valid; + + } + +} \ No newline at end of file diff --git a/README.md b/README.md index 1f050e9..453e849 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,22 @@ [![Test Build](https://github.com/darksidemilk/FogApi/actions/workflows/build-test.yml/badge.svg?branch=master)](https://github.com/darksidemilk/FogApi/actions/workflows/build-test.yml) +[![Tag, Release, and Publish to PSGallery and Chocolatey Community Repo](https://github.com/darksidemilk/FogApi/actions/workflows/tag-and-release.yml/badge.svg)](https://github.com/darksidemilk/FogApi/actions/workflows/tag-and-release.yml) + This is a powershell module to make using the Fog Project API even easier. -FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to perform almost any operation. It can be used to create more automation or to simply have a command line method of controlling fog operations. +FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to perform almost any operation you can do in the GUI of Fog and provides you with the ability to extend things further. +It can be used to create more automation or to simply have a command line method of controlling fog operations. + +Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/ + +For more information about FOG see + +- https://FOGProject.org +- https://docs.fogproject.org +- https://github.com/FOGProject +- https://github.com/FOGProject/fogproject +- https://forums.fogproject.org -Docs can be found at https://fogapi.readthedocs.io/en/latest/ ## Notes about its new home and future structuring @@ -32,95 +44,140 @@ Any time I publish a new version that isn't a major change I'll increment the re # Installation -All completed/tested/stable releases of this module will be published to powershell gallery. I don't currently have any plans to use github releases +The module can be installed via PowershellGet, PSResourceGet, Chocolatey, or Manually -## Requirements +## Installation Methods + +To install this module you need at least powershell v3, it was originally created with 5.1, +but now for BEST EXPERIENCE use Powershell Core 7+ to be able to use tab completion when running Fog 1.6 -To install this module you need at least powershell v3, was created with 5.1 and intended to be cross platform compatible with powershell v6 and v7 +To Install this module follow these steps -To Install this module follow these steps... +### Install from PSgallery -## Install From PSGallery +- Easiest method: Install from PSGallery https://www.powershellgallery.com/packages/FogApi with powershellget or PSResourceGet + - `Install-Module -name FogApi -Scope AllUsers` + - `Install-PSResource -Name FogApi -scope -Scope AllUsers` +- updating is then as easy as + - `Update-Module -name FogApi` + - `Update-PSResource -Name FogApi` -* Easiest method, cross platform: Install from PSGallery https://www.powershellgallery.com/packages/FogApi via a powershell console with the command `Install-Module -name fogApi` -* You can also use PSResourceGet `Install-PSRe +### Install with Chocolatey -## Install via Chocolatey +If you have chocolatey package manager, you can use the published package that manually installs the module the same way the PSGet managers do. +https://community.chocolatey.org/packages/FogApi +See https://chocolatey.org for more information on chocolatey package manager -* https://community.chocolatey.org/packages/FogApi -* You can install the module as a chocolatey package with `choco upgrade FogApi -y` - * This will install it in the Windows PowerShell and Powershell Core module paths complete with the hidden psgetxml file that makes it so the module is registered as installed when using commands like `Get-InstalledModule` +- Install with chocolatey (will install the module by copying the built version to the powershell core and windows powershell paths, will remove any existing versions) + - `choco install fogapi -y` +- Upgrading is as easy as (note that you can also use this same command for a new install) + - `choco upgrade fogapi -y` ## Manual Installation ### Use assets from the release -* Use Chocolatey, PackageManagement, Nuget or what have you to install the *chocolatey.nupkg or *.psgallery.nupkg file from the release assets -* Extract the *builtModule.zip from the release and run `import-module` on the resulting folder for a portable installation. You can also extract to the paths outlined below in the manual build install steps for a more system wide install +- Use Chocolatey, PackageManagement, Nuget or what have you to install the *chocolatey.nupkg or *.psgallery.nupkg file from the release assets +- Extract the *builtModule.zip from the release and run `import-module` on the resulting folder for a portable installation. You can also extract to the paths outlined below in the manual build install steps for a more system wide install ### Manually build the module -* Manual Method: -* download the zip of this repo and extract it (or use git clone) - * Or clone the repo using your favorite git tool, you just need the FogApi Folder this readme is in -* Run the build.ps1 script -* Copy the built module folder (.\_module_build) into... - * For Windows Powershell v3-v5.1 - * C:\Program Files\WindowsPowershell\Modules - * For Windows Powershell v6+ - * C:\Program Files\PowerShell\6-preview\Modules - * 6-Preview may need to be replaced with whatever current version you have installed - * For Linux Powershell v6+ - * /opt/microsoft/powershell/6.1.0-preview.2/Modules - * 6.1.0-preview.2 may need to be replaced with whatever current version you have installed - * For Mac Powershell v6+ (untested) - * /usr/local/microsoft/powershell/6.x/Modules - * 6.x should be replaced with whatever most current version you are using - * I haven't tested this on a mac, the module folder may be somewhere else - this is based on where it is in other powershell 6 installs -* Open a powershell command prompt (I always run as admin, unsure if it's required) -* Run `Import-Module FogApi` +- Manual Method: +- download the zip of this repo and extract it (or use git clone) + - Or clone the repo using your favorite git tool, you just need the FogApi Folder this readme is in +- Run the build.ps1 script +- Copy the built module folder (.\_module_build) into... + - For Windows Powershell v3-v5.1 + - C:\Program Files\WindowsPowershell\Modules\FogApi + - For Powershell Core (pwsh) on Windows v7+ + - C:\Program Files\PowerShell\Modules\FogApi + - For Linux Powershell Core (pwsh) v7+ + - /usr/local/share/powershell/Modules/FogApi + - For Mac Powershell Core (pwsh) v7+ (untested) + - /usr/local/share/powershell/Modules/FogApi + - I haven't tested this on a mac, the module folder may be somewhere else + this is based on where it is in other powershell core installs +- Open powershell (as admin recommended) +- Run `Import-Module FogApi` The module is now installed. # Using The Module -The first time you try to run a command the settings.json file will automatically open +You can use `Set-FogServerSettings` to set your fogserver hostname and api keys. + +The first time you try to run a command the settings.json file will automatically open if it isn't already configured in notepad on windows, nano on linux, or TextEdit on Mac -You can also open the settings.json file and edit it manually before running your first command. -The default settings are explanations of where to find the proper settings since json can't have comments -Once the settings are set you can have a jolly good time utilzing the fog documentation +You can also open the settings.json file and edit it manually before running your first command, but it's best to use the `Set-FogServerSettings -interactive` function and switch for first time setup. +The default settings in `settings.json` are explanations of where to find the proper settings since json can't have comments + +Once the settings are set you can have a jolly good time utilzing the fog documentation found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters i.e. -Get-FogObject has a type param that validates to object, objectactivetasktype, and search as those are the options given in the documentation. +`Get-FogObject` has a type param that validates to `object, objectactivetasktype, and search` as those are the options given in the documentation. Each of those types validates (which means autocompletion) to the core types listed in the documentation. -So if you typed in `Get-FogObject -Type object -Object h` and then started hitting tab, it would loop through the possible core objects you can get from the api that start with 'h' such as history, host, etc. +So if you typed in `Get-FogObject -Type object -Object h` and then started hitting tab, it would loop through the possible core objects you can get from the api that start with `h` such as history, host, etc. + +Unless you filter a GET with a json body it will return all the results into a powershell object. +That object is easy to work with to create other commands. Note: Full Pipeline support will come at a later time +i.e. + +``` +hosts = Get-FogObject -Type Object -CoreObject Host # calls GET on {your-fog-server}/fog/host to list all hosts +``` + +Now you can search all your hosts for the one or ones you are looking for with powershell +maybe you want to find all the hosts with ''IT'' in the name (note `?` is an alias for `Where-Object`) -Unless you filter a get with a json body it will return all the results into a powershell object. That object is easy to work with to create other commands. Note: Full Pipeline support will come at a later time - i.e. +``` +$ITHosts = $hosts.data | ? name -match ''IT''; +``` + +Now maybe you want to change the image all of these computers use to one named ''''IT-Image'''' +You can edit the object in powershell with a foreach-object (`%` is an alias for `foreach-object`) - `$hosts = Get-FogObject -Type Object -CoreObject Host `# calls get on http://fog-server/fog/host to list all hosts - Now you can search all your hosts for the one or ones you're looking for with powershell - maybe you want to find all the hosts with 'IT' in the name (note '?' is an alias for Where-Object) -`$ITHosts = $hosts.hosts | ? name -match 'IT';` +``` +#get the id of the image by getting all images and finding the one with the IT-image name +$image = Get-FogImages | ? name -eq "IT-image" +$updatedITHosts = $ITHosts | % { $_.imageid = $image.id} +``` -Now maybe you want to change the image all of these computers use to one named 'IT-Image' -You can edit the object in powershell with a foreach-object ('%' is an alias for foreach-object) -`$updatedITHosts = $ITHosts | % { $_.imagename = 'IT-image'}` +Then you need to convert that object to json and pass each object into one api call at a time. +Which sounds complicated, but it's not, it's as easy as -Then you need to convert that object to json and pass each object into one api call at a time. Which sounds complicated, but it's not, it's as easy as ``` -$updateITHosts | % { - $jsonData = $_ | ConvertTo-Json; - Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData $jsonData; - #successful result of updated objects properties - #or any error messages will output to screen for each object -} +$updatedITHosts | % { + Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData ($_ | ConvertTo-Json); +} ``` This is just one small example of the limitless things you can do with the api and powershell objects. +There are also many ''helper'' functions that make various operations easier. +i.e. Maybe you want to create a host and deploy that "IT-image" image to it. + +``` +#create the host +New-FogHost -name "test-host" -macs "01:23:45:67:89:00" + +#add the image to the host +$foghost = get-foghost -hostname "test-host"; +$image = Get-FogImages | ? name -eq "IT-image" +$foghost.imageid = $image.id; +$jsonData = $fogHost | ConvertTo-Json; +Update-FogObject -Type object -CoreObject host -objectID $foghost.id -jsonData jsonData; + +#start the image task on the host now +get-foghost -hostname "test-host" | send-fogimage +``` + +``` +#alternatively, schedule the image for later, like 10pm tomorrow +get-foghost -hostname "test-host" | send-fogimage -StartAtTime (Get-Date 10pm).AddDays(1) +``` + +## Additional info -see also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 +See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 diff --git a/build-choco.ps1 b/build-choco.ps1 index 8cedbdd..b7daaa2 100644 --- a/build-choco.ps1 +++ b/build-choco.ps1 @@ -36,10 +36,18 @@ .DESCRIPTION build choco module to install published powershell module +.PARAMETER buildPth +Specificy a non-default path to where the built module is found + +.PARAMETER useLocal +Switch param to create a temp repository to publish the built module to and download the nuspec and psgetxml from the local +repo and then adjust that xml to point to the psgallery as the publish repository. Default behavior is to download and package based on latest publicly available package in psgallery + #> [CmdletBinding()] Param( - [string]$buildPth + [string]$buildPth, + [switch]$useLocal ) Import-Module .\BuildHelpers.psm1 @@ -51,14 +59,22 @@ if([string]::IsNullOrEmpty($buildPth)) { $buildPth = ".\_module_build\$moduleName"; } +if ($useLocal) { + mkdir "$env:temp\modules" -ea 0 | out-null; + Register-PSResourceRepository -Name temp -Trusted -Uri "$env:temp\modules" -ea 0 + $repo = "temp" + publish-PSResource -Repository temp -Path $buildPth -vb +} else { + try { + Register-PSResourceRepository -PSGallery -Trusted -ea 0 -wa 0 + } catch { + "PSgallery already registered" | out-host + Set-PSResourceRepository -Name PSGallery -Trusted + } + $repo = "PSGallery" +} $chocoPth = "$buildPth\choco"; mkdir $chocoPth -ea 0 | out-null; -try { - Register-PSResourceRepository -PSGallery -Trusted -ea 0 -wa 0 -} catch { - "PSgallery already registered" | out-host - Set-PSResourceRepository -Name PSGallery -Trusted -} $manifest = "$buildPth\$moduleName.psd1" $cur = test-ModuleManifest -Path $manifest; @@ -68,34 +84,51 @@ $version = $cur.version; #get the psgetxml try { - Save-PSResource -Name FogApi -Repository PSGallery -Path $chocoPth -Version $version -IncludeXml -TrustRepository -ea stop; + Save-PSResource -Name FogApi -Repository $repo -Path $chocoPth -Version $version -IncludeXml -TrustRepository -ea stop; } catch { # "in the catch" | out-host; - Save-PSResource -Name FogApi -Repository PSGallery -Path $chocoPth -IncludeXml -TrustRepository; + Save-PSResource -Name FogApi -Repository $repo -Path $chocoPth -IncludeXml -TrustRepository; } #get the nuspec try { - Save-PSResource -Name FogApi -Repository PSGallery -Path $chocoPth -Version $version -AsNupkg -TrustRepository -ea Stop; + Save-PSResource -Name FogApi -Repository $repo -Path $chocoPth -Version $version -AsNupkg -TrustRepository -ea Stop; } catch { - Save-PSResource -Name FogApi -Repository PSGallery -Path $chocoPth -AsNupkg -TrustRepository; + Save-PSResource -Name FogApi -Repository $repo -Path $chocoPth -AsNupkg -TrustRepository; } #create the tools and files folders for choco pkg mkdir "$chocoPth\$moduleName\$version\tools" -ea 0 | out-null; mkdir "$chocoPth\$moduleName\$version\tools\files" -ea 0 | out-null; +if (!(Test-Path "$chocoPth\$moduleName\$version\icons")) { + mkdir "$chocoPth\$moduleName\$version\icons" -ea 0 | out-null; + Copy-Item "$PSScriptRoot\$modulename\icons\favicon.png" "$chocoPth\$moduleName\$version\icons\favicon.png" +} + #extract the nupkg as a zip and grab the nuspec rename-item "$chocoPth\$moduleName.$version.nupkg" -NewName "$moduleName.$version.zip" -Force Expand-Archive "$chocoPth\$moduleName.$version.zip" -DestinationPath "$chocoPth\$moduleName.$version" Copy-Item "$chocoPth\$moduleName.$version\$moduleName.nuspec" "$chocoPth\$moduleName\$version\$moduleName.nuspec" + Remove-Item "$chocoPth\$moduleName.$version*" -Force -Recurse -#edit the psgetxml file install location for ps5 and ps7 and save those files in the files folders +#edit the psgetxml file install location for ps5 and ps7 and save those files in the files folders, remove the downloaded psgetxml + $psgetXml = Import-Clixml "$chocoPth\$moduleName\$version\PSGetModuleInfo.xml"; +#if not grabbing the remote nuspec, set the remote to the remote repo +if ($useLocal) { + $psgetXml.Repository = "PSGallery" + $psgetXml.RepositorySourceLocation = "https://www.powershellgallery.com/api/v2" +} + +#set the ps5 install location and export $psgetXml.InstalledLocation = "C:\Program Files\WindowsPowerShell\Modules\$moduleName\$version" $psgetXml | Export-Clixml -path "$chocoPth\$moduleName\$version\tools\files\PSGetModuleInfo-ps5.xml" + +#set the ps7 install location and export $psgetXml.InstalledLocation = "C:\Program Files\PowerShell\Modules\$moduleName\$version" $psgetXml | Export-Clixml -path "$chocoPth\$moduleName\$version\tools\files\PSGetModuleInfo-ps7.xml" + remove-item "$chocoPth\$moduleName\$version\PSGetModuleInfo.xml" -force -ea 0; $chocoTemplateDir = '.\chocoTemplate\PSGetModule\tools'; @@ -111,14 +144,15 @@ if (!(Get-command choco.exe)) { #taken from https://chocolatey.org/install#individual Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) } -cd "$chocoPth\$modulename\$version" +Set-Location "$chocoPth\$modulename\$version" "Updating nuspec" | out-host; +$nuspec ="$pwd\$moduleName.nuspec" $nuspecSnippet = @" https://fogapi.readthedocs.io/en/latest https://forums.fogproject.org/topic/12026/powershell-api-module https://github.com/darksidemilk/FogApi/issues - https://github.com/darksidemilk/FogApi + https://github.com/darksidemilk/FogApi/tree/master/chocoTemplate/PSGetModule "@ $titleSnippet = @" @@ -126,7 +160,40 @@ $titleSnippet = @" FogApi Powershell Module Powershell Module for using the FOG Project API to simplify imaging and provisioning automations "@ -$nuspec ="$pwd\$moduleName.nuspec" +# $softwareSite = "https://FOGProject.org" + +$filesSnippet = @" + + + + + + + + + + + + + + +"@ + Set-Content -Path $nuspec -Value (Get-Content $nuspec).Replace("",$nuspecSnippet) -Force; Set-Content -Path $nuspec -Value (Get-Content $nuspec).Replace("FogApi",$titleSnippet) -Force; +# Set-Content -Path $nuspec -Value (Get-Content $nuspec).Replace("https://github.com/darksidemilk/FogApi",$softwareSite) -Force; +Set-Content -Path $nuspec -Value (Get-Content $nuspec).Replace("",$filesSnippet) -Force; + +if ($useLocal) { + Unregister-PSResourceRepository -name temp -ea 0; + remove-item $env:temp\modules -force -Recurse -ea 0; +} +#fix description and release notes +$nuspecContent = Get-Content $nuspec; +[xml]$nuspecXml = $nuspecContent; +$nuspecXml.package.metadata.description = "`n$($nuspecXml.package.metadata.description)" +$nuspecXml.package.metadata.releaseNotes = "`n$($nuspecXml.package.metadata.releaseNotes)" +$nuspecXml.Save($nuspec); + + choco pack diff --git a/build.ps1 b/build.ps1 index 7dae1c7..325ff15 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,7 +1,7 @@ <#PSScriptInfo -.VERSION 2.0.0.0 +.VERSION 3.0.0 .GUID 473e8205-f9ee-4185-9daa-096fb36cf0b6 @@ -9,7 +9,7 @@ .COMPANYNAME FogProject -.COPYRIGHT 2019 +.COPYRIGHT 2019-2024 .TAGS @@ -27,6 +27,10 @@ .RELEASENOTES + 3.0.0 + Updated to be compatible with github actions automated build and release flow + Added BuildHelpers.psm1 adhoc module functions + 2.0.0.0 Updated with documentation integrations @@ -95,6 +99,8 @@ mkdir "$modulePath\bin" -EA 0; mkdir "$modulePath\Public" -EA 0; mkdir "$modulePath\Private" -EA 0; mkdir "$modulePath\Classes" -EA 0; +mkdir "$modulePath\icons" -EA 0; + #update documentation @@ -184,25 +190,34 @@ try { New-ExternalHelp -Path "$docsPth\commands" -OutputPath "$docsPth\en-us" -Force; } - -$moduleFile = "$buildPth\$moduleName.psm1"; -New-Item $moduleFile -Force | Out-Null; - $PublicFunctions = Get-ChildItem "$modulePath\Public" -Recurse -Filter '*.ps1' -EA 0; $Classes = Get-ChildItem "$modulePath\Classes" -Recurse -Filter '*.ps1' -EA 0; $PrivateFunctions = Get-ChildItem "$modulePath\Private" -Recurse -Filter '*.ps1' -EA 0; -$aliases = Get-AliasesToExport -psm1Path $moduleFile -modulePath $modulePath; +$aliases = Get-AliasesToExport -psm1Path "$modulePath\$moduleName.psm1" -modulePath $modulePath; # mkdir "$PSSCriptRoot\ModuleBuild" -EA 0; # $buildPth = "$env:userprofile\ModuleBuild\$moduleName"; +"Creating new module build folder" | out-host; # Create the build output folder if (Test-Path $buildPth) { Remove-Item $buildPth -force -recurse; } mkdir $buildPth | Out-Null; +"Copying xml docs to build path" | out-host; Copy-Item "$docsPth\en-us" "$buildPth\en-us" -Recurse -Exclude '*.md'; + +"Copying icons folder" | out-host; +Copy-item "$modulePath\icons" "$buildPth\icons" -Recurse -force -ea 0; + +"Building module file" | out-host; + +$moduleFile = "$buildPth\$moduleName.psm1"; +New-Item $moduleFile -Force | Out-Null; + + +"Adding module file header" | out-host; Add-Content -Path $moduleFile -Value "`$PSModuleRoot = `$PSScriptRoot"; if ((Get-ChildItem "$modulePath\lib").count -gt 0) { Copy-Item "$modulePath\lib" "$buildPth\lib" -Recurse; @@ -218,33 +233,33 @@ Add-Content -Path $moduleFile -Value "`$script:tools = `"`$PSModuleRoot\tools`"" #Build the psm1 file - #Add Classes if ($null -ne $Classes) { - + "Adding classes to module file" | out-host; $Classes | ForEach-Object { Add-Content -Path $moduleFile -Value (Get-Content $_.FullName); } - } # Add-PublicFunctions -Add-Content -Path $moduleFile -Value $heading - # $PublicFunctions; - $PublicFunctions | ForEach-Object { # Replace the comment block with external help link - $rawContent = (Get-Content $_.FullName -Raw); - $commentStartIdx = $rawContent.indexOf('<#'); - if ($commentStartIdx -ge 0) { - $commentEndIdx = $rawContent.IndexOf('#>'); - $commentLength = $commentEndIdx - ($commentStartIdx-2); #-2 to adjust for the # in front of > and the index starting at 0 - $comment = $rawContent.Substring($commentStartIdx,$commentLength); - $newComment = "# .ExternalHelp $moduleName-help.xml" - $Function = $rawContent.Replace($comment,$newComment); - } else { - $Function = $rawContent; - } - Add-Content -Path $moduleFile -Value $Function - } +# Add-Content -Path $moduleFile -Value $heading +# $PublicFunctions; +"Adding public functions to module file" | Out-Host; +$PublicFunctions | ForEach-Object { # Replace the comment block with external help link + $rawContent = (Get-Content $_.FullName -Raw); + $commentStartIdx = $rawContent.indexOf('<#'); + if ($commentStartIdx -ge 0) { + $commentEndIdx = $rawContent.IndexOf('#>'); + $commentLength = $commentEndIdx - ($commentStartIdx-2); #-2 to adjust for the # in front of > and the index starting at 0 + $comment = $rawContent.Substring($commentStartIdx,$commentLength); + $newComment = "# .ExternalHelp $moduleName-help.xml" + $Function = $rawContent.Replace($comment,$newComment); + } else { + $Function = $rawContent; + } + Add-Content -Path $moduleFile -Value $Function +} #Add Private Functions +"Adding private functions to module file" | Out-Host; if ($null -ne $PrivateFunctions) { $PrivateFunctions | ForEach-Object { Add-Content -Path $moduleFile -Value (Get-Content $_.FullName); @@ -252,7 +267,7 @@ if ($null -ne $PrivateFunctions) { } #Update The Manifest - +"Updating the module manifest" $manifest = "$PSScriptRoot\$moduleName\$moduleName.psd1" $cur = test-ModuleManifest -Path $manifest; @@ -270,7 +285,7 @@ if ($major) { # $verArgs.Add(($oldVer.Revision + 1)) # if($verArgs[-1] -eq 0) {$verArgs[-1] += 1} $newVer = New-Object version -ArgumentList $verArgs; -$releaseNotes = "`n# $newVer`n`n`t$releaseNote" +$releaseNotes = "`n# $newVer`n`n`t$releaseNote`n`nFull change log history available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/" $copyRight = (get-date -Format yyyy).tostring() @@ -302,11 +317,17 @@ if($null -eq $aliases) { } # Update-ModuleManifest -Path $manifest -ReleaseNotes $releaseNotes -ModuleVersion $newVer -RootModule "$moduleName.psm1" -FunctionsToExport $PublicFunctions.BaseName -Update-ModuleManifest @manifestSplat; +if (Get-Command Update-PSModuleManifest) { + Update-PSModuleManifest @manifestSplat; +} else { + "PSResourceGet version of update manifest not found, reverting to psget version, may cause issues with choco nuspec" | out-host; + Update-ModuleManifest @manifestSplat; +} Set-EmptyExportArray -psd1Path $Manifest -ExportType Cmdlets; Set-EmptyExportArray -psd1Path $Manifest -ExportType Variables; +"Adding manifest to build path" | out-host; Copy-Item $manifest "$buildPth\$moduleName.psd1"; diff --git a/chocoTemplate/PSGetModule/FogApi.nuspec b/chocoTemplate/PSGetModule/FogApi.nuspec new file mode 100644 index 0000000..affaf26 --- /dev/null +++ b/chocoTemplate/PSGetModule/FogApi.nuspec @@ -0,0 +1,38 @@ + + + + FogApi + FogApi Powershell Module + Powershell Module for using the FOG Project API to simplify imaging and provisioning automations + [[ModuleVersion]] + JJ Fullmer + FOG Project + false + https://github.com/darksidemilk/FogApi/blob/master/LICENSE + https://github.com/darksidemilk/FogApi + https://cdn.statically.io/gh/darksidemilk/FogApi/0ed5e87e/FogApi/icons/favicon.png + +[[ModuleDescription]] + +[[ModuleReleaseNote]] + 2018-2024 + PSModule fog fogapi imaging provisioning fogproject + https://fogapi.readthedocs.io/en/latest + https://forums.fogproject.org/topic/12026/powershell-api-module + https://github.com/darksidemilk/FogApi/issues + https://github.com/darksidemilk/FogApi/tree/master/chocoTemplate/PSGetModule + + + + + + + + + + + + + + + diff --git a/chocoTemplate/PSGetModule/README.MD b/chocoTemplate/PSGetModule/README.MD new file mode 100644 index 0000000..cf97edf --- /dev/null +++ b/chocoTemplate/PSGetModule/README.MD @@ -0,0 +1,9 @@ +# Choco Package Template + +This is the template for the creating the chocolatey package with the build-choco.ps1 script at the root of this repo. +build-choco.ps1 is run after running the build.ps1 is run and typically after publishing to the powershell gallery so the same nuspec published to the psgallery is used for the choco package (with some chocolatey specific alterations) +The nuspec found here is a general template for what is built, it isn't actually used in the build script at this time. +Could have the main build function build into here + +The PSGetModuleInfo-*.xml files in the tools\files folder are generated at save/install time by PowershellGet/PSResourceGet and are what are required for a module to show in the `Get-InstalledModule` and `Get-InstalledPSResource -scope allusers` commands. +The general templates are stored here in the template, but they are obtained dynamically at build time for the package. \ No newline at end of file diff --git a/chocoTemplate/PSGetModule/tools/chocolateyInstall.ps1 b/chocoTemplate/PSGetModule/tools/chocolateyInstall.ps1 index e011489..4b3ac17 100644 --- a/chocoTemplate/PSGetModule/tools/chocolateyInstall.ps1 +++ b/chocoTemplate/PSGetModule/tools/chocolateyInstall.ps1 @@ -30,7 +30,7 @@ $destinationPath = New-Object -TypeName 'System.Collections.generic.list[System. $destinationPath.add((Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules\$moduleName\$moduleVersion")) $destinationPath.add((Join-Path -Path $env:ProgramFiles -ChildPath "PowerShell\Modules\$moduleName\$moduleVersion")) -"Installing $modulename version $moduleVersion in bothe pwsh 7+ and windows powershell 5.1 system paths" | out-host; +"Installing $modulename version $moduleVersion in both pwsh 7+ and windows powershell 5.1 system paths" | out-host; ForEach ($destPath in $destinationPath) { Write-Verbose "Installing '$modulename' to '$destPath'." @@ -58,7 +58,7 @@ ForEach ($destPath in $destinationPath) { } else { #this is the tools dir, make sure to not copy the chocolatey install scripts or psgetxml sources folder to the module install folder try { - Copy-Item $_ -Destination $destPath -Exclude "sources","chocolateyInstall.ps1","chocolateyUninstall.ps1","chocolateyBeforeModify.ps1","PSGetModuleInfo-ps5.xml","PSGetModuleInfo-ps7.xml" -force -Recurse + Copy-Item $_ -Destination $destPath -Exclude "sources","files","chocolateyInstall.ps1","chocolateyUninstall.ps1","chocolateyBeforeModify.ps1","PSGetModuleInfo-ps5.xml","PSGetModuleInfo-ps7.xml","functions.psm1" -force -Recurse } catch { if ($compare) { Write-Verbose "The module may have already been installed, ignoring errors" @@ -66,6 +66,20 @@ ForEach ($destPath in $destinationPath) { throw "Error during copy of $($_) to $destPath!" } } + Write-Verbose "Removing any empty directories within tools directory" + "files","sources" | ForEach-Object { + if (Test-path "$destPath\$_") { + if ((Get-ChildItem -Path "$destPath\$_").count -eq 0) { + Remove-Item "$destPath\$_" -Force -Recurse; + } + } + } + Write-Verbose "Empty tools directory from installed location if it is empty" + if (Test-path "$destPath") { + if ((Get-ChildItem -Path "$destPath").count -eq 0) { + Remove-Item "$destPath" -Force -Recurse; + } + } } } @@ -115,9 +129,13 @@ ForEach ($destPath in $destinationRootPath) { if ($null -ne $oldVersions) { Write-verbose "Taking ownership of path $($_) and setting permissions"; $oldVersions | ForEach-Object { - $takeOwn = start-process -FilePath takeown.exe -ArgumentList "/F `"$($_)`" /R /A /D Y" -wait -NoNewWindow -PassThru -RedirectStandardOutput "C:\logs\takeown-$modulename-paths.log" - Write-Verbose "Take Ownership result is $($takeOwn | out-string) - $(Get-content "C:\logs\takeown-$modulename-paths.log" | out-string)" - Remove-Item "C:\logs\takeown-$modulename-paths.log" -force -Recurse -ea 0; + $logDir = "$env:temp\logs" + if (!(Test-Path $logDir)) { + mkdir $logDir -ea 0; + } + $takeOwn = start-process -FilePath takeown.exe -ArgumentList "/F `"$($_)`" /R /A /D Y" -wait -NoNewWindow -PassThru -RedirectStandardOutput "$logDir\takeown-$modulename-paths.log" + Write-Verbose "Take Ownership result is $($takeOwn | out-string) - $(Get-content "$logDir\takeown-$modulename-paths.log" | out-string)" + Remove-Item "$logDir\takeown-$modulename-paths.log" -force -Recurse -ea 0; } try { $perms = Grant-FullRightsToPath -path $oldVersions -recurseInherit -ea stop -wa 0 -wait -NoOutHost @@ -127,6 +145,7 @@ ForEach ($destPath in $destinationRootPath) { Write-Verbose "Grant-fullrightstopath had an error, icacls native grant result is $($perms | out-string)" } $oldVersions | Foreach-object { + #uninstall from rare path scenario if ($_ -match 'config\\systemprofile\\AppData\\Local\\Microsoft\\Windows\\INetCache') { $inetCache = "C:\windows\system32\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache" if (Test-Path $inetCache) { @@ -139,8 +158,10 @@ ForEach ($destPath in $destinationRootPath) { remove-item $inetCache -Force -Recurse } } elseif ($_ -match "AppData\\Local\\Application Data") { + #uninstall from rare path scenario Write-Warning "$($_) is a symlink path with no access, skip this install, this may indicate other misconfigurations! Skipping removal attempts of this path" } else { + #standard uninstall try { if (Test-Path $_) { Write-Verbose "Attempting removal of old version of $moduleName installed at $($_)" @@ -174,7 +195,7 @@ $sourcePath | ForEach-Object { } else { #is toolsdir, keep install scripts if (Test-Path $_) { - $_ | Get-ChildItem -Exclude "sources","chocolateyInstall.ps1","chocolateyUninstall.ps1","chocolateyBeforeModify.ps1" | ForEach-Object { + $_ | Get-ChildItem -Exclude "sources","files","chocolateyInstall.ps1","chocolateyUninstall.ps1","chocolateyBeforeModify.ps1","functions.psm1" | ForEach-Object { Remove-item $_.fullname -force -recurse -ea 0; } } diff --git a/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps5.xml b/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps5.xml new file mode 100644 index 0000000..d3adecf --- /dev/null +++ b/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps5.xml @@ -0,0 +1,108 @@ + + + + Deserialized.System.Management.Automation.PSCustomObject + Deserialized.System.Object + + + FogApi + [[ModuleVersion]] + + + Deserialized.Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType + Deserialized.System.Enum + Deserialized.System.ValueType + Deserialized.System.Object + + Module + 1 + + _x000D__x000A_# FOG Api Powershell Module_x000D__x000A__x000D__x000A_This is a powershell module to simplify the use of the Fog Project API._x000D__x000A_This module is used to easily run Fog API commands on your fogserver from a powershell console or script._x000D__x000A_FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to _x000D__x000A_perform almost any operation you can do in the GUI of Fog and provides you with the ability to extend things further._x000D__x000A_It can be used to create more automation or to simply have a command line method of controlling fog operations._x000D__x000A_This essentially gives you a crossplatform commandline interface for fog tasks and makes many things easier to automate._x000D__x000A__x000D__x000A_Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/_x000D__x000A__x000D__x000A_For more information about FOG see_x000D__x000A__x000D__x000A_- https://FOGProject.org_x000D__x000A_- https://docs.fogproject.org_x000D__x000A_- https://github.com/FOGProject_x000D__x000A_- https://github.com/FOGProject/fogproject_x000D__x000A_- https://forums.fogproject.org_x000D__x000A__x000D__x000A_# Versioning_x000D__x000A__x000D__x000A_The versioning of this module follows this pattern_x000D__x000A__x000D__x000A_`{Year|Month}.{Major Version}.{Revision #}`_x000D__x000A__x000D__x000A_## Year/Month_x000D__x000A__x000D__x000A_This versioning shows you first the Year and month this version of the module was published, giving you an idea of when it was last updated._x000D__x000A_i.e. 2208 would be august 2022._x000D__x000A__x000D__x000A_## Major_x000D__x000A__x000D__x000A_The Major version follows the typical major versioning where any major changes will increment this version number, especially possible breaking changes or structural changes, etc._x000D__x000A__x000D__x000A_## Minor/Revision_x000D__x000A__x000D__x000A_Any time I publish a new version that isn't a major change I'll increment the revision. This may also be incremented for each build test and increment by more than one for each published version_x000D__x000A__x000D__x000A_# Usage_x000D__x000A__x000D__x000A_You can use Set-fogserverSettings to set your fogserver hostname and api keys._x000D__x000A_The first time you try to run a command the settings.json file will automatically open_x000D__x000A_in notepad on windows, nano on linux, or TextEdit on Mac_x000D__x000A_You can also open the settings.json file and edit it manually before running your first command._x000D__x000A_The default settings are explanations of where to find the proper settings since json can''t have comments_x000D__x000A__x000D__x000A_Once the settings are set you can have a jolly good time utilzing the fog documentation_x000D__x000A_found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters_x000D__x000A__x000D__x000A_See https://github.com/darksidemilk/FogApi/blob/master/README.md for more examples and see https://fogapi.readthedocs.io/en/latest/commands/ for a list of all the commands_x000D__x000A__x000D__x000A_# Additional info_x000D__x000A__x000D__x000A_See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2_x000D__x000A_Full change log available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/_x000D__x000A_ + JJ Fullmer + FOG Project + 2018-2024 + +
2024-09-09T10:51:37.0771033-06:00
+ false + + https://github.com/darksidemilk/FogApi/blob/master/LICENSE + https://github.com/darksidemilk/FogApi + https://cdn.statically.io/gh/darksidemilk/FogApi/0ed5e87e/FogApi/icons/favicon.png + + + Deserialized.System.String[] + Deserialized.System.Array + Deserialized.System.Object + + + fog + fogapi + imaging + provisioning + fogproject + + + + + Deserialized.System.Collections.Hashtable + Deserialized.System.Object + + + + DscResource + + + + + + + RoleCapability + + + + Cmdlet + + + + + + + Function + + + + Workflow + + + + Command + + + + + + + + + _x000D__x000A_# [[ModuleVersion]]_x000D__x000A__x000D__x000A__x0009_Updated choco build to reformat release notes and description_x000D__x000A__x000D__x000A_Full change log history available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/ + + + Deserialized.Microsoft.PowerShell.PSResourceGet.UtilClasses.Dependency[] + Deserialized.System.Array + Deserialized.System.Object + + + + https://www.powershellgallery.com/api/v2 + PSGallery + + + + [[ModuleVersion]] + False + + + C:\Program Files\WindowsPowerShell\Modules\FogApi\[[ModuleVersion]] +
+
+
\ No newline at end of file diff --git a/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps7.xml b/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps7.xml new file mode 100644 index 0000000..66a90d2 --- /dev/null +++ b/chocoTemplate/PSGetModule/tools/files/PSGetModuleInfo-ps7.xml @@ -0,0 +1,108 @@ + + + + Deserialized.System.Management.Automation.PSCustomObject + Deserialized.System.Object + + + FogApi + [[ModuleVersion]] + + + Deserialized.Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType + Deserialized.System.Enum + Deserialized.System.ValueType + Deserialized.System.Object + + Module + 1 + + _x000D__x000A_# FOG Api Powershell Module_x000D__x000A__x000D__x000A_This is a powershell module to simplify the use of the Fog Project API._x000D__x000A_This module is used to easily run Fog API commands on your fogserver from a powershell console or script._x000D__x000A_FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to _x000D__x000A_perform almost any operation you can do in the GUI of Fog and provides you with the ability to extend things further._x000D__x000A_It can be used to create more automation or to simply have a command line method of controlling fog operations._x000D__x000A_This essentially gives you a crossplatform commandline interface for fog tasks and makes many things easier to automate._x000D__x000A__x000D__x000A_Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/_x000D__x000A__x000D__x000A_For more information about FOG see_x000D__x000A__x000D__x000A_- https://FOGProject.org_x000D__x000A_- https://docs.fogproject.org_x000D__x000A_- https://github.com/FOGProject_x000D__x000A_- https://github.com/FOGProject/fogproject_x000D__x000A_- https://forums.fogproject.org_x000D__x000A__x000D__x000A_# Versioning_x000D__x000A__x000D__x000A_The versioning of this module follows this pattern_x000D__x000A__x000D__x000A_`{Year|Month}.{Major Version}.{Revision #}`_x000D__x000A__x000D__x000A_## Year/Month_x000D__x000A__x000D__x000A_This versioning shows you first the Year and month this version of the module was published, giving you an idea of when it was last updated._x000D__x000A_i.e. 2208 would be august 2022._x000D__x000A__x000D__x000A_## Major_x000D__x000A__x000D__x000A_The Major version follows the typical major versioning where any major changes will increment this version number, especially possible breaking changes or structural changes, etc._x000D__x000A__x000D__x000A_## Minor/Revision_x000D__x000A__x000D__x000A_Any time I publish a new version that isn't a major change I'll increment the revision. This may also be incremented for each build test and increment by more than one for each published version_x000D__x000A__x000D__x000A_# Usage_x000D__x000A__x000D__x000A_You can use Set-fogserverSettings to set your fogserver hostname and api keys._x000D__x000A_The first time you try to run a command the settings.json file will automatically open_x000D__x000A_in notepad on windows, nano on linux, or TextEdit on Mac_x000D__x000A_You can also open the settings.json file and edit it manually before running your first command._x000D__x000A_The default settings are explanations of where to find the proper settings since json can''t have comments_x000D__x000A__x000D__x000A_Once the settings are set you can have a jolly good time utilzing the fog documentation_x000D__x000A_found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters_x000D__x000A__x000D__x000A_See https://github.com/darksidemilk/FogApi/blob/master/README.md for more examples and see https://fogapi.readthedocs.io/en/latest/commands/ for a list of all the commands_x000D__x000A__x000D__x000A_# Additional info_x000D__x000A__x000D__x000A_See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2_x000D__x000A_Full change log available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/_x000D__x000A_ + JJ Fullmer + FOG Project + 2018-2024 + +
2024-09-09T10:51:37.0771033-06:00
+ false + + https://github.com/darksidemilk/FogApi/blob/master/LICENSE + https://github.com/darksidemilk/FogApi + https://cdn.statically.io/gh/darksidemilk/FogApi/0ed5e87e/FogApi/icons/favicon.png + + + Deserialized.System.String[] + Deserialized.System.Array + Deserialized.System.Object + + + fog + fogapi + imaging + provisioning + fogproject + + + + + Deserialized.System.Collections.Hashtable + Deserialized.System.Object + + + + DscResource + + + + + + + RoleCapability + + + + Cmdlet + + + + + + + Function + + + + Workflow + + + + Command + + + + + + + + + _x000D__x000A_# [[ModuleVersion]]_x000D__x000A__x000D__x000A__x0009_Updated choco build to reformat release notes and description_x000D__x000A__x000D__x000A_Full change log history available at https://fogapi.readthedocs.io/en/latest/ReleaseNotes/ + + + Deserialized.Microsoft.PowerShell.PSResourceGet.UtilClasses.Dependency[] + Deserialized.System.Array + Deserialized.System.Object + + + + https://www.powershellgallery.com/api/v2 + PSGallery + + + + [[ModuleVersion]] + False + + + C:\Program Files\PowerShell\Modules\FogApi\[[ModuleVersion]] +
+
+
\ No newline at end of file diff --git a/docs/ReleaseNotes.md b/docs/ReleaseNotes.md index 998e723..6bdd157 100644 --- a/docs/ReleaseNotes.md +++ b/docs/ReleaseNotes.md @@ -2,12 +2,58 @@ ## 9.x -### 2409.9.4 +### 2409.9.15 + + revert change of appending gpu ram + +### 2409.9.14 + + Filter out rdp display driver when getting host inventory details and append video memory in GB to each adapter name + +### 2409.9.13 + + Updated Send-FogImage with params for 1.6 and added switch options and autocomplete for available fog images. Also added a basic Set-FogHostImage function, needs to be further flushes out but the basic functionality is there. + + + +### 2409.9.12 + + Updated choco build and build function formatting operations further + +### 2409.9.11 + + Updated choco build to reformat release notes and description + +### 2409.9.10 + + Updated release note formatting in manifest to always link to full change log + +### 2409.9.9 + + Adding choco package template for source url and fix releasenote md formattinc in nuspec + +### 2409.9.8 + + Added gpu properties to get-foginventory for upcoming add of gpu info to fog inventory records and fixed missing functions in in get-winbcdpxeid - "Adding Chocolatey package and updates to auto adding various assets to each release. Also updated some manifest things. No Code changes, really just a maintenance release" +### 2409.9.7 + Fix choco package building issue where not all files were being properly included in the package +### 2409.9.6 + + Fix choco template issue of typo of folder name sources vs files + +### 2409.9.5 + + Updated and unified various docs, added icon packaging with best practicies for chocolatey and psgallery. Updated chocolatey packaging and build functions. + +### 2409.9.4 + + Adding Chocolatey package and updates to auto adding various assets to each release. + Also updated some manifest things. + No Code changes, really just a maintenance release ### 2408.9.3 @@ -24,7 +70,7 @@ - Fixed issue with getting fog inventory in 1.6 - Implemented #16 for getting and setting fog global settings in fog 1.6 - Implemented #14 for getting the fog version - - Implemented #13 for invoking wol task for a host + - Implemented #13 for invoking wol task for a host - Added basic pipeline functionality for foghost objects in all applicable functions. - Made it possible to send multiple specified snapins in a single start-fogsnapin call - Added tab completion of server specific host names and snapin names in various functions like get-foghost, start-fogsnapin. set-fogsnapins, remove-usbmac @@ -353,17 +399,28 @@ ### 2004.2.2.1 - * Mainly a bug fix release for issues with pending mac handling.Ended up adding some extra helper functions along the way - * Added more get functions for ease of use including + - Mainly a bug fix release for issues with pending mac handling.Ended up adding some extra helper functions along the way + - Added more get functions for ease of use including - Get-FogGroupAssociations - Get-FogGroupByName - Get-FogGroups - Get-FogHostGroup (replaces Get-FogGroup, but kept Get-FogGroup as an alias as to not break anyones scripts) - Get-FogMacAddresses (has alias of Get-FogMacs) - Get-MacsForHost - * Fixed Approve-FogPendingMac so it makes a given mac not pending instead of keeping it pending - * Fixed Get-PendingMacsForHost so it uses less pipeline and more separate commands that was causing it to return all pending macs in some cases, rather than just for a given host - * Added hostID param to get-foghost so you can get a host from the internal hostID if you already have that + - Fixed Approve-FogPendingMac so it makes a given mac not pending instead of keeping it pending + - Fixed Get-PendingMacsForHost so it uses less pipeline and more separate commands that was causing it to return all pending macs in some cases, rather than just for a given host + - Added hostID param to get-foghost so you can get a host from the internal hostID if you already have that + + + + + + + + + + + diff --git a/docs/about_FogApi.md b/docs/about_FogApi.md index e2946d7..d242160 100644 --- a/docs/about_FogApi.md +++ b/docs/about_FogApi.md @@ -9,48 +9,105 @@ A module for managing FOG API operations via powershell # LONG DESCRIPTION This is a powershell module to make using the Fog Project API even easier. -FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to perform almost any operation. It can be used to create more automation or to simply have a command line method of controlling fog operations. +This module is used to easily run Fog API commands on your fogserver from a powershell console or script. +FOG is an opensource tool for imaging comptuters, this module uses the API on your internal fog server to perform almost any operation you can do in the GUI of Fog and provides you with the ability to extend things further. +It can be used to create more automation or to simply have a command line method of controlling fog operations. +This essentially gives you a crossplatform commandline interface for fog tasks and makes many things easier to automate. + +Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/ + +For more information about FOG see + +- https://FOGProject.org +- https://docs.fogproject.org +- https://github.com/FOGProject +- https://github.com/FOGProject/fogproject +- https://forums.fogproject.org # Versioning The versioning of this module follows this pattern -`{Year|Month}.{Major Version}.{Build/Revision #}` +`{Year|Month}.{Major Version}.{Revision #}` ## Year/Month -This versioning shows you first the Year and Month the module was published, giving you an idea of when it was last updated. +This versioning shows you first the Year and month this version of the module was published, giving you an idea of when it was last updated. +i.e. 2208 would be august 2022. ## Major The Major version follows the typical major versioning where any major changes will increment this version number, especially possible breaking changes or structural changes, etc. -## Minor/Build/Revision +## Minor/Revision -Not every revision will be published. This is auto incremented every time the build script is used to test something. Not all of these changes are added to git or published so there is often a jump between releases representing how many builds/revisions have taken place during development. +Any time I publish a new version that isn't a major change I'll increment the revision. This may also be incremented for each build test and increment by more than one for each published version # Installation -All completed/tested/stable releases of this module will be published to powershell gallery. -You can also download the sources zip from the latest release and manually build the module with the build.ps1 script +The module can be installed via PowershellGet, PSResourceGet, Chocolatey, or Manually + +## Installation Methods + +To install this module you need at least powershell v3, it was originally created with 5.1, +but now for BEST EXPERIENCE use Powershell Core 7+ to be able to use tab completion when running Fog 1.6 + +To Install this module follow these steps -## Requirements +### Install from PSgallery -To install this module you need at least powershell v3, was created with 5.1 and intended to be cross platform compatible with powershell v6 and v7 +- Easiest method: Install from PSGallery https://www.powershellgallery.com/packages/FogApi with powershellget or PSResourceGet + - `Install-Module -name FogApi -Scope AllUsers` + - `Install-PSResource -Name FogApi -scope -Scope AllUsers` +- updating is then as easy as + - `Update-Module -name FogApi` + - `Update-PSResource -Name FogApi` -To Install this module follow these steps... +### Install with Chocolatey -## Install From PSGallery +If you have chocolatey package manager, you can use the published package that manually installs the module the same way the PSGet managers do. +https://community.chocolatey.org/packages/FogApi +See https://chocolatey.org for more information on chocolatey package manager -* Easiest method: [Install from PSGallery](https://www.powershellgallery.com/packages/FogApi) via a powershell console with the command - * `Install-Module -name fogApi` +- Install with chocolatey (will install the module by copying the built version to the powershell core and windows powershell paths, will remove any existing versions) + - `choco install fogapi -y` +- Upgrading is as easy as (note that you can also use this same command for a new install) + - `choco upgrade fogapi -y` +## Manual Installation + +### Use assets from the release + +- Use Chocolatey, PackageManagement, Nuget or what have you to install the *chocolatey.nupkg or *.psgallery.nupkg file from the release assets +- Extract the *builtModule.zip from the release and run `import-module` on the resulting folder for a portable installation. You can also extract to the paths outlined below in the manual build install steps for a more system wide install + +### Manually build the module + +- Manual Method: +- download the zip of this repo and extract it (or use git clone) + - Or clone the repo using your favorite git tool, you just need the FogApi Folder this readme is in +- Run the build.ps1 script +- Copy the built module folder (.\_module_build) into... + - For Windows Powershell v3-v5.1 + - C:\Program Files\WindowsPowershell\Modules\FogApi + - For Powershell Core (pwsh) on Windows v7+ + - C:\Program Files\PowerShell\Modules\FogApi + - For Linux Powershell Core (pwsh) v7+ + - /usr/local/share/powershell/Modules/FogApi + - For Mac Powershell Core (pwsh) v7+ (untested) + - /usr/local/share/powershell/Modules/FogApi + - I haven't tested this on a mac, the module folder may be somewhere else + this is based on where it is in other powershell core installs +- Open powershell (as admin recommended) +- Run `Import-Module FogApi` + +The module is now installed. ### Update from psgallery `Update-Module FogApi` -Note: Powershell supports side by side versions, after updating you may want to uninstall old versions with this snippet to avoid conflicting versions. This needs to be run as an admin to uninstall for all users, you can also have installed the module per user, in which case you can add the +Note: PowershellGet supports side by side versions, after updating you may want to uninstall old versions with this snippet to avoid conflicting versions. This needs to be run as an admin to uninstall for all users, you can also have installed the module per user, in which case you can add the ``` #find the latest version from the psgallery @@ -59,85 +116,83 @@ $latestModule = Find-Module FogApi; (Get-installedmodule FogApi -AllVersions) | Where-Object { $latestModule.version -notmatch $_.version } | Uninstall-Module -Force ``` -## Manual Installation - -* Manual Method: -* download the zip of this repo and extract it - * Or clone the repo using your favorite git tool, you just need the FogApi Folder this readme is in -* Run the build.ps1 script -* Copy the built module folder (`$env:userprofile\moduleBuild\fogAPI`) into... - * For Windows Powershell v3-v5.1 - * C:\Program Files\WindowsPowershell\Modules - * For Windows Powershell v6+ - * C:\Program Files\PowerShell\6-preview\Modules - * 6-Preview may need to be replaced with whatever current version you have installed - * For Linux Powershell v6+ - * /opt/microsoft/powershell/6.1.0-preview.2/Modules - * 6.1.0-preview.2 may need to be replaced with whatever current version you have installed - * For Mac Powershell v6+ (untested) - * /usr/local/microsoft/powershell/6.x/Modules - * 6.x should be replaced with whatever most current version you are using - * I haven't tested this on a mac, the module folder may be somewhere else - this is based on where it is in other powershell 6 installs -* Open a powershell window -* Run `Import-Module FogApi` - -You can also import the built module from its build path, the above method makes it available by name - -The module is now installed. # Using The Module +You can use `Set-FogServerSettings` to set your fogserver hostname and api keys. -The first time you try to run a command the settings.json file will automatically open +The first time you try to run a command the settings.json file will automatically open if it isn't already configured in notepad on windows, nano on linux, or TextEdit on Mac -You can also open the settings.json file and edit it manually before running your first command. -The default settings are explanations of where to find the proper settings since json can't have comments -You can also use Set-FogServerSettings to set the api tokens for the sever and your user in one command. You first need to obtain these keys/tokens from the fog web gui. replace fog-server in the below example links with the name of your internal fog server if different -- The fog API token is found at https://fog-server/fog/management/index.php?node=about&sub=settings under API System -- The fog user api token found in the user settings https://fog-server/fog/management/index.php?node=user&sub=list select your api enabled used and view the api tab -- the fog server name is the name of your fog server, it defaults to `fog-server` but can be updated if you aren't using that default name as the hostname or an alias +You can also open the settings.json file and edit it manually before running your first command, but it's best to use the `Set-FogServerSettings -interactive` function and switch for first time setup. +The default settings in `settings.json` are explanations of where to find the proper settings since json can't have comments -Once you've obtained these you can run the command like this to save your fog api settings for the current user in a json file under `$home/APPDATA/Roaming/FogApi/api-settings.json` (this appdata path is created in linux/mac home folders) +Once the settings are set you can have a jolly good time utilzing the fog documentation +found here https://news.fogproject.org/simplified-api-documentation/ that was used to model the parameters -``` -Set-FogServerSettings -fogApiToken "SuperLongPastedFogToken" -fogUserToken "SuperLongPastedUserToken" -fogServer "fog-server-hostname" -``` +i.e. -Once the settings are set you can have a jolly good time utilzing the fog documentation -found [here](https://news.fogproject.org/simplified-api-documentation/) that was used to model the parameters +`Get-FogObject` has a type param that validates to `object, objectactivetasktype, and search` as those are the options given in the documentation. +Each of those types validates (which means autocompletion) to the core types listed in the documentation. +So if you typed in `Get-FogObject -Type object -Object h` and then started hitting tab, it would loop through the possible core objects you can get from the api that start with `h` such as history, host, etc. +Unless you filter a GET with a json body it will return all the results into a powershell object. +That object is easy to work with to create other commands. Note: Full Pipeline support will come at a later time i.e. -Get-FogObject has a type param that validates to object, objectactivetasktype, and search as those are the options given in the documentation. -Each of those types validates (which means autocompletion) to the core types listed in the documentation. -So if you typed in `Get-FogObject -Type object -Object h` and then started hitting tab, it would loop through the possible core objects you can get from the api that start with 'h' such as history, host, etc. +``` +hosts = Get-FogObject -Type Object -CoreObject Host # calls GET on {your-fog-server}/fog/host to list all hosts +``` + +Now you can search all your hosts for the one or ones you are looking for with powershell +maybe you want to find all the hosts with ''IT'' in the name (note `?` is an alias for `Where-Object`) -Unless you filter a get with a json body it will return all the results into a powershell object. That object is easy to work with to create other commands. Note: Full Pipeline support will come at a later time - i.e. +``` +$ITHosts = $hosts.data | ? name -match ''IT''; +``` - `$hosts = Get-FogObject -Type Object -CoreObject Host ` - - Does a GET call on [http://fog-server/fog/host](http://fog-server/fog/host) to list all hosts - Now you can search all your hosts for the one or ones you're looking for with powershell. - maybe you want to find all the hosts with 'IT' in the name (note '?' is an alias for Where-Object) -`$ITHosts = $hosts.hosts | ? name -match 'IT';` +Now maybe you want to change the image all of these computers use to one named ''''IT-Image'''' +You can edit the object in powershell with a foreach-object (`%` is an alias for `foreach-object`) + +``` +#get the id of the image by getting all images and finding the one with the IT-image name +$image = Get-FogImages | ? name -eq "IT-image" +$updatedITHosts = $ITHosts | % { $_.imageid = $image.id} +``` -Now maybe you want to change the image all of these computers use to one named 'IT-Image' -You can edit the object in powershell with a foreach-object ('%' is an alias for foreach-object) -`$updatedITHosts = $ITHosts | % { $_.imagename = 'IT-image'}` +Then you need to convert that object to json and pass each object into one api call at a time. +Which sounds complicated, but it's not, it's as easy as -Then you need to convert that object to json and pass each object into one api call at a time. Which sounds complicated, but it's not, it's as easy as ``` -$updateITHosts | % { - $jsonData = $_ | ConvertTo-Json; - Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData $jsonData; - #successful result of updated objects properties - #or any error messages will output to screen for each object -} +$updatedITHosts | % { + Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData ($_ | ConvertTo-Json); +} ``` This is just one small example of the limitless things you can do with the api and powershell objects. +There are also many ''helper'' functions that make various operations easier. +i.e. Maybe you want to create a host and deploy that "IT-image" image to it. + +``` +#create the host +New-FogHost -name "test-host" -macs "01:23:45:67:89:00" + +#add the image to the host +$foghost = get-foghost -hostname "test-host"; +$image = Get-FogImages | ? name -eq "IT-image" +$foghost.imageid = $image.id; +$jsonData = $fogHost | ConvertTo-Json; +Update-FogObject -Type object -CoreObject host -objectID $foghost.id -jsonData jsonData; + +#start the image task on the host now +get-foghost -hostname "test-host" | send-fogimage +``` + +``` +#alternatively, schedule the image for later, like 10pm tomorrow +get-foghost -hostname "test-host" | send-fogimage -StartAtTime (Get-Date 10pm).AddDays(1) +``` + +## Additional info -see also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 +See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 diff --git a/docs/commands/Get-FogInventory.md b/docs/commands/Get-FogInventory.md index 322889a..0e12484 100644 --- a/docs/commands/Get-FogInventory.md +++ b/docs/commands/Get-FogInventory.md @@ -44,7 +44,7 @@ the inventory of the linux machine isn't yet implemented ### -hostObj the host to get the model of the inventory object from This is used for the inventory structure of the object -It defaults to the current host +It defx\`aults to the current host ```yaml Type: Object diff --git a/docs/commands/Get-WinBcdPxeId.md b/docs/commands/Get-WinBcdPxeId.md index 8f7a4cf..a58e773 100644 --- a/docs/commands/Get-WinBcdPxeId.md +++ b/docs/commands/Get-WinBcdPxeId.md @@ -25,7 +25,7 @@ The id can be used with \`bcdedit /set "{fwbootmgr}" displayorder $pxeID /addfir ### EXAMPLE 1 ``` -Get-BcdPxeBootID +Get-WinBcdPxeId ``` Will return the guid of the native pxe boot option if one is found. diff --git a/docs/commands/Send-FogImage.md b/docs/commands/Send-FogImage.md index d9f6eda..35224ed 100644 --- a/docs/commands/Send-FogImage.md +++ b/docs/commands/Send-FogImage.md @@ -14,24 +14,26 @@ Start or schedule a deploy task for a fog host ### now (Default) ``` -Send-FogImage [-hostId ] [-ProgressAction ] [] +Send-FogImage [-hostId ] [-imageName ] [-debugMode] [-NoWol] [-shutdown] + [-ProgressAction ] [] ``` ### schedule ``` -Send-FogImage [-hostId ] [-StartAtTime ] [-ProgressAction ] - [] +Send-FogImage [-hostId ] [-StartAtTime ] [-imageName ] [-debugMode] [-NoWol] + [-shutdown] [-NoSnapins] [-ProgressAction ] [] ``` ### schedule-byhost ``` -Send-FogImage [-fogHost ] [-StartAtTime ] [-ProgressAction ] - [] +Send-FogImage [-fogHost ] [-StartAtTime ] [-imageName ] [-debugMode] [-NoWol] + [-shutdown] [-NoSnapins] [-ProgressAction ] [] ``` ### now-byhost ``` -Send-FogImage [-fogHost ] [-ProgressAction ] [] +Send-FogImage [-fogHost ] [-imageName ] [-debugMode] [-NoWol] [-shutdown] + [-ProgressAction ] [] ``` ## DESCRIPTION @@ -109,6 +111,84 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -imageName +The name of the image to deploy, uses currently set image if not specified +Tab completion of your fog server's image names if you're on pwsh 7+ + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -debugMode +Switch param to mark the task as a debug task + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWol +Switch param to not use wake on lan in the task, default is to use wake on lan + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -shutdown +Switch param to indicate the host should shutdown at the end of the task instead of restarting. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoSnapins +Switch param for when running a scheduled task, you can choose to set deploysnapins to false so the +assigned snapins aren't auto scheduled too. +Only works in FOG 1.6+ + +```yaml +Type: SwitchParameter +Parameter Sets: schedule, schedule-byhost +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -ProgressAction {{ Fill ProgressAction Description }} diff --git a/docs/commands/Set-FogHostImage.md b/docs/commands/Set-FogHostImage.md new file mode 100644 index 0000000..75974ae --- /dev/null +++ b/docs/commands/Set-FogHostImage.md @@ -0,0 +1,89 @@ +--- +external help file: FogApi-help.xml +Module Name: FogApi +online version: https://fogapi.readthedocs.io/en/latest/commands/Set-FogHostImage +schema: 2.0.0 +--- + +# Set-FogHostImage + +## SYNOPSIS +Function to set a given image object to a host by its id + +## SYNTAX + +``` +Set-FogHostImage [-hostID] [[-fogImage] ] [-ProgressAction ] + [] +``` + +## DESCRIPTION +Function to set a given image object to a host by its id +Will be expanded for better usability in the future + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -hostID +the host id to set an image on + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -fogImage +the image object gotten from get-fogimages + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/docs/commands/Set-FogServerSettings.md b/docs/commands/Set-FogServerSettings.md index a04888a..d9aa500 100644 --- a/docs/commands/Set-FogServerSettings.md +++ b/docs/commands/Set-FogServerSettings.md @@ -96,6 +96,7 @@ Accept wildcard characters: False ### -interactive switch to make setting these an interactive process, if you set no values this is the default +Warning, this can have issues in linux, especially when working in a remote shell, the paste into read-host can behave odd. ```yaml Type: SwitchParameter diff --git a/docs/commands/Test-StringNotNullOrEmpty.md b/docs/commands/Test-StringNotNullOrEmpty.md new file mode 100644 index 0000000..da6e6bb --- /dev/null +++ b/docs/commands/Test-StringNotNullOrEmpty.md @@ -0,0 +1,89 @@ +--- +external help file: FogApi-help.xml +Module Name: FogApi +online version: https://fogapi.readthedocs.io/en/latest/commands/Test-StringNotNullOrEmpty +schema: 2.0.0 +--- + +# Test-StringNotNullOrEmpty + +## SYNOPSIS +Returns true if passed in object is a string that is not null, empty, or whitespace + +## SYNTAX + +``` +Test-StringNotNullOrEmpty [[-str] ] [-ProgressAction ] [] +``` + +## DESCRIPTION +Uses built in string functions to test if a given string is null, empty or whitespace +if it is not any of these things and has valid content, this returns true otherwise false + +## EXAMPLES + +### EXAMPLE 1 +``` +Test-StringNotNullOrEmpty "An example" +``` + +Will return true as it is a valid string with content + +### EXAMPLE 2 +``` +$s = ""; Test-StringNotNullOrEmpty $s; +``` + +Will return false as this is an empty string. + +### EXAMPLE 3 +``` +$str = " "; $str | Test-StringNotNullOrEmpty +``` + +Will return false as this string is just whitespace + +## PARAMETERS + +### -str +String to test + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Meant to simplify input validation tests as test-string $param or $value | test-string is easier to type in an if statement than +doing \[string\]::isnullorempty($str) along with \[string\]::isnullorwhitespace($str) + +## RELATED LINKS diff --git a/docs/commands/index.md b/docs/commands/index.md index e7b608d..31d8b14 100644 --- a/docs/commands/index.md +++ b/docs/commands/index.md @@ -96,6 +96,8 @@ ## [Send-FogWolTask](Send-FogWolTask.md) +## [Set-FogHostImage](Set-FogHostImage.md) + ## [Set-FogInventory](Set-FogInventory.md) ## [Set-FogServerSettings](Set-FogServerSettings.md) @@ -114,6 +116,8 @@ ## [Test-FogVerAbove1dot6](Test-FogVerAbove1dot6.md) +## [Test-StringNotNullOrEmpty](Test-StringNotNullOrEmpty.md) + ## [Update-FogObject](Update-FogObject.md) diff --git a/docs/en-us/FogApi-help.xml b/docs/en-us/FogApi-help.xml index 928d2fe..2607f8b 100644 --- a/docs/en-us/FogApi-help.xml +++ b/docs/en-us/FogApi-help.xml @@ -2121,7 +2121,7 @@ $groupAssocs | ? hostId -eq ((Get-FogHost).id) hostObj - the host to get the model of the inventory object from This is used for the inventory structure of the object It defaults to the current host + the host to get the model of the inventory object from This is used for the inventory structure of the object It defx`aults to the current host Object @@ -2159,7 +2159,7 @@ $groupAssocs | ? hostId -eq ((Get-FogHost).id) hostObj - the host to get the model of the inventory object from This is used for the inventory structure of the object It defaults to the current host + the host to get the model of the inventory object from This is used for the inventory structure of the object It defx`aults to the current host Object @@ -3538,7 +3538,7 @@ $mods -------------------------- EXAMPLE 1 -------------------------- - Get-BcdPxeBootID + Get-WinBcdPxeId Will return the guid of the native pxe boot option if one is found. @@ -5012,6 +5012,51 @@ $mods None + + imageName + + The name of the image to deploy, uses currently set image if not specified Tab completion of your fog server's image names if you're on pwsh 7+ + + String + + String + + + None + + + debugMode + + Switch param to mark the task as a debug task + + + SwitchParameter + + + False + + + NoWol + + Switch param to not use wake on lan in the task, default is to use wake on lan + + + SwitchParameter + + + False + + + shutdown + + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + + SwitchParameter + + + False + ProgressAction @@ -5051,6 +5096,62 @@ $mods None + + imageName + + The name of the image to deploy, uses currently set image if not specified Tab completion of your fog server's image names if you're on pwsh 7+ + + String + + String + + + None + + + debugMode + + Switch param to mark the task as a debug task + + + SwitchParameter + + + False + + + NoWol + + Switch param to not use wake on lan in the task, default is to use wake on lan + + + SwitchParameter + + + False + + + shutdown + + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + + SwitchParameter + + + False + + + NoSnapins + + Switch param for when running a scheduled task, you can choose to set deploysnapins to false so the assigned snapins aren't auto scheduled too. Only works in FOG 1.6+ + + + SwitchParameter + + + False + ProgressAction @@ -5090,6 +5191,62 @@ $mods None + + imageName + + The name of the image to deploy, uses currently set image if not specified Tab completion of your fog server's image names if you're on pwsh 7+ + + String + + String + + + None + + + debugMode + + Switch param to mark the task as a debug task + + + SwitchParameter + + + False + + + NoWol + + Switch param to not use wake on lan in the task, default is to use wake on lan + + + SwitchParameter + + + False + + + shutdown + + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + + SwitchParameter + + + False + + + NoSnapins + + Switch param for when running a scheduled task, you can choose to set deploysnapins to false so the assigned snapins aren't auto scheduled too. Only works in FOG 1.6+ + + + SwitchParameter + + + False + ProgressAction @@ -5117,6 +5274,51 @@ $mods None + + imageName + + The name of the image to deploy, uses currently set image if not specified Tab completion of your fog server's image names if you're on pwsh 7+ + + String + + String + + + None + + + debugMode + + Switch param to mark the task as a debug task + + + SwitchParameter + + + False + + + NoWol + + Switch param to not use wake on lan in the task, default is to use wake on lan + + + SwitchParameter + + + False + + + shutdown + + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + + SwitchParameter + + + False + ProgressAction @@ -5168,6 +5370,66 @@ $mods None + + imageName + + The name of the image to deploy, uses currently set image if not specified Tab completion of your fog server's image names if you're on pwsh 7+ + + String + + String + + + None + + + debugMode + + Switch param to mark the task as a debug task + + SwitchParameter + + SwitchParameter + + + False + + + NoWol + + Switch param to not use wake on lan in the task, default is to use wake on lan + + SwitchParameter + + SwitchParameter + + + False + + + shutdown + + Switch param to indicate the host should shutdown at the end of the task instead of restarting. + + SwitchParameter + + SwitchParameter + + + False + + + NoSnapins + + Switch param for when running a scheduled task, you can choose to set deploysnapins to false so the assigned snapins aren't auto scheduled too. Only works in FOG 1.6+ + + SwitchParameter + + SwitchParameter + + + False + ProgressAction @@ -5354,6 +5616,120 @@ $mods + + + Set-FogHostImage + Set + FogHostImage + + Function to set a given image object to a host by its id + + + + Function to set a given image object to a host by its id Will be expanded for better usability in the future + + + + Set-FogHostImage + + hostID + + the host id to set an image on + + Object + + Object + + + None + + + fogImage + + the image object gotten from get-fogimages + + Object + + Object + + + None + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + hostID + + the host id to set an image on + + Object + + Object + + + None + + + fogImage + + the image object gotten from get-fogimages + + Object + + Object + + + None + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> {{ Add example code here }} + + {{ Add example description here }} + + + + + + Online Version: + https://fogapi.readthedocs.io/en/latest/commands/Set-FogHostImage + + + Set-FogInventory @@ -5537,7 +5913,7 @@ $mods interactive - switch to make setting these an interactive process, if you set no values this is the default + switch to make setting these an interactive process, if you set no values this is the default Warning, this can have issues in linux, especially when working in a remote shell, the paste into read-host can behave odd. SwitchParameter @@ -5599,7 +5975,7 @@ $mods interactive - switch to make setting these an interactive process, if you set no values this is the default + switch to make setting these an interactive process, if you set no values this is the default Warning, this can have issues in linux, especially when working in a remote shell, the paste into read-host can behave odd. SwitchParameter @@ -6756,6 +7132,110 @@ $mods + + + Test-StringNotNullOrEmpty + Test + StringNotNullOrEmpty + + Returns true if passed in object is a string that is not null, empty, or whitespace + + + + Uses built in string functions to test if a given string is null, empty or whitespace if it is not any of these things and has valid content, this returns true otherwise false + + + + Test-StringNotNullOrEmpty + + str + + String to test + + Object + + Object + + + None + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + str + + String to test + + Object + + Object + + + None + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + + Meant to simplify input validation tests as test-string $param or $value | test-string is easier to type in an if statement than doing [string]::isnullorempty($str) along with [string]::isnullorwhitespace($str) + + + + + -------------------------- EXAMPLE 1 -------------------------- + Test-StringNotNullOrEmpty "An example" + + Will return true as it is a valid string with content + + + + -------------------------- EXAMPLE 2 -------------------------- + $s = ""; Test-StringNotNullOrEmpty $s; + + Will return false as this is an empty string. + + + + -------------------------- EXAMPLE 3 -------------------------- + $str = " "; $str | Test-StringNotNullOrEmpty + + Will return false as this string is just whitespace + + + + + + Online Version: + https://fogapi.readthedocs.io/en/latest/commands/Test-StringNotNullOrEmpty + + + Update-FogObject diff --git a/docs/en-us/about_FogApi.help.txt b/docs/en-us/about_FogApi.help.txt index 5c53999..465d0a2 100644 --- a/docs/en-us/about_FogApi.help.txt +++ b/docs/en-us/about_FogApi.help.txt @@ -6,144 +6,181 @@ SHORT DESCRIPTION LONG DESCRIPTION This is a powershell module to make using the Fog Project API even easier. - FOG is an opensource tool for imaging comptuters, this module uses the API - on your internal fog server to perform almost any operation. It can be used - to create more automation or to simply have a command line method of - controlling fog operations. + This module is used to easily run Fog API commands on your fogserver from a + powershell console or script. FOG is an opensource tool for imaging + comptuters, this module uses the API on your internal fog server to perform + almost any operation you can do in the GUI of Fog and provides you with the + ability to extend things further. It can be used to create more automation + or to simply have a command line method of controlling fog operations. This + essentially gives you a crossplatform commandline interface for fog tasks + and makes many things easier to automate. + Docs for this module can be found at https://fogapi.readthedocs.io/en/latest/ + For more information about FOG see + - https://FOGProject.org + - https://docs.fogproject.org + - https://github.com/FOGProject + - https://github.com/FOGProject/fogproject + - https://forums.fogproject.org VERSIONING The versioning of this module follows this pattern - `{Year|Month}.{Major Version}.{Build/Revision #}` + `{Year|Month}.{Major Version}.{Revision #}` Year/Month - This versioning shows you first the Year and Month the module was published, - giving you an idea of when it was last updated. + This versioning shows you first the Year and month this version of the + module was published, giving you an idea of when it was last updated. i.e. + 2208 would be august 2022. Major The Major version follows the typical major versioning where any major changes will increment this version number, especially possible breaking changes or structural changes, etc. -Minor/Build/Revision - Not every revision will be published. This is auto incremented every time - the build script is used to test something. Not all of these changes are - added to git or published so there is often a jump between releases - representing how many builds/revisions have taken place during development. +Minor/Revision + Any time I publish a new version that isn't a major change I'll increment + the revision. This may also be incremented for each build test and increment + by more than one for each published version INSTALLATION - All completed/tested/stable releases of this module will be published to - powershell gallery. You can also download the sources zip from the latest - release and manually build the module with the build.ps1 script + The module can be installed via PowershellGet, PSResourceGet, Chocolatey, or + Manually + +Installation Methods + + To install this module you need at least powershell v3, it was originally + created with 5.1, but now for BEST EXPERIENCE use Powershell Core 7+ to be + able to use tab completion when running Fog 1.6 + To Install this module follow these steps + + INSTALL FROM PSGALLERY + - Easiest method: Install from PSGallery + https://www.powershellgallery.com/packages/FogApi with powershellget or + PSResourceGet - `Install-Module -name FogApi -Scope AllUsers` - + `Install-PSResource -Name FogApi -scope -Scope AllUsers` - updating is then + as easy as - `Update-Module -name FogApi` - `Update-PSResource -Name + FogApi` + + INSTALL WITH CHOCOLATEY + If you have chocolatey package manager, you can use the published package + that manually installs the module the same way the PSGet managers do. + https://community.chocolatey.org/packages/FogApi See https://chocolatey.org + for more information on chocolatey package manager + - Install with chocolatey (will install the module by copying the built + version to the powershell core and windows powershell paths, will remove any + existing versions) - `choco install fogapi -y` - Upgrading is as easy as + (note that you can also use this same command for a new install) - + `choco upgrade fogapi -y` -Requirements - To install this module you need at least powershell v3, was created with 5.1 - and intended to be cross platform compatible with powershell v6 and v7 - To Install this module follow these steps... - -Install From PSGallery - * Easiest method: - Install from PSGallery - via a powershell console with the command * `Install-Module -name fogApi` +Manual Installation + USE ASSETS FROM THE RELEASE + - Use Chocolatey, PackageManagement, Nuget or what have you to install the + chocolatey.nupkg or + .psgallery.nupkg file from the release assets - Extract the *builtModule.zip + from the release and run `import-module` on the resulting folder for a + portable installation. You can also extract to the paths outlined below in + the manual build install steps for a more system wide install + + MANUALLY BUILD THE MODULE + - Manual Method: + - download the zip of this repo and extract it (or use git clone) - Or + clone the repo using your favorite git tool, you just need the FogApi Folder + this readme is in - Run the build.ps1 script + - Copy the built module folder (._module_build) into... - For Windows + Powershell v3-v5.1 - C:\Program + Files\WindowsPowershell\Modules\FogApi - For Powershell Core (pwsh) on + Windows v7+ - C:\Program Files\PowerShell\Modules\FogApi - For + Linux Powershell Core (pwsh) v7+ - + /usr/local/share/powershell/Modules/FogApi - For Mac Powershell Core + (pwsh) v7+ (untested) - /usr/local/share/powershell/Modules/FogApi + - I haven't tested this on a mac, the module folder may be + somewhere else this is based on where it is in other powershell + core installs - Open powershell (as admin recommended) + - Run `Import-Module FogApi` + The module is now installed. UPDATE FROM PSGALLERY `Update-Module FogApi` - Note: Powershell supports side by side versions, after updating you may want - to uninstall old versions with this snippet to avoid conflicting versions. - This needs to be run as an admin to uninstall for all users, you can also - have installed the module per user, in which case you can add the + Note: PowershellGet supports side by side versions, after updating you may + want to uninstall old versions with this snippet to avoid conflicting + versions. This needs to be run as an admin to uninstall for all users, you + can also have installed the module per user, in which case you can add the #find the latest version from the psgallery $latestModule = Find-Module FogApi; #get all installed versions of the module, filter to where the version isn't the latest, and then uninstall each of those (Get-installedmodule FogApi -AllVersions) | Where-Object { $latestModule.version -notmatch $_.version } | Uninstall-Module -Force -Manual Installation - * Manual Method: - * download the zip of this repo and extract it * Or clone the repo using - your favorite git tool, you just need the FogApi Folder this readme is in * - Run the build.ps1 script - * Copy the built module folder (`$env:userprofile\moduleBuild\fogAPI`) into... - * For Windows Powershell v3-v5.1 * C:\Program - Files\WindowsPowershell\Modules * For Windows Powershell v6+ * - C:\Program Files\PowerShell\6-preview\Modules * 6-Preview may - need to be replaced with whatever current version you have installed * - For Linux Powershell v6+ * - /opt/microsoft/powershell/6.1.0-preview.2/Modules * - 6.1.0-preview.2 may need to be replaced with whatever current version you - have installed * For Mac Powershell v6+ (untested) * - /usr/local/microsoft/powershell/6.x/Modules * 6.x should be - replaced with whatever most current version you are using * I - haven't tested this on a mac, the module folder may be somewhere else - this is based on where it is in other powershell 6 installs * Open a - powershell window - * Run `Import-Module FogApi` - You can also import the built module from its build path, the above method - makes it available by name - The module is now installed. - USING THE MODULE + You can use `Set-FogServerSettings` to set your fogserver hostname and api keys. The first time you try to run a command the settings.json file will - automatically open in notepad on windows, nano on linux, or TextEdit on Mac + automatically open if it isn't already configured in notepad on windows, + nano on linux, or TextEdit on Mac You can also open the settings.json file and edit it manually before running - your first command. The default settings are explanations of where to find - the proper settings since json can't have comments You can also use - Set-FogServerSettings to set the api tokens for the sever and your user in - one command. You first need to obtain these keys/tokens from the fog web - gui. replace fog-server in the below example links with the name of your - internal fog server if different - - The fog API token is found at - https://fog-server/fog/management/index.php?node=about&sub=settings under - API System - - The fog user api token found in the user settings - https://fog-server/fog/management/index.php?node=user&sub=list select your - api enabled used and view the api tab - - the fog server name is the name of your fog server, it defaults to - `fog-server` but can be updated if you aren't using that default name as the - hostname or an alias - Once you've obtained these you can run the command like this to save your - fog api settings for the current user in a json file under - `$home/APPDATA/Roaming/FogApi/api-settings.json` (this appdata path is - created in linux/mac home folders) - - Set-FogServerSettings -fogApiToken "SuperLongPastedFogToken" -fogUserToken "SuperLongPastedUserToken" -fogServer "fog-server-hostname" - + your first command, but it's best to use the `Set-FogServerSettings + -interactive` function and switch for first time setup. The default settings + in `settings.json` are explanations of where to find the proper settings + since json can't have comments Once the settings are set you can have a jolly good time utilzing the fog - documentation found - here - that was used to model the parameters + documentation found here + https://news.fogproject.org/simplified-api-documentation/ that was used to + model the parameters i.e. - Get-FogObject has a type param that validates to object, - objectactivetasktype, and search as those are the options given in the + `Get-FogObject` has a type param that validates to `object, + objectactivetasktype, and search` as those are the options given in the documentation. Each of those types validates (which means autocompletion) to the core types listed in the documentation. So if you typed in - `Get-FogObject -Type object -Object h` and then started hitting tab, it + `Get-FogObject -Type object -Object h` and then started hitting tab, it would loop through the possible core objects you can get from the api that - start with 'h' such as history, host, etc. - Unless you filter a get with a json body it will return all the results into - a powershell object. That object is easy to work with to create other - commands. Note: Full Pipeline support will come at a later time i.e. - `$hosts = Get-FogObject -Type Object -CoreObject Host ` Does a GET call on - http://fog-server/fog/host - to list all hosts Now you can search all your hosts for the one or ones - you're looking for with powershell. maybe you want to find all the hosts - with 'IT' in the name (note '?' is an alias for Where-Object) `$ITHosts = - $hosts.hosts | ? name -match 'IT';` + start with `h` such as history, host, etc. + Unless you filter a GET with a json body it will return all the results into + a powershell object. That object is easy to work with to create other + commands. Note: Full Pipeline support will come at a later time i.e. + + hosts = Get-FogObject -Type Object -CoreObject Host # calls GET on {your-fog-server}/fog/host to list all hosts + + Now you can search all your hosts for the one or ones you are looking for + with powershell maybe you want to find all the hosts with ''IT'' in the name + (note `?` is an alias for `Where-Object`) + + $ITHosts = $hosts.data | ? name -match ''IT''; + Now maybe you want to change the image all of these computers use to one - named 'IT-Image' You can edit the object in powershell with a foreach-object - ('%' is an alias for foreach-object) `$updatedITHosts = $ITHosts | % { - $_.imagename = 'IT-image'}` + named ''''IT-Image'''' You can edit the object in powershell with a + foreach-object (`%` is an alias for `foreach-object`) + + #get the id of the image by getting all images and finding the one with the IT-image name + $image = Get-FogImages | ? name -eq "IT-image" + $updatedITHosts = $ITHosts | % { $_.imageid = $image.id} + Then you need to convert that object to json and pass each object into one - api call at a time. Which sounds complicated, but it's not, it's as easy as + api call at a time. Which sounds complicated, but it's not, it's as easy as - $updateITHosts | % { - $jsonData = $_ | ConvertTo-Json; - Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData $jsonData; - #successful result of updated objects properties - #or any error messages will output to screen for each object + $updatedITHosts | % { + Update-FogObject -Type object -CoreObject host -objectID $_.id -jsonData ($_ | ConvertTo-Json); } This is just one small example of the limitless things you can do with the - api and powershell objects. - see also the fogforum thread for the module + api and powershell objects. There are also many ''helper'' functions that + make various operations easier. i.e. Maybe you want to create a host and + deploy that "IT-image" image to it. + + #create the host + New-FogHost -name "test-host" -macs "01:23:45:67:89:00" + + #add the image to the host + $foghost = get-foghost -hostname "test-host"; + $image = Get-FogImages | ? name -eq "IT-image" + $foghost.imageid = $image.id; + $jsonData = $fogHost | ConvertTo-Json; + Update-FogObject -Type object -CoreObject host -objectID $foghost.id -jsonData jsonData; + + #start the image task on the host now + get-foghost -hostname "test-host" | send-fogimage + + #alternatively, schedule the image for later, like 10pm tomorrow + get-foghost -hostname "test-host" | send-fogimage -StartAtTime (Get-Date 10pm).AddDays(1) + +Additional info + See also the fogforum thread for the module https://forums.fogproject.org/topic/12026/powershell-api-module/2 diff --git a/docs/index.md b/docs/index.md index 16380d3..6c31205 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,10 +17,22 @@ You can also find the published version of this module in the [Powershell Galler ## Configuring the api tokens -In order to use the api, you need to have it enabled in the fog server and you need the api token for the server and the one for your user. +In order to use the api, you need to have it enabled in the fog server and you need the api token for the server and the one for your user. You can do this with `Set-FogServerSettings` i.e. -The first time you try to run a command the settings.json file will automatically open -in notepad on windows, nano on linux, or TextEdit on Mac +``` +Set-FogServerSettings -fogApiToken "SuperLongPastedFogToken" -fogUserToken "SuperLongPastedUserToken" -fogServer "fog-server-hostname" +``` + +or you can try + +``` +Set-FogServerSettings -interactive +``` + +If you don't configure it with that command, then the first time you try to run a command the settings.json file will automatically open +- in vscode if present or notepad if it's not on windows +- nano if present or vi if it's not on linux +- or TextEdit on Mac You can also open the settings.json file and edit it manually before running your first command. The default settings are explanations of where to find the proper settings since json can't have comments You can also use Set-FogServerSettings to set the api tokens for the sever and your user in one command. You first need to obtain these keys/tokens from the fog web gui. replace fog-server in the below example links with the name of your internal fog server if different @@ -29,7 +41,7 @@ You can also use Set-FogServerSettings to set the api tokens for the sever and y - The fog user api token found in the user settings https://fog-server/fog/management/index.php?node=user&sub=list select your api enabled used and view the api tab - the fog server name is the name of your fog server, it defaults to `fog-server` but can be updated if you aren't using that default name as the hostname or an alias -Once you've obtained these you can run the command like this to save your fog api settings for the current user in a json file under `$home/APPDATA/Roaming/FogApi/api-settings.json` (this appdata path is created in linux/mac home folders) +Once you've obtained these you can run the command like this to save your fog api settings for the current user in a json file under `$env:APPDATA/FogApi/api-settings.json` if running in Windows, it's at `$home/.FogApi/api-settings.json` if running in Linux or Mac ``` Set-FogServerSettings -fogApiToken "SuperLongPastedFogToken" -fogUserToken "SuperLongPastedUserToken" -fogServer "fog-server-hostname" diff --git a/invoke-modulebuild.ps1 b/invoke-modulebuild.ps1 index 30a43b6..6e32f5e 100644 --- a/invoke-modulebuild.ps1 +++ b/invoke-modulebuild.ps1 @@ -43,6 +43,8 @@ [CmdletBinding()] Param() +Import-Module .\BuildHelpers.psm1 + $moduleName = 'FogApi' $modulePath = "$PSScriptRoot\$moduleName"; @@ -121,4 +123,12 @@ if ($null -ne $PrivateFunctions) { $manifest = "$PSScriptRoot\$moduleName\$moduleName.psd1" Copy-Item $manifest "$buildPth\$moduleName.psd1"; -Update-ModuleManifest -Path "$buildPth\$moduleName.psd1" -RootModule "$moduleName.psm1" -FunctionsToExport $PublicFunctions.BaseName \ No newline at end of file + +if (Get-Command Update-PSModuleManifest) { + Update-PSModuleManifest -Path "$buildPth\$moduleName.psd1" -RootModule "$moduleName.psm1" -FunctionsToExport $PublicFunctions.BaseName +} else { + "PSResourceGet version of update manifest not found, reverting to psget version, may cause issues with choco nuspec" | out-host; + Update-ModuleManifest -Path "$buildPth\$moduleName.psd1" -RootModule "$moduleName.psm1" -FunctionsToExport $PublicFunctions.BaseName +} +Set-EmptyExportArray -psd1Path "$buildPth\$moduleName.psd1" -ExportType Cmdlets; +Set-EmptyExportArray -psd1Path "$buildPth\$moduleName.psd1" -ExportType Variables;