1

I want to query a server for, say memory

gwmi win32_freephysicalmemory -computername server1 -credential $cred

I know about get-credentials and also constructing an pscredential-object, but i want to first try to query with my current credentials, and if i get unauthorizedexception ill prompt for new credentials with get-credentials. this way i could run the script from either my workstation or some server (i dont use the same creds)

i think i initially need to feed $cred with my current credentials and then change it in the catchblock if it fails, but how do i dump my logged on credentials to an pscreential-object?

  • Tried to set $cred to [System.net.credentialcache]::DefaultCredential but since it returns an interface, im not sure if its possible to cast to a pscredential-object somehow – user2589164 Jul 16 '13 at 22:09

1 Answers1

1

Have you tried [System.Management.Automation.PSCredential]::Empty?

Are you using PS 3.0? You can set of default parameter value using

$PSDefaultParameterValues.Add('Get-WMIObject:Credential',[System.Management.Automation.P
SCredential]::Empty)

And, when this fails, you can look for the Credential Parameter.

ravikanth
  • 24,922
  • 4
  • 60
  • 60
  • Right on! exactly what i was looking for.. when i pass a cred-object to get-wmi as returned from Empty(), Powershell (or dotnet) seems to use my logged on credentials since the object is empty? or something, just as good. – user2589164 Jul 17 '13 at 15:29
  • 1
    `$creds = [System.Management.Automation.PSCredential]::Empty try{ Get-WmiObject -Class Win32_PhysicalMemory -ComputerName server -Credential $creds } catch [System.UnauthorizedAccessException] { Write-Warning "Not Authorized" $creds = Get-Credential -Message "Give me other credentials" } finally { "retrying...`n" Get-WmiObject -Class Win32_PhysicalMemory -ComputerName server -Credential $creds }` – user2589164 Jul 17 '13 at 15:34