使用凭据启动进程时出现问题

Problems starting processes with credentials

我在让 DSC(在 PowerShell 4 中)以另一个用户身份启动进程时遇到问题。这是一个示例配置:

$configData = @{
    AllNodes = @(
        @{
            NodeName = 'localhost'
            PSDscAllowPlainTextPassword = $true
        }
    )
}

Configuration DSC_AttribProblem {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [PsCredential] $credential
    )

    Node "localhost" {
        File CreateTestFolder {
            Ensure = "Present"
            Type = "Directory"
            DestinationPath = "C:\DSC_Test"
        }

        Script CreateTestFile {
            SetScript = {
                $sw = New-Object System.IO.StreamWriter("C:\DSC_Test\TestFile.txt")
                $sw.Close()
            }
            TestScript = {
                return Test-Path "C:\DSC_Test\TestFile.txt"
            }
            GetScript = {
            }
            DependsOn = "[File]CreateTestFolder"
        }

        WindowsProcess Attrib {
            Path = "C:\Windows\System32\attrib.exe"
            Arguments = "-A C:\DSC_Test\TestFile.txt"
            Credential = $credential
            DependsOn = "[Script]CreateTestFile"
        }
    }
}

请注意,这只是一个示例,用于演示 运行 具有凭据的可执行文件的问题。 (真实案例也需要重定向标准输出。)

Attrib 步骤失败并出现此错误:

PowerShell provider MSFT_ProcessResource  failed to execute
Set-TargetResource functionality with error message: Failure starting
process matching path 'C:\Windows\System32\attrib.exe'. Message:
"Failed  to wait for processes to start". 
    + CategoryInfo          : InvalidOperation: (:) [], CimException
    + FullyQualifiedErrorId : ProviderOperationExecutionFailure
    + PSComputerName        : localhost

我在 http://powershell.org/wp/forums/topic/running-windowsprocess/ 发现了一个类似的问题,但没有真正回答。

在幕后,我可以想象这是由于 does windows have a limitation when a process started by a scheduled task under one set of creds runs another program under a different set of Creds and Why is this process crashing as soon as it is launched?。那么,您究竟是如何解决这类问题的呢? (即使为此类问题编写自定义资源,我 运行 也遇到了问题。)

为了让它工作,我的第一次尝试是使用 LogonUser,然后使用 .NET Process class 创建新进程(它很好地支持重定向)。 LogonUser 部分基于 https://gist.github.com/idavis/856603 (for impersonating within a scriptblock) and http://poshcode.org/1856(它似乎可以更好地处理我的情况)。这一切都包含在自定义资源中。

后来我发现,虽然这实现了本地拥有凭据的目标,但它不适用于通过网络访问文件。那时我选择了使用 CreateProcessAsUser as in DSC powershell xwindowsprocess to execute batch file under different user account. Although the comments on that thread were inconclusive to me, I came up with a solution that worked, and posted it to this Gist page 的替代方法,包括自定义 DSC 资源和 PowerShell 模块。该解决方案还有一个替代实现,可以在涉及 CreateProcessWithLogonW() 时进行交换,但在我的测试中这不起作用。