Pass password into -credential - powershell

I am trying to login into a computer.
I have been playing with various versions and determined that my past questions were when I didn't know what I was really trying to do.
I discovered that I was on the incorrect PC when running the script.
When I now run the script on the correct PC, the following code requires me to enter the password.
gwmi win32_service –credential domain\username –computer PC#
Is there a way with my current script above, to enforce the username and password without user entry? I have to do this for 100s of PCs so I want to loop through all of them without the user having to input the password 100s of times.
I tried doing the following:
$Username = 'domain\username'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString = $pass
# Users you password securly
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString –computer PC#
However, I get an error of A parameter cannot be found that matches parameter name 'computer'.
also tried:
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
# Sets yous credentials to be used
#$RemoteConn = New-PSSession -ComputerName "PC#" -Credential $MySecureCreds -Authentication default
but the RemoteConn didn't work

WOW I figured it out thanks to https://social.technet.microsoft.com/forums/windowsserver/en-US/440ab7ed-7727-4ff7-a34a-6e69e2dff251/getwmiobject-prompting-for-password-issues
So I didn't realize I can use the $MySecureCreds as the -credential
ANSWER:
$Username = 'domain\username'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString = $pass
# Users you password securly
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
gwmi win32_service –credential $MySecureCreds –computer PC#

$pass="FooBoo"|ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential('user#domain',$pass)
gwmi win32_service –credential $cred –computer $computer

Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.
PS C:\Users\joshua> Get-Help Get-Credential -Full
NAME
Get-Credential
SYNOPSIS
Gets a credential object based on a user name and password.
SYNTAX
Get-Credential [-Credential] []
Get-Credential [[-UserName] <String>] -Message <String> [<CommonParameters>]
DESCRIPTION
The Get-Credential cmdlet creates a credential object for a specified user name and password. You can use the
credential object in security operations.
Beginning in Windows PowerShell 3.0, you can use the Message parameter to specify a customized message on the
dialog box that prompts the user for their name and password.
The Get-Credential cmdlet prompts the user for a password or a user name and password. By default, an
authentication dialog box appears to prompt the user. However, in some host programs, such as the Windows
PowerShell console, you can prompt the user at the command line by changing a registry entry. For more information
about this registry entry, see the notes and examples.
PARAMETERS
-Credential
Specifies a user name for the credential, such as "User01" or "Domain01\User01". The parameter name
("Credential") is optional.
When you submit the command, you are prompted for a password.
Starting in Windows PowerShell 3.0, if you enter a user name without a domain, Get-Credential no longer
inserts a backslash before the name.
If you omit this parameter, you are prompted for a user name and a password.
Required? true
Position? 1
Default value None
Accept pipeline input? false
Accept wildcard characters? false
-Message <String>
Specifies a message that appears in the authentication prompt.
This parameter is designed for use in a function or script. You can use the message to explain to the user why
you are requesting credentials and how they will be used.
This parameter is introduced in Windows PowerShell 3.0.
Required? true
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? false
-UserName <String>
Specifies a user name. The authentication prompt requests a password for the user name. By default, the user
name is blank and the authentication prompt requests both a user name and password.
When the authentication prompt appears in a dialog box, the user can edit the specified user name. However,
the user cannot change the user name when the prompt appears at the command line. When using this parameter in
a shared function or script, consider all possible presentations.
This parameter is introduced in Windows PowerShell 3.0.
Required? false
Position? 1
Default value None (blank)
Accept pipeline input? false
Accept wildcard characters? false
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
INPUTS
None
You cannot pipe input to this cmdlet.
OUTPUTS
System.Management.Automation.PSCredential
http://go.microsoft.com/fwlink/?LinkId=228224
Get-Credential returns a credential object.
NOTES
You can use the PSCredential object that Get-Credential creates in cmdlets that request user authentication,
such as those with a Credential parameter.
By default, the authentication prompt appears in a dialog box. To display the authentication prompt at the
command line, add the ConsolePrompting registry entry
(HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\ConsolePrompting) and set its value to True. If the
ConsolePrompting registry entry does not exist or if its value is False, the authentication prompt appears in
a dialog box. For instructions, see the examples.
The ConsolePrompting registry entry works in the Windows PowerShell console, but it does not work in all host
programs. For example, it has no effect in the Windows PowerShell Integrated Scripting Environment (ISE). For
information about the effect of the ConsolePrompting registry entry, see the help topics for the host program.
The Credential parameter is not supported by all providers that are installed with Windows PowerShell.
Beginning in Windows PowerShell 3.0, it is supported on selected cmdlet, such as the Get-WmiObject and
New-PSDrive cmdlets.
-------------------------- EXAMPLE 1 --------------------------
PS C:\>$c = Get-Credential
This command gets a credential object and saves it in the $c variable.
When you enter the command, a dialog box appears requesting a user name and password. When you enter the requested
information, the cmdlet creates a PSCredential object representing the credentials of the user and saves it in the
$c variable.
You can use the object as input to cmdlets that request user authentication, such as those with a Credential
parameter. However, some providers that are installed with Windows PowerShell do not support the Credential
parameter.
-------------------------- EXAMPLE 2 --------------------------
PS C:\>$c = Get-Credential
PS C:\>Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
These commands use a credential object that the Get-Credential cmdlet returns to authenticate a user on a remote
computer so they can use Windows Management Instrumentation (WMI) to manage the computer.
The first command gets a credential object and saves it in the $c variable. The second command uses the credential
object in a Get-WmiObject command. This command gets information about the disk drives on the Server01 computer.
-------------------------- EXAMPLE 3 --------------------------
PS C:\>Get-WmiObject Win32_BIOS -ComputerName Server01 -Credential (Get-Credential -Credential Domain01\User01)
This command shows how to include a Get-Credential command in a Get-WmiObject command.
This command uses the Get-WmiObject cmdlet to get information about the BIOS on the Server01 computer. It uses
the Credential parameter to authenticate the user, Domain01\User01, and a Get-Credential command as the value of
the Credential parameter.
-------------------------- EXAMPLE 4 --------------------------
PS C:\>$c = Get-Credential -credential User01
PS C:\>$c.Username
\User01
This example creates a credential that includes a user name without a domain name. It demonstrates that
Get-Credential inserts a backslash before the user name.
The first command gets a credential with the user name User01 and stores it in the $c variable.
The second command displays the value of the Username property of the resulting credential object.
-------------------------- EXAMPLE 5 --------------------------
PS C:\>$Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.",
"", "NetBiosUserName")
This command uses the PromptForCredential method to prompt the user for their user name and password. The command
saves the resulting credentials in the $Credential variable.
The PromptForCredential method is an alternative to using the Get-Credential cmdlet. When you use
PromptForCredential, you can specify the caption, messages, and user name that appear in the message box.
-------------------------- EXAMPLE 6 --------------------------
PS C:\>Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds" -Name ConsolePrompting -Value $true
This example shows how to modify the registry so that the user is prompted at the command line, instead of by
using a dialog box.
The command creates the ConsolePrompting registry entry and sets its value to True. To run this command, start
Windows PowerShell with the "Run as administrator" option.
To use a dialog box for prompting, set the value of the ConsolePrompting to false ($false) or use the
Remove-ItemProperty cmdlet to delete it.
The ConsolePrompting registry entry works in some host programs, such as the Windows PowerShell console. It might
not work in all host programs.
-------------------------- EXAMPLE 7 --------------------------
The first command saves the user account name in the $User parameter. The value must have the "Domain\User" or
"ComputerName\User" format.
PS C:\>$User = "Domain01\User01"
The second command uses the ConvertTo-SecureString cmdlet to create a secure string from a plain text password.
The command uses the AsPlainText parameter to indicate that the string is plain text and the Force parameter to
confirm that you understand the risks of using plain text.
PS C:\>$PWord = ConvertTo-SecureString –String "P#sSwOrd" –AsPlainText -Force
The third command uses the New-Object cmdlet to create a PSCredential object from the values in the $User and
$PWord variables.
PS C:\>$Credential = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
This example shows how to create a credential object that is identical to the object that Get-Credential returns
without prompting the user. This method requires a plain text password, which might violate the security standards
in some enterprises.
-------------------------- EXAMPLE 8 --------------------------
PS C:\>Get-Credential -Message "Credential are required for access to the \\Server1\Scripts file share." -User
Server01\PowerUsers
Windows PowerShell Credential Request
Credential are required for access to the \\Server1\Scripts file share.
Password for user ntdev\juneb:
This command uses the Message and UserName parameters of the Get-Credential cmdlet. This command format is
designed for shared scripts and functions. In this case, the message tells the user why credentials are needed and
gives them confidence that the request is legitimate.
-------------------------- EXAMPLE 9 --------------------------
PS C:\>Invoke-Command -ComputerName Server01 {Get-Credential Domain01\User02}
Windows PowerShell Credential Request : Windows PowerShell Credential Request
Warning: This credential is being requested by a script or application on the SERVER01 remote computer. Enter your
credentials only if you
trust the remote computer and the application or script requesting it.
Enter your credentials.
Password for user Domain01\User02: ***************
PSComputerName : Server01
RunspaceId : 422bdf52-9886-4ada-ab2f-130497c6777f
PSShowComputerName : True
UserName : Domain01\User01
Password : System.Security.SecureString
This command gets a credential from the Server01 remote computer. The command uses the Invoke-Command cmdlet to
run a Get-Credential command on the remote computer. The output shows the remote security message that
Get-Credential includes in the authentication prompt.
RELATED LINKS
Online Version: http://go.microsoft.com/fwlink/p/?linkid=293936

Related

How do I run a command on localhost with saved credentials? -Powershell

I want to run one command with saved credentials on powershell, i have the following script
$user = "test"
$passwd = ConvertTo-SecureString -String "ExtremelyStrongPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $passwd
Copy-Item -Path "C:\Temp\*" "C:\Program Files\Test\" -Credentials $cred
The user doesn't have administrator permissions, but in the localhost we have an user with administrator permissions to run these process.
The error returned is "Access Denied"
How do i pass these parameters to run a command with elevation?
Never pass plain text credentials in a script. Use the Get-Credential cmdlet to collect and use them. Even doing this, the user will get prompted for a password.
This is what the -RunAs switch of Start-Process is for
Or set your script to auto elevate
Or use the credential switch of a cmdlet
Or use a scheduled task with whatever creds you need, and let the user run it.
Use the Requires statement at the top of your script
Store the need creds in the Windows Credential Store and call them
from there
about_Requires - PowerShell | Microsoft Docs
Short description Prevents a script from running without the required
elements.
#Requires -RunAsAdministrator
Start-Process
Example 5: Start PowerShell as an administrator This example starts
PowerShell by using the Run as administrator option.
Start-Process -FilePath "powershell" -Verb RunAs
Using what you have this way:
Copy-Item -Path 'C:\Temp\*' 'C:\Program Files\Test\' -Credentials (Get-Credential -Credential 'Domain\UserName')
With exception of the scheduled task approach, each will prompt the user for a password, which sounds like what you wanting to avoid. So, consider the following:
Accessing Windows Credentials Manager from PowerShell
This simple PowerShell class can be used for working with Credentials
Manager and Password Vault in Windows: checking if account information
is present in the vault, saving credentials to the vault and reading
stored login and password information from the vault.
https://gallery.technet.microsoft.com/scriptcenter/Accessing-Windows-7210ae91
Using the registry to store credentials:
Save Encrypted Passwords to Registry for PowerShell

How to store local administrator username and password in powershell script

I am creating a PowerShell script that a user can just run to edit an entry in registry. My problem is that I cannot figure out how to store local admin username and password in the same script so that the user can just double click the script and run it without having to enter username and password manually.
Here is my code:
$username = "testpc\administrator"
$pasword = get-content C:\Users\test1\documents\testpassword.txt
$credential = new-object -typename system.management.automation.pscredential -argumentlist $username, $password
This does not work at all. Please let me know what I am doing wrong here.
Usually I'd ask for an error, but in this case I'll advise different, just because your approach isn't acceptable.
Don't store passwords unencrpted in script. Never.
Don't store passwords encrypted in scripts, which are meant to be read by someone else, especially not a user with less privileges. Never!
Go, figure other ways to solve your problem. Always!
In this case I see two solutions with the given information:
change the ACL for the registry key that need to be changed by the user
Create a scheduled task which runs as SYSTEM. Make sure the user cannot edit the script.
Actually #vrdse is right.
you can create the script with the KEY as parameter and:
create a scheduled job with the credentials of your user and add the script as task.
give the user the right to execute the job but NOT to edit or to delete
give a shortcut to the scheduled job (or a runner script) to the user and make a how-to document to show him,/her how the parameter should be used.
I use clear text passwords as temporary testing stuff to make sure users CANNOT use my script (so it is exactly the opposite of your action).
You can capture credential during execution:
$cred = get-gredential -message 'This script needs a real admin user'
Enter-PSSession -Credential $cred -ComputerName 127.0.0.127
You can build a credential (do not store privileged user data):
$user = 'SuchAGreatDomainName\IAmLowPrivilegedUserName'
$Password = 'SuperSecretPassEverybodyKnows'
$secpassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpassword)
Invoke-RestMethod -Uri $Uri -Credential $Credential

Powershell, RunAs vs Credential

So I have not found anything that explains why this code will run when you open PowerShell as "Administrator", entering your domain admin credential. Whereas when you open PowerShell with no admin privilege and using the -credential Domain\DomainAdminUser, then entering your password when prompted and I get error. Why is this?
Error: Get-WinEvent: The parameter is incorrect.
I'm asking because I have a menu script which I can run it as admin using my domain admin credential but the gpresult command will not work because of "invalid pointer" and reason being is, my domain account is not part of the authenticated user.
So to make it easy, I need to run my menu script without admin rights and use the -credential switch for certain commands within the menu script.
cls
$logname = "Security"
$Id = "4634"
$Id2 = "4624"
Get-WinEvent -ComputerName $env:COMPUTERNAME -Credential Domain\DomainAdminuser #{logname=$logname;Id=$Id,$Id2;starttime=[datetime]::Today} |
Select-Object TimeCreated, Id, #{n="Message";e={($_.message).Split(" ")[0..4] -join " "}} | Format-Table -Wrap

Permissions required to use Move-VM remotely in Hyper-v 2016

I am attempting to run the PowerShell command "move-vm" remotely but I am getting permissions errors that I can't seem to get past.
My move-vm command looks like this:
move-vm -ComputerName SorceHost -Name $vm.name -DestinationHost $DestHost -IncludeStorage -DestinationStoragePath d:\vms -DestinationCredential $cred -Credential $cred
and I am defining the credentials like this
$username = ".\PSAPIUser"
$password = Get-Content 'C:\key\PSAPIAUTH.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
Both the source and destination are on the same AD domain, and I have created a domain admin account specifically for this function. I have added the domain admins group to the local groups 'Hyper-V administrators' 'administrators' on the source and destination hosts. When I issue the command I get:
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer 'SourceHost'.
There are various articles out there about how to do this in 2012, however, its my understanding that the process has changed significantly in 2016 due to the depreciation of something called authorisation manager.
Does anyone have any experience on how to configure permissions to allow remote Hyper-V management with PowerShell specifically in 2016?
Thanks in advance.
Edit:
$cred = Get-Credential
$cred
UserName Password
-------- --------
PSAPIuser#domain.net System.Security.SecureString
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer
Managing Hyper-V remotely uses something called Constrained Delegation. Imagine the scenario.
You are on the host Man1, and you are issuing a command to Hyp-001 to move a VM to Hyp-002. So you have Man1 issuing commands to Hyp-001, which is fine as it can use your credentials, but when Hyp-001 passes commands to Hyp-002 it has no credentials to pass, hence you get the error
move-vm : Virtual machine migration operation failed at migration source.
Failed to establish a connection with host 'ng2-vps-011.hyperslice.net': No credentials are available in the security package
to get around this you need to give specific permissions that allows hosts to run specific services on each other, within AD delegation.
From PowerShell it would look like this:
Set-ADObject -Identity $HostDeetsArra.Disname -ADD #{"msDS-AllowedToDelegateTo"="$service1/$Disname","$Service1/$HostName"}
#$disnam = distignushed name, $Service1 is the service 'cifs' $hostanme is the FQDN
In 2016 you also need this:
Set-ADAccountControl -Identity $HostDeetsArra.Disname -TrustedToAuthForDelegation $true
My source for this information is below
https://www.altaro.com/hyper-v/free-powershell-script-configure-constrained-delegation-hyper-v/

Add-AzureAccount -credential not working as I'd hoped

4 days ago (on 4th August 2014) there was a new release of Azure Powershell that included a new -Credential parameter on the Add-AzureAccount cmdlet. I'm trying to use it but I'm clearly doing something wrong.
First I store my password in a file:
read-host -assecurestring | convertfrom-securestring | out-file C:\temp\securestring.txt
Then try and use it in Add-AzureAccount
$password = cat C:\temp\securestring.txt | convertto-securestring
$username = "dhdom1\jamiet" #yes, this is the correct username
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
Add-AzureAccount -credential $mycred
The call to Add-AzureAccount fails:
Add-AzureAccount : user_realm_discovery_failed: User realm discovery
failed: The remote server returned an error: (404) Not Found.
I know that "dhdom1\jamiet" is the correct account. Anyone any idea why this might be failing? TIA
You should use the organizational account you use to log in to the Azure Portal with. So, it might look like jamiet#yourorganizationalaccountname.com, or something like that.
open azure powershell window
type Add-AzureAccount then enter
a login screen will be popuped to him then enter this credential outlook
by this, this credentials are stored in this PowerShell window, then run all other scripts from this specific window.