Powershell equivalent of the "tail" command ALMOST works remotely - powershell

I am looking for a Windows 7 equivalent of the "tail" command and thought I had found it with this Powershell equivalent -
C:\>powershell -command "& {Get-Content file.txt | Select-Object -last 100}"
If I use this in the CMD prompt on my own Windows 7 PC, returns the info just fine. I can even input/append it into another file.
However, when I log on remotely to another PC (via openSSH), the command works, but it never drops me back to a command prompt - just hangs after showing me the last 100 lines of the file. Which means this won't work for a batch file I'm trying to edit for about 300 remote Windows 7 PCs.
Any ideas?

After trying MANY different suggestions found all over online, FINALLY found one that worked!
And the answer is within the Batch file itself. My batch file to call this Powershell line was just this:
Powershell.exe -noprofile -executionpolicy Bypass C:\log\Tail.ps1
:end
Again, works great if you're using it on the very PC from which you want it to run/get the information. But not remotely. Finally found you just need to add "< nul" to the end of your call to Powershell in your batch file, just like this
Powershell.exe -noprofile -executionpolicy Bypass C:\log\Tail.ps1 <nul
:end
What the other person wrote is what finally made sense: "My research has shown that PowerShell runs the commands in the script indicated through the -File switch and then waits for additional PowerShell commands from the standard input (my brief experimentation with the -Command switch demonstrated similar behavior). By redirecting the standard input to nul, once PowerShell finishes executing the script and 'reads end-of-file' from the standard input, PowerShell exits."
Found here at this page - Powershell script gets stuck, doesn't exit when called from batch file
so credit actually goes to #Gordon Smith

Since your running the command with -command "...", according to the docs, you need to specify the -noexit flag to stop powershell from exiting after the command is run.
powershell -command "& {Get-Content file.txt | Select-Object -last 100}" -noexit
When you add this to a batch file you'll probably need -noprofile and -noninteractive as well - though for remote commands you might want to spawn a process for better control and error handling. Also, if this doesn't work the problem would probably be with how OpenSSH is handling something (this worked for me on a test-server with remote connect)

Related

Answer File PowerShell Script To Run On First Boot Of a Fresh Install

I added this FirstLogonCommand to my answer file.
powershell.exe -executionpolicy bypass -NoExit -file D:\DisableGuard.ps1 -Disable
I don't want it to exit to see the output so I added -NoExit
The -Disable switch is the correct switch for the script.
Am I formatting it correctly to run with that switch in an answer file?
It runs correctly if I run it direct from an admin command prompt.
If you run help about_PowerShell.exe in PS it will show you the command, syntax and formatting.
It looks like you have the correct syntax

Batch script not calling Powershell

I have a batch script that calls a Powershell file in administration mode. I found this code a while ago, and it's worked great ever since:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command
"& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File %PSFile%' -Verb RunAs}";
This time though, I called the batch script from another program. This program says the process worked, but it didn't actually do anything. Examining the logs from echo, I can see the batch script is being called, but it's not calling Powershell. I tried running the batch script manually, and it calls PS fine, so something with how the batch script is being called by the other program is messing with how it calls PS.
This in mind, I tried changing the batch script to directly run my .ps1 file, instead of starting a new admin instance of powershell to start it. My new .bat file looked like this:
Powershell -File %PSFILE% -Verb RunAs
Calling this from the other program sucessfully calls my Powershell script, but I get a bunch of errors from the PS script, since it's not an admin PS session like it needs to be.
How can I change my batch script to call Powershell as an admin, without using Powershell to call itself (which doesn't seem to work with the program that needs to run it)?
EDIT: After trying a bunch of tweaks, I've found I don't even need to be in admin mode to do what this script does. However, I still get access denied errors when running it through the program (admin or not). So something about running it from the program is making it need more permissions than when I run the batch script manually.
This is what I do (inside the .bat file):
If the .bat is NOT running as admin
powershell.exe -Command "powershell.exe 'C:\path\to\script.ps1' -Verb runAs"
If the .bat is running as admin
powershell.exe -ExecutionPolicy Bypass -Command "C:\path\to\script.ps1"
You could use a small utility I wrote called elevate32.exe/elevate64.exe.
elevate64 -- C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "d:\path to script\scriptfile.ps1"
elevate32.exe (32-bit version) and elevate64.exe (64-bit version) basically elevate whatever command line you pass to them.
You can get it here (ElevationToolkit1.zip):
http://www.westmesatech.com/misctools.html
An alternative is to use a short WSH script that, when called, provokes elevation. An example is on Aaron Margosis' blog here:
https://blogs.msdn.microsoft.com/aaron_margosis/2007/07/01/scripting-elevation-on-vista/
Script:
// elevate.js -- runs target command line elevated
if (WScript.Arguments.Length >= 1) {
Application = WScript.Arguments(0);
Arguments = "";
for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
if (Index > 1) {
Arguments += " ";
}
Arguments += WScript.Arguments(Index);
}
new ActiveXObject("Shell.Application").ShellExecute(Application, Arguments, "", "runas");
}
else {
WScript.Echo("Usage:");
WScript.Echo("elevate Application Arguments");
}
The limitations of this approach is that it relies on the WSH command-line parser and can't wait for the program to terminate. These limits may not be a problem in your scenario.
Looks like I was totally off as to the problem source. This was a permissions error on some folders I was editing. The program I was running the scripts through acts as a separate service. I had to add that with modify permissions to the security groups of all the folders I was editing. No elevation required in the scripts, just modifying permissions.

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

Running PowerShell Scripts in Komodo Edit

I have a hard time trying to run PowerShell Scripts from the "Run Command" within Komodo Edit on Windows 7.
The command that I am using is:
powershell -File "%F"
When I run it, it does not return anything to the console, it just keeps running till I terminate it.
I have tested it, with the following simple script:
Write-Host "Hello World"
This is a known issue where powershell.exe waits for a STDIN prompt to return in certain cases, causing it to hang when no input is provided.
Solutions
Use -InputFormat None to indicate STDIN will not be used:
powershell.exe -InputFormat None -File "%F"
Forward null input from the outer command scope so that STDIN returns:
powershell.exe -File "%F" < NUL
Similar Questions
2010-11-09 Silently executing a PowerShell script from WiX Hangs PowerShell
2010-11-21 Running PowerShell from MSdeploy runcommand does not exit
2011-07-26 Exiting VMware vSphere PowerCLI command prompt?

Set up PowerShell Script for Automatic Execution

I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:
One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)
A file that I can double-click to run the above (I would use this method when manually testing components of my build process)
I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.
From http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx
If you're willing to sully your beautiful PowerShell script with a little CMD, you can use a PowerShell-CMD polyglot trick. Save your PowerShell script as a .CMD file, and put this line at the top:
#PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %*);'+[String]::Join(';',(Get-Content '%~f0') -notmatch '^^#PowerShell.*EOF$')) & goto :EOF
If you need to support quoted arguments, there's a longer version, which also allows comments. (note the unusual CMD commenting trick of double #).
##:: This prolog allows a PowerShell script to be embedded in a .CMD file.
##:: Any non-PowerShell content must be preceeded by "##"
##setlocal
##set POWERSHELL_BAT_ARGS=%*
##if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
##PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^##'))) & goto :EOF
Save your script as a .ps1 file and launch it using powershell.exe, like this:
powershell.exe .\foo.ps1
Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.
Run Script Automatically From Another Script (e.g. Batch File)
As Matt Hamilton suggested, simply create your PowerShell .ps1 script and call it using:
PowerShell C:\Path\To\YourPowerShellScript.ps1
or if your batch file's working directory is the same directory that the PowerShell script is in, you can use a relative path:
PowerShell .\YourPowerShellScript.ps1
And before this will work you will need to set the PC's Execution Policy, which I show how to do down below.
Run Script Manually Method 1
You can see my blog post for more information, but essentially create your PowerShell .ps1 script file to do what you want, and then create a .cmd batch file in the same directory and use the following for the file's contents:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"
Replacing MyPowerShellScript.ps1 on the 3rd line with the file name of your PowerShell script.
This will allow you to simply double click the batch file to run your PowerShell script, and will avoid you having to change your PowerShell Execution Policy.
My blog post also shows how to run the PowerShell script as an admin if that is something you need to do.
Run Script Manually Method 2
Alternatively, if you don't want to create a batch file for each of your PowerShell scripts, you can change the default PowerShell script behavior from Edit to Run, allowing you to double-click your .ps1 files to run them.
There is an additional registry setting that you will want to modify so that you can run scripts whose file path contains spaces. I show how to do both of these things on this blog post.
With this method however, you will first need to set your execution policy to allow scripts to be ran. You only need to do this once per PC and it can be done by running this line in a PowerShell command prompt.
Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs
Set-ExecutionPolicy RemoteSigned -Force is the command that actually changes the execution policy; this sets it to RemoteSigned, so you can change that to something else if you need. Also, this line will automatically run PowerShell as an admin for you, which is required in order to change the execution policy.
Source for Matt's answer.
I can get it to run by double-clicking a file by creating a batch file with the following in it:
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe LocationOfPS1File
you can use this command :
powershell.exe -argument c:\scriptPath\Script.ps1