How to upgrade windows service using PowerShell Desired State Configuration

百般思念 提交于 2019-12-08 02:43:21

问题


Below is an example of my config, install works fine but if I replace '\\BuildMachine\Output\MyService.exe' with a newer version DSC fails with file in use errors. What is the correct way to upgrade a windows service using DSC? Thanks.

Configuration ServiceTestConfiguration {
    Import-DscResource -ModuleName PSDesiredStateConfiguration
    Import-DscResource -ModuleName xPSDesiredStateConfiguration

    Node localhost
    {
        File EnsureLatestServiceExist {
            Ensure = 'Present'
            Type = 'File'
            Checksum = 'ModifiedDate'
            SourcePath = '\\BuildMachine\Output\MyService.exe'
            DestinationPath = 'c:\MyService\MyService.exe'
        }

        xService EnsureServiceStarted {
            Ensure = 'Present'
            DependsOn = '[File]EnsureLatestServiceExist'
            Name = 'MyService'
            DisplayName = 'My Service'
            Description = 'My Service'
            Path = 'c:\MyService\MyService.exe'
            StartupType = 'Automatic'
            State = 'Running'
        }
    }
}

回答1:


I have not found a built-in method to accomplish this, but the Script resource lets you pretty much do anything.

Add a Script resource that checks to see if the remote (source) file was updated. If the remote file was updated, stop the service. Make the File resource depend upon the Script resource so that it runs before the file copy. The Service resource will run last and start the service again.

Script StopServiceCheck
{
    SetScript = 
    {
        Stop-Service -Name ServiceName -Force
    }
    TestScript = 
    {
        $LocalFile = "C:\Path\To\Local.exe"
        $RemoteFile = "\\Path\To\Remote.exe"

        #Returns false if the remote file is newer than the local file or use -eq
        return ((Get-Item -Path $RemoteFile).LastWriteTime -le (Get-Item -Path $LocalFile).LastWriteTime) 
    }
    GetScript = 
    {
        $LocalFile = "C:\Path\To\Local.exe"
        $RemoteFile = "\\Path\To\Remote.exe"
        $return = @{Result = "Executables match"}

        If ((Get-Item -Path $RemoteFile).LastWriteTime -gt (Get-Item -Path $LocalFile).LastWriteTime) { $return.Result = "Remote file is newer" }

        return $return
    }
}



回答2:


Open source PowerShell module Carbon has custom DSC Resource for this very purpose: http://get-carbon.org/Carbon_Service.html




回答3:


It's not one desired state, it's two desired states.

The first desired state is: The service is properly shut down and ready for maintenance.

The second desired state is: The service is active and running using the latest version of the code.

Write it as two scripts.



来源:https://stackoverflow.com/questions/35302781/how-to-upgrade-windows-service-using-powershell-desired-state-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!