Check File size powershell ssh - powershell

I use this script for check file size. How can I make to verify each computers ip's in ip.txt and the result print in results.txt ?
Thank you!
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\Users\user\Desktop\Check_File.txt -append
$Computers = Get-Content -Path C:\Users\user\Desktop\ip.txt
foreach($Computer in $Computers){
$User = "admin"
$Password = "paSSw"
$Command = "dir C:\Proset\SRM\abc.ddc && hostname"
$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
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command | Select -Expand Output > result.txt
}

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

Powershell SSH multiple user

I have this script, I want run $command on multiple machines but some have different user/pass. How can I make to connect >if user/pass 1 is wrong try > user1/pass1 or user2/pass2. And return in result.txt $command result + 'connected with user2' +ip $Computers in one line or directly in .csv file.
$Computers = Get-Content -Path C:\Users\me\Desktop\ip.txt | Where-Object { $_ -match '\S' }
foreach($Computer in $Computers){
Write-Host $Computer
$User = "user" # if user is wrong try user and pass 1 ; or user pass 2
$Password = "pass"
$User1 = "user1"
$Password1 = "pass1"
$User2 = "user2"
$Password2 = "pass2"
$Command = 'hostname && systeminfo | findstr /B /C:"OS Name"'
$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
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command | Select -Expand Output | Add-Content -Path result.txt
}
In my case example of result.txt
John-PC ; Windows 10 ; IP: $Computers ; Connected with $user1

Restart machine using powershell script

I am running the below code but the restart is not working. My intention was to run restart command parallelly on all remote machines at once.
$YourFile = gc "machinelst.txt"
$username = "user1"
$password = "pass1"
$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $secpw)
foreach ($computer in $YourFile)
{
Invoke-Command -ComputerName $computer -credential $cred -ErrorAction Stop -ScriptBlock { Restart-Computer -ComputerName $computer -Force } -AsJob
}
That looks like its the output from Get-Job - could you try Receive-Job $id (Receive-Job 80).
Should give you the actual exception.
This likely runs in parallel just like invoke-command does with an array of computernames:
restart-computer computer01,computer02,computer03,computer04,computer05
Or this. It takes a couple minutes for the winrm service to come back, but they all seem to reboot at the same time.
$c = get-credential
$list = 1..10 | % tostring computer00
restart-computer $list -wait -protocol wsman -cr $c
try this (you will can add -asjob if it's work) :
$username = "yourdomain\user1"
$password = ConvertTo-SecureString "pass1" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
get-content "machinelst.txt" | %{
Restart-Computer -ComputerName $_ -Authentication default -Credential $cred
}
if you want use job, you can do it :
$listjob=#()
get-content "machinelst.txt" | %{
$listjob+=Restart-Computer -ComputerName $_ -Authentication default -Credential $cred -AsJob
}
$listjob | Wait-Job -Timeout 30
$listjob | %{
if ($_.State -eq 'Failed' )
{
Receive-Job -Job $_ -Keep
}
}

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
}
}

select multiple switch statements

I have the script below that lets me switch between the different elements and runs the functions in them one by one.
But what I need to do now is make it so I can select multiple ones and have them run and pause between them to verifiy if things were loaded correctly. So that way I don't run into the issue having to re rerun the full script again and redo the same one over.
Can anybody show me how to do this? I am lost as to how to get this completed and working properly.
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
while ($ElementDistro -notmatch "^(TV30|TV30BP|TV30LM|TV30PV|LT101|XR2|MU11|SAP)$")
{
write-host "you have enterd an error" -ForegroundColor Red
write-host "You must type TV30 or TV30BP or TV30LM or TV30PV or LT101 or XR2 or MU11 or SAP"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
}
switch ($ElementDistro)
{
'TV30'
{
# Do TV30 Stuff
write-host "you have entered TC TV30"
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30BP'
{
# Do TV30BP Stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
# exit-pssession
break
}
'TV30LM'
{
# Do TV30LM stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30PV'
{
# Do TV30PV stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'LT101'
{
# Do LT101 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'XR2'
{
# Do XR2 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'MU11'
{
# Do TF10 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'SAP'
{
# Do SAP stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
}
break
}
If you got at least V3, you can use Out-GridView with -OutPutMode Multiple as a menu to select multiple items from:
$Menu = 'TV30','TV30BP','TV30LM','TV30PV','LT101','XR2','MU11','SAP','ALL'
$Choices = $Menu | Out-GridView -OutputMode Multiple -Title 'Select Locations you want to run staging, and click OK.'
Switch ($Choices)
{
.....
The quick answer is that Powershell's switch statement accepts an array for input. If you leave out the break statement at the end of each switch case it will execute each case that is a match. Enter your choices as a comma-separated list and put them into an array using the split statement.
Each choice in you $Choices array will be executed. If you put a Pause statement where your break statements are you can pause at the completion of each step.
$Choices = #('TV30','MU11')
switch ($Choices)
{
'TV30' {some code}
'TV30BP' {some code}
'MU11' {some code}
}