Author Posts

November 15, 2014 at 6:37 pm

Hello,
I am curious if it is possible is there a way to add -credentials as a common param to my scripts ?
I looked at the common param from tech net but it does not list -credentials as a option.
what I am trying to do is basically ad a run as prompt ( for lack of a batter term) to my scripts.
thanks for the help.

November 15, 2014 at 7:04 pm

Hi Brian,

It is not a common parameter because not every script or function requires credentials but you can easily add the -Credential parameter if needed.

Param
(
    [Parameter(Mandatory = $true)]
    [String] $ComputerName,

    [Parameter(Mandatory = $true)]
    [PSCredential] $Credential
)

Connect-Server -Credential $Credential

Best,
Daniel

November 16, 2014 at 4:56 pm

The problem with the [PSCredential] type accelerator is that this will force the parameter to only accept a credential object as it's value. In the interest of flexibility there is actually a credential parameter attribute you can use. This way you can either accept a credential object or a string as the argument to the parameter. If a string is specified the user is prompted for the password:

Param
(
    [Parameter(Mandatory = $true)]
    [String]
    $ComputerName,
 
    [Parameter(Mandatory = $true)]
    [System.Management.Automation.Credential()]
    $Credential
) 

Usage:

Connect-Server -Credential $Credential

Or:

Connect-Server -Credential username

November 19, 2014 at 5:50 pm

Daniel & Matt,
Thank you both for your responses, however neither solution was able to meet my needs. Maybe some more details is needed.
I am trying to make it so my scripts can be run from a powershell session but still allow you to input a privileged access accounts when running a script.
I know I can do with the sysinternals Shellrunas.exe but I would much rather do it within powershell.
when I tried the scripts above I was not able to run my script with an elevated account.
to test it I loaded a PS session with my normal account and then Tried both methods from with in my script ( which was a simple check for services script that i knew would not work with my normal account as we disable PSremoting for normal users)
I did try several times to make sure I did not mistype my user name or password.
Is what I am asking for possible within powershell 2.0?

November 19, 2014 at 7:06 pm

Update
actually i figured it out.

#Lose example but you get the Idea
Function Get-servicesRemote{

[CmdletBinding()]

Param
(
[Parameter(Mandatory = $true)]
[String]
$ComputerName,

[Parameter(Mandatory = $true)]
[System.Management.Automation.Credential()]
$Credential
)

invoke-comand -computername $computername -scriptblock{get-service} -Credential $Credential

#Thank you Matt and Daniel for helping to get me in the right direction