I'm trying to create a module with a bunch of functions, but I'm stuck with a problem: sometimes I need to run functions with a different from current credentials. But the thing is: I don't want to ask for credentials if I didn't specify a username. Like this:
function MyFunction ($ComputerName='localhost', $UserName) {
if ($UserName) {
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Credential $UserName
} else {
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName
}
}
Can I somehow get rid of the if
statement? Can I just let the function use current credentials unless I specify -UserName
?
If I leave it like this:
Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Credential $UserName
and call a function without specifying -UserName
, it asks for credentialls every time. Yes, it uses current if I close the 'get-cred' box, but it's not what I want.