ReadPower.ps1 contain the following. And able to get output on output.csv locally.
$port= new-Object System.IO.Ports.SerialPort COM7,19200,None,8,one
$port.open()
$port.WriteLine("?p")
$port.ReadLine()
$MachinePower= $port.ReadLine()
$date = Get-Date
$TextTOsend = "MachineName,"+ $date +"," +$MachinePower
$TextTOsend | Out-File output.csv -Append -Encoding ASCII
$port.Close()
When run remotely, using this
psexec \\RemotePC -s -u username -p password powershell C:\ReadFAMLaser\ReadPower.ps1
No output on output.csv
Did I miss out anything?
Related
Problem: I need to pipe ffmpeg stream to a variable using PowerShell. The code below "works" (95% of the time), the problem is some Unicode characters do not exist when printed to the console which results in a malformed image.
Question: Is there a way to pipe bytes, decimal values, or even binary values instead of Unicode to console from ffmpeg???
clear-host
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$ffmpeg = "C:\ffmpeg\bin\ffmpeg.exe"
$input = "C:\Users\Jukari\Desktop\test\test1.mp4"
$output = "C:\Users\Jukari\Desktop\test\test1.bmp"
$screenshot = 3
[console]::OutputEncoding = New-Object System.Text.UnicodeEncoding
[string]$image = & cmd /u /c "chcp 65001 > NUL && $ffmpeg -i `"$input`" -hide_banner -loglevel error -ss $screenshot -vframes 1 -an -c:v bmp -f image2pipe - 2>&1" 2>&1 | Out-String -Stream
[console]::OutputEncoding = New-Object System.Text.UTF8Encoding
$bytes = [System.Text.Encoding]::Unicode.GetBytes($image)
$stream = new-object System.IO.MemoryStream(,$bytes)
$image_out = [system.drawing.Image]::FromStream($stream,1,1)
write-host $image_out.Height
write-host $image_out.Width
if(Test-Path -LiteralPath $output)
{
Remove-Item $output
}
$image_out.Save($output)
$image_out.Dispose()
Thank you in advance!
Hi I have a script to automate some tasks, running in powershell core v.7.+.
In one of these scripts when I run the command inside the ps1 file and the special characters returned is encoded and I can't decode to right format, below the command used to do this and the return:
// the variable $script is my command its a ask-cli command to work in alexa
$model = pwsh -Command $script
/*
* when I running the script from here the special characters returned is these:
* "nächste",
* "nächstgelegene"
*/
But when I run the same command directly in the terminal the strings returned are:
/*
* "nächste",
* "nächstgelegene"
*/
I would like to know how can I run the command inside the file without encode the return.
I already tried some things as:
$encoding = [System.Text.Encoding]::Unicode
$model = pwsh -Command $script
Write-Output $model
$model = $encoding.GetBytes($model)
$model = $encoding.GetString($model)
But don't work as expected, I don't know more how I can to this, if someone could help me with this I appreciate too much.
Try returning the string as bytes and then decode it from the place you are calling the function pwsh. This would preserve it from any changes. What you're doing is converting it into bytes after receiving it then returning it to string.
Below my script:
(Get-Content "$currentPath\skill-package\skill.json" -Raw | ConvertFrom-Json).manifest.publishingInformation.locales.PSObject.Properties | ForEach-Object {
$lang = $_.Name
Write-Output "Profile: $profile skill-id: $skillId language: $lang"
$script = "ask smapi get-interaction-model -l $lang -s $skillId -p $profile -g $env"
Write-Output 'Running script'
Write-Warning $script
# $encoding = [System.Text.Encoding]::ASCII
$model = pwsh -Command $script
Write-Output $model
$model = $model
| ConvertFrom-Json -Depth 100
| Select-Object * -ExcludeProperty version
| ConvertTo-Json -Depth 100
# out-file "$file$lang.json" -InputObject $model -Encoding ascii
Write-Output "New model saved locally $file$lang.json"
}
Write-Warning 'Finished!!!'
(Get-Content "$currentPath\skill-package\skill.json" -Raw | ConvertFrom-Json).manifest.publishingInformation.locales.PSObject.Properties | ForEach-Object {
$lang = $_.Name
Write-Output "Profile: $profile skill-id: $skillId language: $lang"
$script = "`$command = ask smapi get-interaction-model -l $lang -s $skillId -p $profile -g $env;`$command = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes(Invoke-Expression `$command));`$command"
Write-Output 'Running script'
Write-Warning $script
# $encoding = [System.Text.Encoding]::ASCII
$model = pwsh -Command $script
$model = Text.Encoding::Unicode.GetString([Convert]::FromBase64String($model))
Write-Output $model
$model = $model
| ConvertFrom-Json -Depth 100
| Select-Object * -ExcludeProperty version
| ConvertTo-Json -Depth 100
# out-file "$file$lang.json" -InputObject $model -Encoding ascii
Write-Output "New model saved locally $file$lang.json"
}
Write-Warning 'Finished!!!'
After many researches, I could find something more easiest to solve my problem.
Powershell has by default a different output encoder used in these cases, and the only thing I need to do it's change it.
I used the command:
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
I find this question explaining how this work and this help a lot, for more question please check this answer.
I have a script that calls notepad on a remote computer with psexec. Is there a way I can get the Process ID after it is started?
Here is what I have:
$PCname = "MyPC"
$SessionID = "2"
$Program = "Notepad.exe"
$FilePath = "C:\temp\"
$FileName = "Test.txt"
set-alias psexec "C:\PsExec\psexec.exe"
&psexec -s -d -i $SessionID \\$PCname $Program $FilePath\$FileName
After running I get this in the output window that shows the Process ID:
Connecting to MyPC...Starting PSEXESVC service on MyPC...Connecting
with PsExec service on MyPC...Starting Notepad.exe on MyPC...
Notepad.exe started on MyPC with process ID 8352.
How can I grab the process ID?
You can use the Select-String cmdlet to grab the process ID using a regex:
&psexec -s -d -i $SessionID \\$PCname $Program $FilePath\$FileName |
Select-String 'process ID (\d+)' |
ForEach-Object {$_.Matches.Groups[1].Value}
$a = (gps -ComputerName PcName| where{ $_.ProcessName -eq "Notepad.exe"} | select Id)
$a.Id contains the wanted Id
I have working script that use Invoke-Expression to execute psexec in Powershell ISE
<# $password is encrypted password, need to unencrypt to pass it to psexec #>
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$enable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_enable.ps1"
Invoke-Expression $enable_command
I don't want to use Invoke-Expression because it outputs data, including PLAINTEXT password onto Powershell ISE console. But this script with Start-Process doesn't work
<# $password is encrypted password, need to unencrypt to pass it to psexec #>
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
Start-Process -FilePath D:\PSTools\PsExec.exe -ArgumentList '$comp', '-u', 'Administrator', '-p', '$str', '-accepteula', 'powershell.exe', 'c:\share\ps_enable.ps1'
How to fix?
How about just capturing the Invoke-Expression in a variable, or piping it to Out-Null?
$CmdOutput = Invoke-Expression $enable_command
or
Invoke-Expression $enable_command | Out-Null
Edit: Ok, I forgot that PSExec likes to use StdErr as a method for displaying some of it's text, and that portion would not be captured by these. What you can do is redirect StdErr to StdOut, and either pipe to Out-Null or capture it as suggested. Try this:
$CmdOutput = Invoke-Expression $enable_command 2>&1
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