Search code examples
powershellworkflow

Pass credentials in powershell Workflow


I have a powershell workflow to run on servers remotely but having issue to pass the credentials in workflow. The password should be from user at the time of execution.

workflow Gethost{
    param(
        [string[]]$Servers
    )
   $credential = (Get-Credential)
    foreach -parallel ($server in $Servers) {
        $session = inlineScript{New-PSSession -ComputerName $using:server -Credential $using:credential} 
        $id = $session.id
        inlineScript{Invoke-Command -ComputerName $using:server -Credential $using:credential -Filepath C:\Checkhost.ps1}
        inlineScript {Exit-PSSession}
        inlineScript{Remove-PSSession -id $using:id}
    }
}

Solution

  • You cannot use Get-Credential cmdlet inside a PowerShell workflow. Only some limited set of cmdlets can be used inside a workflow. You can get the credential outside and pass that using a parameter.

    workflow Gethost{
        param(
            [string[]]$Servers,
            [PSCredential]$Credential
        )       
        foreach -parallel ($server in $Servers) {
        $session = inlineScript{New-PSSession -ComputerName $using:server -Credential $using:credential} 
        $id = $session.id
        inlineScript{Invoke-Command -ComputerName $using:server -Credential $using:credential -Filepath C:\Checkhost.ps1}
            inlineScript {Exit-PSSession}
            inlineScript{Remove-PSSession -id $using:id}
        }
    }
    

    See here for the restrictions in Workflow