Try different credentials PS script SSH - powershell

I have this script and cannot work correctly .. I try to connect with 2 users ; if one doesn't work try other one.
#1. Try user and pass1 if is not good try #2. user and pass2.
*problem is with winscp users ; I really don't know how to implement 2 try connection
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$db = import-csv -Path "C:\Program Files (x86)\WinSCP\db.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db | where-Object {$_.HostName -eq $inputID}
if ($inputID -eq $entry.HostName){
"$inputID Ok!"
}
else{
"$inputID nu exista in baza de date!"
$title = 'Title'
$question = 'Doriti sa introduceti un ID nou in Baza de Date?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
$ID = Read-Host -Prompt "Introduceti ID"
$IP = Read-Host -Prompt "Introduceti IP"
$wrapper = New-Object PSObject -Property #{ HostName = $ID; IP = $IP }
Export-Csv -Append -InputObject $wrapper -Path "C:\Program Files (x86)\WinSCP\db.csv" -NoTypeInformation -Force
$dbTrimmer = Get-Content -Path "C:\Program Files (x86)\WinSCP\db.csv"
$dbTrimmer.Replace('","',",").TrimStart('"').TrimEnd('"') | Out-File "C:\Program Files (x86)\WinSCP\db.csv" -Force -Confirm:$false
Exit
}
else{
Write-Host 'No'
Exit
}
}
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = "$User"
Password = "$Password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
$file = "Dev.log", "Info.dat"
$localPath = "E:\Arhive\*"
$remotePath = "/C:/Program Files/Dev.log", "/C:/Program File/Info.dat"
try {
# Connect
$session.Open($sessionOptions)
# Check exists files
foreach ($remotePath in $remotePath)
{
if ($session.FileExists($remotePath))
{
Write-Host "Fisierul $remotePath exista"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()
}
else
{
Write-Host "Fisierul $remotePath NU exista"
}
}
}
finally {
$session.Dispose()
}
foreach ($file in "E:\loguri\Dev.log", "E:\loguri\Info.dat") {
if (Test-Path $file) {
Compress-Archive $file -DestinationPath "E:\Arhive\$inputID.zip" -Update
Remove-Item $file
}
}
# Stergere fisiere din Arhive mai vechi de 60 minute
$Files = get-childitem 'E:\Arhive' | Where-Object PSIsContainer -eq $false
$LimitTime = (Get-Date).AddMinutes(-60)
$Files | ForEach-Object {
if ($_.CreationTime -lt $LimitTime -and $_.LastWriteTime -lt $LimitTime) {
Remove-Item -Path $_.FullName -Force
Write-Host "Am sters $Files pentru ca sunt mai vechi de $LimitTime !"
}
}
Here is all my script. In this moment all works very well , just I want to add 2 users for auth. If 1 fail try other one.
Any ideea ? Thank you

I couldn't test this myself, but I think I would go about it like below:
$User = "SameUser"
$Password = "Pass1"
$sPassword = "Pass2"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$ssecpasswd = ConvertTo-SecureString $sPassword -AsPlainText -Force
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
# try the first credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true -Verbose -ErrorAction Stop
}
catch {
# first one failed, try second credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $ssecpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $sCredentials -AcceptKey:$true -Verbose
}
try {
Invoke-SSHCommand -SessionId $SessionID.SessionId -Command $Command -ErrorAction Stop
}
catch {
throw
}
# create a hashtable with the first password
$options = #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = $User
Password = $Password
GiveUpSecurityAndAcceptAnySshHostKey = $true
}
try {
# Set up session options using first password
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
# Set up session options using second password
$options['Password'] = $sPassword
try {
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
throw
}
}
try {
# Check if exists files.
# Make sure variables $remotePath and $localPath are defined on top of the script
foreach ($remoteFile in $remotePath) {
if ($session.FileExists($remoteFile)) {
$session.GetFiles($remotePath, $localPath).Check()
}
else {
Write-Warning "File '$remoteFile' not found"
}
}
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
}
finally {
if ($session) { $session.Dispose() }
}

Related

csv powershell cmd output

I use this script for check on multiple machine if I have installed some apps and now the script return in txt file result. (format hostname\nYes/No). How can I change return result in csv file in 2 columns ; 1.Hostname ; 2. Result ?
actual result.txt
hostname
YES / NO
desired csv export
Hostname | Result
hostname | YES / NO / OFFLINE
script
$Computers = Get-Content -Path C:\Users\m\Desktop\ip.txt | Where-Object { $_ -match '\S' }
foreach($Computer in $Computers){
Write-Host $Computer
$User = "ussr"
$Password = "pssd"
$Command = 'hostname && if exist "C:\LdApp.exe" (echo YES) else (echo NO)'
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
try{
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command | Select -Expand Output | Add-Content -Path result.txt}
catch {Add-Content -Path result.txt -Value "$Computer conectare esuata!"}
}
Thank you,
I have modified your code and not tested it. I will do some thing like this
$result = Get-Content -Path C:\Users\m\Desktop\ip.txt | ForEach-Object {
$computer = $_
try {
Write-Host $Computer
$User = "ussr"
$Password = "pssd"
$Command = 'if exist "C:\LdApp.exe" (echo YES) else (echo NO)'
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
$output = if ($SessionID) {
(Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command).Output
}
else {
"Offline"
}
}
catch {
{
Write-Host "$Computer conectare esuata!"
$output = "conectare esuata!"
}
}
[PsCustomObject]#{
'Hostname' = $computer
'Status' = $output
}
}
$result | Export-csv -Path "C:\Users\m\Desktop\result.csv" -NoTypeInformation
Answer2: for multiple commands and capturing results, and yet again not tested :(
Get-Content -Path C:\Users\m\Desktop\ip.txt | ForEach-Object {
$computer = $_
try {
Write-Host $Computer
$User = "ussr"
$Password = "pssd"
$Command = 'hostname && if exist "C:\LdApp.exe" (echo YES) else (echo NO)'
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
if ($SessionID) {
$Output = (Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command).Output
$result = $Output.split("`n")
[PSCustomObject]#{
"HostName" = $result[0]
"IPAddress" = $result[1] # Print $result to verify the exact index of this value.
"Status" = $result[2]
}
}
else {
[PSCustomObject]#{
"HostName" = $computer
"IPAddress" = "NA"
"Status" = "offline"
}
}
}
catch {
{
Write-Host "$Computer conectare esuata!"
}
}
} | Export-csv -Path "C:\Users\m\Desktop\result.csv" -NoTypeInformation

Select Multiple Host PowerShell

I have this ps code.
Can somebody help me with one ideas :
How can I do to type multiple host and execute on multiple host this script ?
For eg I run script and ask me ID , I enter ID script trying to find IP in db.csv for connect ssh/sftp but I want to type more ID if I can. "Type the ID:" A, B, C, D, ...,X and execute.
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$db = import-csv -Path "C:\Program Files (x86)\WinSCP\db.csv"
$inputID = Read-Host -Prompt "Type the ID"
$entry = $db -match $inputID
Write-Host "IP:" $entry.IP
$User = "username"
$Password = "Password"
$Command = "C:\SaveBVInfo.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = "$User"
Password = "$Password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
$file = "Device.log", "SaveBVInfo.dat"
$localPath = "E:\loguri\Log\Arhive\*"
$remotePath = "/C:/Program Files/Common Files/logs/Device.log", "/C:/Program Files/SaveBVInfo.dat"
try {
# Connect
$session.Open($sessionOptions)
# Check exists files
foreach ($remotePath in $remotePath)
{
if ($session.FileExists($remotePath))
{
Write-Host "Fisierul $remotePath exista"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()
}
else
{
Write-Host "Fisierul $remotePath NU exista"
}
}
}
finally {
$session.Dispose()
}
foreach ($file in "E:\loguri\Log\Arhive\Device.log", "E:\loguri\Log\Arhive\SaveBVInfo.dat") {
if (Test-Path $file) {
Compress-Archive $file -DestinationPath "E:\loguri\Log\Arhive\$inputID.zip" -Update
Remove-Item $file
}
}
Thank you :D
You have to split the input either by a comma, a space, etc.
$inputID = Read-Host -Prompt "Type the ID"
$inputID -split " "
...but, you would have to iterate through those once theyre selected using foreach.
$inputID = Read-Host -Prompt "Type the ID"
$grouped = $inputID -split " "
Foreach($id in $grouped){
"This is ID: $ID"
}
Output:
Type the ID: 1 2 3 4 5 6
This is ID: 1
This is ID: 2
This is ID: 3
This is ID: 4
This is ID: 5
This is ID: 6

Testing and reporting Invoke-command execution

I have the following PowerShell script that creates a session with Windows server administrator account.I want to report in case of failure of Invoke-command the error and save it in a file
Below is the code that I wrote but if i tamper for example .json file(set a wrong username),execution fails and error_report.txt is not created
#Param(
$user = "lamda"
#)
$user_domain = (Get-WmiObject Win32_ComputerSystem).Domain
$user_computer = (Get-WmiObject Win32_ComputerSystem).Name
$file = "error_report.txt"
If ((Test-Path "creds.json") -eq $True)
{
$jsonfile = Get-ChildItem creds.json
if ($jsonfile.Length -eq 0)
{
#$file = "error_report.txt"
Set-Content -Path $file -Value "Error:The file 'creds.json' is empty"
break
}
else
{
$creds= (Get-Content creds.json | Out-String | ConvertFrom-Json)
$admin = $creds.username
$passwd = $creds.password
if (($admin) -and ($passwd))
{
$Password = ConvertTo-SecureString -String $passwd -AsPlainText -Force
$credential = [pscredential]::new($admin,$Password)
$command = Invoke-Command -ComputerName Server.$user_domain -FilePath
C:\SECnology\Data\Utilities\Updating.ps1 -ArgumentList
$user,$admin,$user_computer -Credential $credential
If ($command -eq $false)
{
$file = "error_report.txt"
Set-Content -Path $file -Value "Error:Session between user and server
could not be created,please check your Credentials"
}
break
}
elseif (([string]::IsNullOrEmpty($admin)) -or ([string
]::IsNullOrEmpty($passwd)))
{
#$file = "error_report.txt"
Set-Content -Path $file -Value "Error:One object of 'creds.json' seems
to be empty.Please check your file "
}
}
break
}
else
{
#$file = "error_report.txt"
Set-Content -Path $file -Value "Error:The file 'creds.json' does not exist"
}
I think the issue is the way you are defining the condition on your if statement.
You use -eq $false however if you connections fails it does not set the vale of command to $false it will leave command as a null as it return no value (it errorred).
What you can try is either use the null operator (!) in your if statement so:
If (!$command){Do stuff}
Or you can give you invoke command an error variable and check if that has a value when run.
$command = Invoke-Command -ComputerName Server.$user_domain -FilePath
C:\SECnology\Data\Utilities\Updating.ps1 -ArgumentList
$user,$admin,$user_computer -Credential $credential -ErrorVariable TheError
If ($TheError)
{Do stuff}

automate sitecollection administrator assignment in sharepoint online with powershell for backup purposes

I was asked to create a powershell script to automate the assignment for new sitecollection administrator in SharePoint-Online for BackUp purposes NetApp CloudControl.
This is my firsttime ever in PowerShell and now I got stucked and don't know where to look anymore or least don't understand what I'm looking at.
The script is supposed to do the following:
Get Microsoft-tenant and password
Create a new ps-script where the credentials are already filled in
Connect to sharepoint-online and lookup personal space for every user(onedrive for business sites)
cut the log and create a second one if more than 200 lines were written
read the log and make the service-account a sitecollectionadmin
create task to run the created script once per week
At the moment I got it to do this:
Get Microsoft-tenant and password
Save Credentials
Connect to sharepoint-online and lookup personal space for every user(onedrive for business sites)
read the log and make the service-account a sitecollectionadministrator
Can anyone of you please help me out on how to proceed with the next steps?
P.S. Please excuse that I'm posting the script as a whole, I just didn't know what I should cut out.
$TenantName = $null0
$TenantPassword = $null1
if($TenantName -eq $null0){
$TenantName = Read-Host "Enter Office 365 - Tenant Name."
$NewScript = Get-Content $PSCommandPath | ForEach-Object {$_ -replace '^\$TenantName = \$null0$',"`$TenantName = '$TenantName'"}
$NewScript | Out-File $PSCommandPath -Force
}
if($TenantPassword -eq $null1){
$TenantPassword = Read-Host "Enter Password for netapp-service#$($TenantName).onmicrosoft.com."
$NewScript = Get-Content $PSCommandPath | ForEach-Object {$_ -replace '^\$TenantPassword = \$null1$',"`$TenantPassword = '$TenantPassword'"}
$NewScript | Out-File $PSCommandPath -Force
}
$username = "netapp-service#$($TenantName).onmicrosoft.com"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $TenantPassword -asplaintext -force)
Connect-SPOService -Url https://$($TenantName)-admin.sharepoint.com/ -Credential $cred
$AdminURI = "https://$($TenantName)-admin.sharepoint.com"
$AdminAccount = "netapp-service#$($TenantName).onmicrosoft.com"
$AdminPass = $TenantPassword
$eDiscoveryUser = "netapp-service#$($TenantName).onmicrosoft.com"
$MySitePrefix = "https://$($TenantName)-my.sharepoint.com"
$LogFile = '.\$TenantName\$TenantName-MySites.txt'
$MySiteListFile = '.\$TenantName\$TenantName-MySites.txt'
Connect-SPOService -Url $AdminURI -Credential $cred
$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
$sstr = ConvertTo-SecureString -string $AdminPass -AsPlainText –Force
$AdminPass = ""
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminAccount, $sstr)
$proxyaddr = "$AdminURI/_vti_bin/UserProfileService.asmx?wsdl"
$UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
$UserProfileService.Credentials = $creds
$strAuthCookie = $creds.GetAuthenticationCookie($AdminURI)
$uri = New-Object System.Uri($AdminURI)
$container = New-Object System.Net.CookieContainer
$container.SetCookies($uri, $strAuthCookie)
$UserProfileService.CookieContainer = $container
$UserProfileResult = $UserProfileService.GetUserProfileByIndex(-1)
Write-Host "Starting- This could take a while."
Out-File $LogFile -Force
$NumProfiles = $UserProfileService.GetUserProfileCount()
$i = 1
While ($UserProfileResult.NextValue -ne -1)
{
Write-Host "Examining profile $i of $NumProfiles"
$Prop = $UserProfileResult.UserProfile | Where-Object { $_.Name -eq "PersonalSpace" }
$Url= $Prop.Values[0].Value
if ($Url) {
$Url | Out-File $LogFile -Append -Force
}
$UserProfileResult = $UserProfileService.GetUserProfileByIndex($UserProfileResult.NextValue)
$i++
}
Write-Host "Done!"
$reader = [System.IO.File]::OpenText($MySiteListFile)
try {
for(;;) {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
$fullsitepath = "$MySitePrefix$line"
Write-Host "Operating on $fullsitepath "
$fullsitepath = $fullsitepath.trimend("/")
Write-Host "Making $eDiscoveryUser a Site Collection Admin"
Set-SPOUser -Site $fullsitepath -LoginName $eDiscoveryUser -IsSiteCollectionAdmin $true
}
}
finally {
$reader.Close()
}
Disconnect-SPOService
Write-Host "Done!"

invoke-parallel in Powershell - data sharing inside script with global variable

Using invoke-parallel in Powershell, I'm trying to get a list of hosts where a certain command works vs. does not. How can I write to a global variable inside of invoke-parallel?
$creds = Get-Credential -UserName $username -Message 'Password?'
$servers = get-content .\hosts.txt
$success = #()
$failure = #()
Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
try
{
$result = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" -ErrorAction Stop {hostname}
$success += $result
}
catch
{
$failure += $_
}
}
write-host $success
write-host $failure
Try this:
$Results = Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
try
{
$Output = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" -ErrorAction Stop {hostname}
}
catch
{
$Output = $_
}
#($Output)
}
Final code sample for what I ended up using.
$username = "myuser"
$creds = Get-Credential -UserName $username -Message 'Password?'
$servers = get-content .\hosts.txt
$Results = Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
$arr = #{}
try
{
$Output = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" {hostname} -ErrorAction Stop
$arr[$_] = "successful"
}
catch
{
$arr[$_] = "failed"
}
$arr
}
$Results