Powershell: Using specific credentials to execute a command - powershell

Dears,
In my Powershell script, I would like to use a specific credential on a remote computer. This login exists on the remote computer and is local.
Hence, my code looks like this:
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "Resource"
$USERNAME = "MyLogin"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,"REMOTE_COMPUTER\"+$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
$ComputerMemory = Get-WmiObject -ComputerName "REMOTE_COMPUTER" -Class win32_operatingsystem -ErrorAction Stop -Credential $cred
$Memory = ([math]::round(((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize), 2))
echo $Memory
Problem of course is when executing GetWmiObject, I got an Access denied error...
Is there something wrong with this code?
Thanks in advance for your feedback,
Kind regards,

Related

PS credential retry

I have this script
$db = import-csv -Path ".\testdb.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db -match $inputID
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$User2 = "user2"
$Password2 = "pass2"
$Command = "C:\test.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$secpasswd2 = ConvertTo-SecureString $Password2 -AsPlainText -Force
$Credentials2 = New-Object System.Management.Automation.PSCredential($User2, $secpasswd2)
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
}
catch {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials2 -AcceptKey:$true
}
Is any chance to try connect with 2 different credentials ; if one fail try to other?
So.. first time try user and password ; second time try user2 and password2
Thank you. :)

Find the exact matched string from the variable

In the below code, $Result variable has the following information. I need to iterate below each line in $Result variable and get the <APPPOOL NAME> that is, "DefaultAppPool","Classic .NET AppPool" & ".NET v2.0 Classic" as an input to the second Invoke-Command saved in $Result2. Please advise how this can be accomplished.
$Result output:
APPPOOL "DefaultAppPool" (MgdVersion:v4.0,MgdMode:Integrated,state:Started)
APPPOOL "Classic .NET AppPool" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
APPPOOL ".NET v2.0 Classic" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
$Username = '<username>'
$Password = '<Password>'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
$input_file_path = "servers.txt"
$output_path = "result.txt"
foreach ($server in Get-Content $input_file_path) {
$Result = Invoke-Command -ComputerName $server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools
}
$Result | Add-Content $output_path
$Result2 = Invoke-Command -ComputerName #server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools <APPPOOL NAME> /text:processmodel.username
}
}

how to use different credentials inside an invoke-command

I am currently trying to get a value from a different server. So I am connecting to a server using $sessionUsername and $sessionPassword but then I need to use different credentials to get the information that I require.
I am unsure as to how I can do this, so far I have tried to do a Start-Job and a Start-Process inside the Invoke-Command and even another invoker command but this has not worked.
$sessionUserName = "mysession"
$sessionPassword = "sessionPassword"
#$sessionUserName = "LON\user"
#$sessionPassword = "user"
$serverAddress = "the address"
$securePassword = ConvertTo-SecureString -AsPlainText -Force -String $sessionPassword
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sessionUserName,$securePassword
$session = New-PSSession -ComputerName $serverAddress -Credential $credentials
$username = "LON\differentuser"
$password = "different password"
$PSS = ConvertTo-SecureString $password -AsPlainText -Force
$cred = new-object system.management.automation.PSCredential $username,$PSS
Invoke-Command -Session $session -scriptblock {
#Start-Process "C:\StuckApps\powershell.exe" -Credential $args[0] -ArgumentList "-file C:\StuckApps\connect.ps1"
$args[0].GetNetworkCredential().username;
$args[0].GetNetworkCredential().password;
$t = {
$args[0].GetNetworkCredential().username;
$args[0].GetNetworkCredential().password;
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server = Theserver.co.uk; Database = m; Integrated Security = true;"
$conn.Open()
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandTimeout = 0
$command.CommandText = "exec dbo.AlphaBoard_GetStuckApps"
$command.Connection = $conn
$rows = $command.ExecuteReader()
$dt = New-Object System.Data.DataTable
$dt.Load($rows)
$number = $dt.Rows.Count
$conn.Close()
return $number
Write-Host "Hello"
}
Start-Job -ScriptBlock $t -Credential $args[0]
#Start-Process powershell -ArgumentList '-executionpolicy','bypass', $t -Credential $session
$number
} -ArgumentList $cred
$number
$previousNumberPath = "C:\bamboo-home\xml-data\build-dir\INT-SAM-JOB1\number.txt"
The $args[0].GetNetworkCredential().username; inside the invoke-command shows me that this is passing the credentials in, but how can I use them? I am not sure what I am doing wrong? I can't seem to get the $number variable back, how can I do this?
The main problem I have is the error
This command cannot be run due to the error: Access is denied.
Which I am unsure why this is happening as on the server itself it I run:
Start-Process powershell.exe -Credential $cred -ArgumentList "noexit", "-file C:\StuckApps\connect.ps1"
which I have also tried on my current script, it works fine, but using this on my script shows an access denied. I have already got on the server via the first invoke-command why can't I get the same result?

How to rename a domain computer in Powershell

I've been trying to rename a domain computer with the following script:
$username = "domain\username"
$password = "password"
$ip = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
$hostname = (nslookup $ip)[3]
$hostname = $hostname.replace(" ", "")
$hostname = $hostname.split(":")[1]
$hostname = $hostname.split(".")[0].ToLower()
Rename-Computer -NewName $hostname -DomainCredential $username -Restart -Force
It does everything I desire apart from inputting the password which at this point is a manual process. Can someone advise me on how to get it to input from $password into the prompt box so that I can completely automate the process?
Alternatively, if there's a better way to do it in Powershell, I'm open to going another direction.
You can use this code:
$Username = "DomainUserName"
$Password = "PlainPassword" | ConvertTo-SecureString -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential($Username ,$Password)
Rename-Computer -NewName $newComputerName -ComputerName $OldName -Restart -DomainCredential $Creds

Hardcode password into powershells "New-PSSession"

I have a script to get and set user's Windows environment variables on other computers for a given user. Is it possible to hard code the password for this user so that I don't have to type it every time I run the script?
My script looks something like this:
$s5 = New-PSSession -computername testauto2, testauto3 -Credential
Domain\testautouser
invoke-command -session $s5[0] -scriptblock {[Environment]::GetEnvironmentVariable("TestBrowser", "user")}
Yep - you can totally do this as long as you are comfortable with the security implications (a PW in a file somewhere)...
Here's an example:
$pw = convertto-securestring -AsPlainText -Force -String <insert pw here>
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\User",$pw
$session = new-pssession -computername <computer> -credential $cred
I've used this approach in similar situations. It's certainly not perfect, but it makes me much less nervous than hardcoding a password in a file. I read and store the password during the first run, then read from the DPAPI-encrypted file afterward. I generally run scripts from a shared location on an internal network, and store the encrypted password file in a private folder on my local machine.
$user = "Domain\testautouser"
$passwdFile = "$env:USERPROFILE\myscript-$user"
if ((Test-Path $passwdFile) -eq $false) {
$cred = new-object system.management.automation.pscredential $user,
(read-host -assecurestring -prompt "Enter a password:")
$cred.Password | ConvertFrom-SecureString | Set-Content $passwdFile
}
else {
$cred = new-object system.management.automation.pscredential $user,
(Get-Content $passwdFile | ConvertTo-SecureString)
}