Passing $Credential object as parameter to function

Hi Guys,

Easy question - what is the problem here? I cannot pass $Creds object to function - it doesn’t see it in function. Object is created outside.

It opens PSCreditional pop-up.


function Read($Computer,$Creds)
Write-Host “This is COMPUTER VAR:” $Computer
Write-Host “This is CREDS VAR:” $Creds
Invoke-Command -Credential $Creds -ComputerName $Computer -ScriptBlock {Get-Service WINRM}
Return $Results

$Pass=ConvertTo-SecureString “$Password” -AsPlainText -Force
$Creds=New-Object System.Management.Automation.PSCredential($User,$Pass)

$Computer = “SOME IP”
Read “$Computer” “$Creds”

The biggest issue is wrapping qoutes around you variables (e.g. “$Creds”), but there were several other things like it appeared you were trying to do a string format on the Write-Host, but there was a missing -f and returning $results (the ‘return’ keyword is not required) but not assigning a variable. Try starting with something like this:

function Get-WinRm {
    param (

    Write-Verbose (“This is COMPUTER VAR: {0}” -f $Computer)
    Write-Verbose (“This is CREDS VAR: {0}” -f $Creds.UserName)
    $results = Invoke-Command -Credential $Creds -ComputerName $Computer -ScriptBlock {Get-Service WINRM}

$Pass=ConvertTo-SecureString “$Password” -AsPlainText -Force
$Creds=New-Object System.Management.Automation.PSCredential($User,$Pass)

$Computer = “computer123”
Get-WinRm -Computer $Computer -Creds $Creds -Verbose

Also, naming the function Read is asking for issues as it’s probably a reserved phrase or word, so name your function like other cmdlets is a best practice verb-noun.

Hi Rob,

Thanks for your time. The reason was “$Creds” - quotes around the variable. Other mistakes were during “fixing\stage” :slight_smile:

I thought that I can use quotes there - especially it works with $Computer variable - I don’t understand why I don’t work with $Creds.

Thanks again - helped a lot :slight_smile: