PSExec registry file remotly - powershell

I am trying to execute a PowerShell to execute a reg file remotly
This is what I have at the moment:
$computer = 'IP';
$username = 'user';
$password = 'password';
$reg = 'regedit /s //ip/teste.reg';
$reg_command = "psExec -i -d -c -f -s \\$computer -u $computer\$username -p $password `"$reg`"";
Write-Output "Inserting regestry file...";
Invoke-Expression $reg_command;
I have psExec in my computer, but I don't know how I would add the path executable for PSExec in the code.

Related

Powershell pass parameter to sqlcmd

I'm trying to pass username, db and pwd as variable to sqlcmd - but it does not seem to like it.
This works
#Run SQLCMD for each file
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S 123.database.net -d EMR -U user1-P mypassword -i $FileName.FullName
}
This does not work
#Run SQLCMD for each file
$db = "123.database.net"
$dbId = "user1"
$pwd = "mypassword"
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S $db -d EMR -U $dbId -P $pwd -i $FileName.FullName
}
Error message
sqlcmd : Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login failed for user 'user1'..
sqlcmd has its scope .Make the variables as Global. Then it should pick it.
DO this:
#Run SQLCMD for each file
$global:db = "123.database.net"
$global:dbId = "user1"
$global:pwd = "mypassword"
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S $db -d EMR -U $dbId -P $pwd -i $FileName.FullName
}
Note: I have not taken into consideration that your second scriptlet is throwing any error in particular or not.

how to "sudo root" with posh-ssh (powershell)

i am using posh-ssh to connect to my ssh server do some commands start with su root,but i can not switch user to root sucessfully.
PS C:\> $rootpwdSec = ConvertTo-SecureString $rootpwd -AsPlainText -Force
PS C:\> Invoke-SSHStreamExpectSecureAction -Command 'su ' -ExpectString 'Password:' -SecureAction $rootpwdSec -ShellStream $stream
True
PS C:\> $stream.read();
[root#aaaaaa-test admin]#
PS C:\> Invoke-SSHCommandStream -SessionId $SessionId -Command 'id'
uid=500(admin) gid=500(admin) groups=500(admin) context=user_u:system_r:unconfined_t
PS C:\>
how can run my command as root?
What I noticed when working with posh-ssh and ubuntu was I was failing to sudo up to root using "sudo su -" due to the ExpectString. It was expecting "[sudo] password for (username):" and I was merely providing "password:"
$stream = $session.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 100)
$user = Invoke-SSHCommand $session -Command "whoami"
$SSHusersName = $user.Output | Out-String
$SSHusersName = $SSHusersName.Trim()
$results = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($SSHusersName):" -SecureAction $secpas
$stream.Read()
This was how I was able to sudo to root. Again it may be different for you depending on what *nix variant you are connecting to.

How to bind the -v parameter of sqlcmd from a PowerShell

The following code, setting the -v parameter directly is working
$sqlcmd = #(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]
$path1 = 'D:\somescript.sql'
& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v Mandant=1 SAPMandant="009" SAPEinrichtung="0001"
But I need a way to set these values from a PowerShell variable.
I tried:
$sqlcmd = #(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]
$path1 = 'D:\somescript.sql'
$sqlcmdparameters = 'Mandant=1 SAPMandant="009" SAPEinrichtung="0001" '
& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $sqlcmdparameters
I found this on SO, but it didn't help me.
I found the following solution for PowerShell V2
$sqlcmd = #(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]
$path1 = 'D:\somescript.sql'
$cmdparameters = #(
'Mandant=1',
'SAPMandant="009"'
)
& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $cmdparameters
Try using start-process. That's what I do for Powershell command-line parsing issues. First try invoke operator (&) and if that doesn't work wrap it in a start-process call.
$tempFile = [io.path]::GetTempFileName()
$exitCode = (start-process -FilePath $sqlcmd -ArgumentList #"
-b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $sqlcmdparameters
"# -Wait -RedirectStandardOutput $tempFile -NoNewWindow -Passthru).ExitCode
When using start-process typically you'll need to capture exitcode and also redirect output to temp file in get back the results. I'll then have some code to check $exitcode and cleanup temp file in try/catch/finally block

Starting Powershell elevated from PSExec (enable-psremoting)

I'm trying to enable-psremoting with PSexec on my servers with the following command:
psexec.exe \\server cmd /c "echo . | powershell (-verb runas -argumentlist (enable-psremoting -force))"
but it doesn't work. I'm guessing I'm messing up my double quotes. Any help?
Sune:)
Thanks for commenting all! I found out how to do it, and this is the completed code:
$user = "youruser"
$p = Read-Host "Enter domain password for $adminuser"
cls
$expression1 = "enable-psremoting -force"
$commandBytes1 = [System.Text.Encoding]::Unicode.GetBytes($expression1)
$encodedCommand1 = [Convert]::ToBase64String($commandBytes1)
$expression2 = "Set-ExecutionPolicy remotesigned -Force”
$commandBytes2 = [System.Text.Encoding]::Unicode.GetBytes($expression2)
$encodedCommand2 = [Convert]::ToBase64String($commandBytes2)
$expression3 = "Restart-Service winrm”
$commandBytes3 = [System.Text.Encoding]::Unicode.GetBytes($expression3)
$encodedCommand3 = [Convert]::ToBase64String($commandBytes3)
foreach ($server in (get-content c:\temp\enablepsremotinglist.txt))
{
echo " "
echo "Running on $server"
echo "--------------------------------------- "
echo " "
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand1"
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand2"
psexec.exe \\$server -h -u no\$user -p $p cmd /c "echo . | powershell -EncodedCommand $encodedCommand3"
}
I hope this can be of help to someone else one day:)
PS: Please keep in mind that this send your adminpassword as clear text..
It looks like you are trying to invoke PowerShell to run elevated. This might not be possible to do remotely... I was able to get this to work against a machine without UAC enabled (2003 server):
$c = Get-Credential
$u = $c.UserName
$p = $c.GetNetworkCredential().Password
$path = "C:\SysinternalsSuite"
& "$path\psexec.exe" \\server -u $u -p $p powershell.exe -Command "Enable-PSRemoting -Force"
For some reason though I had to press enter a couple times on the shell for it to keep spitting out output and eventually return me to a prompt. Not sure what's up with that...
You don't need PSExec for that. Check this script by PowerShell developer Lee.
http://poshcode.org/2141

Output ssh command to text file in powershell

I am trying to output the following command to a text file in powershell, but I cannot seem to get it working:
ssh -v git#git.assembla.com | Out-File C:\output.txt
As stated in the post below with using native apps, you could try using Start-Process, e.g.
Start-Process ssh "-v git#git.assembla.com" -NoNewWindow -RedirectStandardOutput stdOut.log -RedirectStandardError stdErr.log; gc *.log; rm *.log
Working on the same problem I made a detail post on my blog How to SSH from Powershell Using Putty\Plink but the short version is this bit of code. But sure you try it after installing putty.
Function Invoke-SSHCommands {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)
$Target = $Username + '#' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"
#Build ssh Commands
$remoteCommand = ""
$CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }
#plist prompts to accept client host key. This section will login and accept the host key then logout.
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
}
#format plist command
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)
#ready to run the following command
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
$msg
}
$PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
$Username = "remoteshell"
$Password = "pa$$w0rd"
$Hostname = "Linuxhost"
$Commands = #()
$Commands += "ls"
$Commands += "whoami"
Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands