NN.MrfkCommands.psm1

#Region './Private/Register-Autofill.ps1' 0
$Splat = @{
    "CommandName" = "New-ShippingLabel"
    "ParameterName" = "location"
    "ScriptBlock" = {
        param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

        $AllLocationNames = (Get-SnipeLocations).name | Sort-Object
        $AllLocationNames.Where({
            $_ -like "$wordToComplete*"
        }).ForEach({
            "`"$_`""
        })
    }
}
Register-ArgumentCompleter @Splat
#EndRegion './Private/Register-Autofill.ps1' 16
#Region './Public/Get-MrfkAdmCreds.ps1' 0
function Get-MrfkAdmCreds {
    param (
        [string]$admCredsPath = "$env:USERPROFILE\.creds\MRFK\adm_creds.xml"
    )

    if (!(Test-Path $admCredsPath)) {
        New-MrfkAdmCreds
    }
    
    Import-Clixml $admCredsPath
}
#EndRegion './Public/Get-MrfkAdmCreds.ps1' 12
#Region './Public/Get-MrfkComputerInfo.ps1' 0
function Get-MrfkComputerInfo {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ParameterSetName="Get computer by hostname")]$Hostname,
        [Parameter(Mandatory,ParameterSetName="Get computers by username")]$Username,
        $MECMNameSpace = "root/SMS/site_PS1",
        $MECMHost = "sccm-ps.intern.mrfylke.no",
        $DC = "dc01.intern.mrfylke.no"
    )

    begin {
        $RequiredModulesNameArray = @("NN.WindowsSetup")
        $RequiredModulesNameArray.ForEach({
            if (Get-InstalledModule $_ -ErrorAction SilentlyContinue) {
                Import-Module $_ -Force
            } else {
                Install-Module $_ -Force
            }
        })

        #Install RSAT
        Install-RSAT -WUServerBypass
    }

    process {
        $ComputerExportArr = New-Object -TypeName System.Collections.ArrayList

        $splat = @{
            "Credential" = Get-MrfkAdmCreds
            "ComputerName" = $MECMHost
            "ErrorAction" = "Stop"
        }
        $CimSession = New-CimSession @splat

        switch ($PsCmdlet.ParameterSetName) {
            "Get computer by hostname" {
                [array]$HostnameArr = $Hostname
            }
            "Get computers by username" {
                $splat = @{
                    "Query" = "Select * from SMS_R_System where LastLogonUserName = `"$Username`""
                    "Namespace" = $MECMNameSpace
                    "CimSession" = $CimSession
                }
                [array]$HostnameArr = (Get-CimInstance @splat).Name
            }
        }

        $HostnameArr.ForEach({
            $splat = @{
                "Query" = "Select * from SMS_R_System where name = `"$_`""
                "Namespace" = $MECMNameSpace
                "CimSession" = $CimSession
            }
            $MecmComputer = Get-CimInstance @splat
            
            $splat = @{
                "Query" = @"
select distinct SMS_G_System_PROCESSOR.*
from SMS_R_System
inner join SMS_G_System_PROCESSOR
on SMS_G_System_PROCESSOR.ResourceID = SMS_R_System.ResourceId
where ResourceId = $($MecmComputer.ResourceId)
"@

                "Namespace" = $MECMNameSpace
                "CimSession" = $CimSession
            }
            $CPUInfo = Get-CimInstance @splat
            
            $splat = @{
                "Query" = @"
Select * from SMS_G_System_Computer_System_Product
where ResourceId = $($MecmComputer.ResourceId)
"@

                "Namespace" = $MECMNameSpace
                "CimSession" = $CimSession
            }
            $ModelInfo = Get-CimInstance @splat
            
            $ADComputer = Get-ADComputer $_
            
            $splat = @{
                "Filter" = {objectclass -eq "msFVE-RecoveryInformation"}
                "SearchBase" = $ADComputer.DistinguishedName
                "Properties" = "msFVE-RecoveryPassword"
                "Credential" = Get-MrfkAdmCreds
                "Server" = $DC
            }
            $BitlockerRecoveryKeys = (Get-ADObject @splat)."msFVE-RecoveryPassword"
            
            if ($MecmComputer.agentname) {
                $HeartbeatIndex = $MecmComputer.agentname.IndexOf("Heartbeat Discovery")
                $LastHeartbeat = $MecmComputer.agenttime[$HeartbeatIndex]
            }
            
            $null = $ComputerExportArr.Add(
                [PSCustomObject]@{
                    "Hostname" = $_
                    "LastLoggedOnUser" = $MecmComputer.LastLogonUserName
                    "MACAddresses" = $MecmComputer.MACAddresses
                    "Model" = $ModelInfo.Name
                    "CPUName" = $CPUInfo.Name
                    "SN" = $ModelInfo.IdentifyingNumber
                    "LastHeartbeat" = $LastHeartbeat
                    "BitlockerRecoveryKeys" = $BitlockerRecoveryKeys
                }
            )
        })
        $ComputerExportArr
    }
}
#EndRegion './Public/Get-MrfkComputerInfo.ps1' 112
#Region './Public/Get-MrfkUserInfo.ps1' 0
function Get-MrfkUserInfo {
    [CmdletBinding()]
    param (
        [Parameter(ParameterSetName="username")][string]$Username,
        [Parameter(ParameterSetName="displayname")][string]$DisplayName,
        [Parameter(ParameterSetName="mobilephone")][string]$MobilePhone,
        [switch]$IncludeComputerInfo,
        [switch]$ExpandComputerInfo
    )

    begin {
        $RequiredModulesNameArray = @("NN.WindowsSetup")
        $RequiredModulesNameArray.ForEach({
            if (Get-InstalledModule $_ -ErrorAction SilentlyContinue) {
                Import-Module $_ -Force
            } else {
                Install-Module $_ -Force
            }
        })

        #Install RSAT
        Install-RSAT -WUServerBypass
    }

    process {
        switch ($PsCmdlet.ParameterSetName) {
            "username" {
                $filter = "SamAccountName -like `"$Username`""
            }
            "displayname" {
                $filter = "DisplayName -like `"$DisplayName`""
            }
            "mobilephone" {
                $filter = "MobilePhone -like `"$MobilePhone`""
            }
        }

        #Install required modules
        $RequiredModulesNameArray = @('NN.MrfkCommands')
        $RequiredModulesNameArray.ForEach({
            if (Get-InstalledModule $_ -ErrorAction SilentlyContinue) {
                Import-Module $_ -Force
            } else {
                Install-Module $_ -Force -Repository PSGallery
            }
        })

        #Get userinfo of the ADusers
        $ADUser = Get-ADUser -filter $filter -Properties MobilePhone,DisplayName | Select-Object @(
            "DisplayName","Name","SamAccountName","MobilePhone",
            "UserPrincipalName","Enabled","DistinguishedName"
        )

        #Pick an ADUser if we get multiple hits on the search query
        while ($ADUser -is [array]) {
            $splat = @{
                "Title" = "Found multiple hits on the input. Please select the user."
                "OutputMode" = "Single"
            }
            $SelectedADUser = $ADUser | Out-GridView @splat

            if ($SelectedADUser) {
                $ADUser = $SelectedADUser
            }
        }

        if ($IncludeComputerInfo) {
            $ComputerExportArr = Get-MrfkComputerInfo -Username $ADUser.SamAccountName
            if (!$ExpandComputerInfo) {
                $ADUser | Add-Member -MemberType NoteProperty -Name "Computers" -Value $ComputerExportArr
            }
        }

        #Post output
        $ADUser
        if ($ExpandComputerInfo) {
            $ComputerExportArr
        }
    }
}
#EndRegion './Public/Get-MrfkUserInfo.ps1' 81
#Region './Public/New-MrfkAdmCreds.ps1' 0
function New-MrfkAdmCreds {
    param (
        [string]$admCredsPath = "$env:USERPROFILE\.creds\MRFK\adm_creds.xml"
    )

    #Create parent folders for the file
    $admCredsDir = $admCredsPath.Substring(0, $admCredsPath.lastIndexOf('\'))
    if (!(Test-Path $admCredsDir)) {
        $null = New-Item -ItemType Directory $admCredsDir
    }
    
    #Create adm_creds file
    Get-Credential -Message "Enter your mrfk admin credentials" | Export-Clixml $admCredsPath
}
#EndRegion './Public/New-MrfkAdmCreds.ps1' 15
#Region './Public/New-MrfkShippingLabel.ps1' 0
function New-MrfkShippingLabel {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ValidateScript({
            $_ -in (Get-SnipeLocations).name
        })][string]$location,
        [Parameter(Mandatory)][string]$displayname,
        [int]$copies = 1,
        [string]$mobile,
        [string]$PrinterNetworkPath = "\\sr-safecom-sla1\PR-STORLABEL-SSDSK"
    )
    
    begin {
        $RequiredModulesNameArray = @("NN.SnipeIT","NN.WindowsSetup")
        $RequiredModulesNameArray.ForEach({
            if (Get-InstalledModule $_ -ErrorAction SilentlyContinue) {
                Import-Module $_ -Force
            } else {
                Install-Module $_ -Force
            }
        })

        #Install RSAT
        Install-RSAT -WUServerBypass
    }
    
    process {
        #Get the selected locations address
        $locationResult = Get-SnipeLocations -name $location

        $locationName = $locationResult.address
        $address = $locationResult.address2
        $postalCode = $locationResult.zip
        $city = $locationResult.city

        if (!$mobile) {
            #Search AD for phonenumber
            [string]$mobile = (Get-ADUser -Filter {DisplayName -like $displayname} -Properties mobile).mobile
        }

        if ($location) {
            #Get current default printer
            $defaultPrinter = (Get-CimInstance -Class Win32_Printer).where({$_.Default -eq $true}).Name

            #Set printer named PR-STORLABEL-SSDSK to default printer
            if (!(Get-Printer -Name $PrinterNetworkPath -ErrorAction SilentlyContinue)) {
                (New-Object -ComObject WScript.Network).AddWindowsPrinterConnection($PrinterNetworkPath)
            }
            (New-Object -ComObject WScript.Network).SetDefaultPrinter($PrinterNetworkPath)

            #Create new Word document
            $WordObj = New-Object -ComObject Word.Application
            $null = $WordObj.Documents.Add()

            #Set page size and margins
            $WordObj.Selection.PageSetup.PageHeight = "192mm"
            $WordObj.Selection.PageSetup.PageWidth = "102mm"
            $WordObj.Selection.PageSetup.TopMargin = "12,7mm"
            $WordObj.Selection.PageSetup.BottomMargin = "12,7mm"
            $WordObj.Selection.PageSetup.LeftMargin = "12,7mm"
            $WordObj.Selection.PageSetup.RightMargin = "12,7mm"

            #Insert content
            $WordObj.Selection.Font.Bold = 1
            $WordObj.Selection.TypeText("Mottaker:
            "
)
            $WordObj.Selection.Font.Bold = 0
            $WordObj.Selection.TypeText("$displayname
            $mobile"
)
            $WordObj.Selection.TypeParagraph()
            $WordObj.Selection.Font.Bold = 1
            $WordObj.Selection.TypeText("Addresse:
            "
)
            $WordObj.Selection.Font.Bold = 0
            $WordObj.Selection.TypeText("$locationName
            $address
            $postalCode $city"
)

            (1..$copies).ForEach({
                #Send To Default Printer
                $WordObj.PrintOut()
            })

            #Change default printer back to the previous value
            (New-Object -ComObject WScript.Network).SetDefaultPrinter("$defaultPrinter")

            #Close File without saving
            $WordObj.ActiveDocument.Close(0)
            $WordObj.quit() 
        }
    }
}
#EndRegion './Public/New-MrfkShippingLabel.ps1' 93