Connecting to multiple servers through PowerShell - powershell

I'm trying to make a script, or just find a way, to use a .txt file that has a list of servers, and go through the list connected to each, or try to connect to each to see which servers belong to me. If I can connect, they're mine, if not then I need to send that server name to a file. There are 600+ servers so I can't enter credentials and have been trying to find a way using New-SSHSession that doesn't ask for -Username or -Password. What I have so far is below, I've just started PowerShell so my knowledge is limited, what you see is what I've been trying to get working before finally coming here.
#$pass = Get-Content C:\securestring.txt | ConvertTo-SecureString
$pass = Read-Host -AsSecureString "Enter Password"
$pass2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
ForEach ($cname in Get-Content "C:\testingconnections\testconnect.txt")
{
New-SshSession -ComputerName $cname -Username $env:USERNAME -Password $pass2 *>> 'C:\testingconnections\error.txt'
Remove-SshSession $cname
}

Related

How to copy a file from local work space to remote server (not a network shared path) with powershell

I am trying to copy a file from my local workspace to a remote server (not a network shared path) by using the powershell command through Inline Powershell" task in TFS vNext build definition.
FYI, destination path is not a network shared path
I tried with below commands
$Session = New-PSSession -ComputerName "remote server name" -Credential "domain\username"
Copy-Item "$(Build.SourcesDirectory)\Test.htm" -Destination "C:\inetpub\wwwroot\aspnet_client\" -ToSession $Session
But it's promoting for the password every time and I tried with entering the password manually and the result looks good.
How can we achieve this step without prompting password or credentials
Are you sure it's not on a network share? :)
Powershell only takes password as a secure string. You can use $credential = Get-Credential to render a really cool box to store those credentials for you, or if you want to store your login programmatically (not recommended for obvious security reasons) use this:
$passwd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("<username>",$passwd)
There might be a way to inherit your current domain credentials, but that's way beyond me, and a quick google search turns up nothing.
EDIT: Sorry I forgot to post the whole thing:
$passwd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("<username>",$passwd)
$Session = New-PSSession -ComputerName "remote server name" -Credential $credential
Copy-Item "$(Build.SourcesDirectory)\Test.htm" -Destination "C:\inetpub\wwwroot\aspnet_client\" -ToSession $Session

Save output to txt file on remote server with user and password [duplicate]

This question already has answers here:
Connecting to a network folder with username/password in Powershell
(3 answers)
Closed 4 years ago.
After connecting to remote computer and executing some powershell job, I need to save a text file with output to a remote server using powershell.
My file name is created depending on computer name and date.
$filename = '' + $enddate + '' + $name + ''
Output is:
$output = "\\10.0.50.8\Informatyka\Posnet_raporty"
There is a username and password to connect to folder "Posnet_raporty"
$username = "user"
$password = "pass"
I use 2 functions to create the file and have been trying to use the NET USE command to create a disc on the remote computer to save the file there, but it has failed ;/ (already mapped source from this adress, net use don't like it)
If ([int]$end1 -gt 30) {
$end1, $end2 | Out-File Q:\$filename'.txt'
}
else {
$end1, $end2 | Out-File Q:\'#'$filename'.txt'
}
The output of $end1 is a number (this does not apply to the question, but I prefer to write everything I can)
edit:
net use fail, can not work with this same source what is already mapped on computers. PSDrive is only accessible in PowerShell session.
I'm not totally clear on what you're trying to do, but if you want to map to a specific remote folder, you might want to use a PSDrive. These are like traditional mapped drives, but are by default only accessible in your PowerShell session. You can create one like this:
$userName = "domain\user"
$password = "Password"
$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($userName, $secPassword)
New-PSDrive -Name Q `
-PSProvider FileSystem `
-Credential $cred `
-Root \\ServerName\Share\Folder1\Folder2
The credentials are optional - the mapping will work ok if the current user already has permission to access the location.
You can then use it like any other drive:
Get-ChildItem Q: -File -Recurse
Disconnect afterwards, by doing this:
Remove-PSDrive -Name Q

Encrypting password or workaround

I am bit of a lazy guy, so I have created a script that opens many applications for me. Works fine as ISE opened with Administrator credentials, also opens apps with admin creds, however some of them need a different credentials.
Is it possible, to make powershell remember typed in password each time I log in and open it? (I know that variables are stored only till ps is opened)
Thing is - I cannot store a visible password in profile/text file or in a script, as this is a jump server used by many people. Is it somehow possible to type a password once, make PS encrypt it and each time I will open PS, it will decrypt it and use? or any workaround possible around this?
edit with code:
It's the only part I would like to change
$currentPW = "some password"
$credentials = New-Object System.Management.Automation.PSCredential ("domain\username",$CurrentPW)
start "c:\application.exe" -credential $credentials
It kinda works but it would require me, to input the password everytime I log in to device, so I could go for option like:
$currentPW = read-host "Provide your password"
$credentials = New-Object System.Management.Automation.PSCredential ("domain\username",$CurrentPW)
start "c:\application.exe" -credential $credentials
but this would require me to input the password each time I log in to system and open PS as it does not remember variables after restart.
So...is it even possible to make this work?^^
You can use ConvertTo-SecureString to encrypt the password using the users account key, then save this secure string to a file to load at a later time.
This assumes you are the only one with access to the logon account (not an account with shared credentials), as anyone who can logon as the account can decrypt the file.
$username = "domain\username"
$passwordFile = "C:\folder\EncryptedPassword.txt"
#if password file exists: populate $securePwd from file contents
If (Test-Path $passwordFile) {
$pwdTxt = Get-Content $passwordFile
$securePwd = $pwdTxt | ConvertTo-SecureString
}
#if no file: prompt for password, create file and populate $securePwd
Else {
$password = Read-Host "Provide your password"
$securePwd = $password | ConvertTo-SecureString -AsPlainText -Force
$securePwd | ConvertFrom-SecureString | Set-Content $passwordFile
}
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd
Start-Process "c:\application.exe" -Credential $credentials
If you have PowerShell 3.0 or newer, you can also combine Get-Credential with Export-CliXml to export a PSCredential object as an XML file. Example:
Get-Credential | Export-CliXml "C:\XML Files\credential.xml"
You can then import the credentials using Import-CliXml. Example:
$credential = Import-CliXml "C:\Xml Files\credential.xml"
Note that the password is encrypted using DPAPI, so you can only import the credentials using Import-CliXml on the same computer using the same user account that was used to export the credentials using Export-CliXml.

Start-Job with credential in custom task problems

I am trying to develop a custom task using Powershell which needs to use Start-Job -Cred to switch to another user in places. Agent is running as user A and I need to switch to user B. Logging in to the server running the agent as user A and then running the script works fine - the Start-Job switches credentials and runs a scriptblock as user B.
Running exactly the same thing from VSTS in the cloud using the same (on-prem) agent server running the agent as user A fails with the uninformative error:
"The background process reported an error with the following message: ."
I have done more debugging and there is no other error message anywhere. It seems to be related to the -Cred parameter of Start-Job as it makes no difference what is in the script block run and if I remove the -Cred parameter, it's also fine.
User A is in the Adminstrators group on the server running the agent
Agent runs as user A
Any ideas?
Try it with Invoke-Command, for example (output current user name):
$mypwd = ConvertTo-SecureString -String "[password, could use variable]" -Force -AsPlainText
$Cred = New-Object System.Management.Automation.PSCredential('[user name]',$mypwd)
$scriptToExecute =
{
$VerbosePreference='Continue'
Write-Output "$env:UserName"
# Write-Verbose "Verbose" 4>&1
}
$b = Invoke-Command -ComputerName localhost -ScriptBlock $scriptToExecute -Credential $Cred
Write-Output "Content of variable B"
Write-Host $b
Based on your experiences, your credentials are not being passed properly. Try this method and insert it into your script:
Outside of your script, get the securestring object-
Read-Host -AsSecureString | ConvertFrom-SecureString
Take the output of this command (where you enter the password), and put it before your start-job-
$Secure = ConvertTo-SecureString -String 'above output'
$Cred = New-Object System.Management.Automation.PSCredential('Username',$Secure)
Start-Job -Credential $Cred
The SecureString can be reversed by someone with know-how, but if the script and/or account is secure, then that doesn't matter.

Looping through all my domains an changing pwd- access denied SET-QADUSER

I have several domains and one admin account in each one. It is a great pain to log into each domain to change password every month..
I have therefore written a script that will connect to all domains and check to see if I have already changed the password or if I am still using the old one.
If I am using the old one the script should update it.
I connect to the domains (sequentially) with
$oldPassword = Read-Host "Enter old password" -AsSecureString
$newPassword = Read-Host "Enter new password" -AsSecureString
$oldCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "$domain\$adminusername",$oldPassword
Connect-QADService -Service $domain -Credential $oldCredentials
and if I get a successfull connection with $oldcredentials I try to change pwd with
GET-QADUSER $adminusername | SET-QADUSER -UserPassword $newPassword
I am guessing that I am not passing the secure string correctly to SET-QADUSER but I've found no documentation on another way to do it.
Please advice:)
SET-QADUSER -UserPassword accept [string] type not [System.Security.SecureString].
Try to pass just a string as password.