How to execute Windows command (Get-Content) from PowerShell in Windows Server - windows

My server is Windows Server. I would like to replicate the Unix tail command in Windows Server.
Unix Server: tail -f test.txt
PowerShell: Get-Content test.txt
How to execute in Windows Server?
Below command is not working:
powershell -File "Get-Content test.txt"
Error message:
Unable to execute program 'powershell -File "\"Get-Content...
Any idea?

Get-Content is not a file; it is a cmdlet. The -file parameter to Powershell.exe instructs Powershell to read the file supplied and execute the commands in it, as a script.
You can pass commands directly to Powershell by using the -command parameter; the parameter can be a quoted string, which is interpreted as a Powershell command. You would therefore want to use
powershell -command "Get-Content test.txt"
in the simplest case.
Note that Powershell.exe must be in your system path; if it is not, you would need to supply the full path to powershell, e.g.,
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -command "Get-Content text.txt"
This question is very similar - perhaps essentially identical - to Unix tail equivalent command in Windows Powershell; I would recommend reading that question and its answers as well.
Additionally, exploring the help for Get-Content will provide useful information.

Working fine after setting full path of powershell.exe and without any quotes
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content test.txt

Within a powershell window :
Get-Content test.txt
command returns :
hello world.
i'm inside test.txt.
bye.

Related

Powershell on ansible-playbook remote host

I have a PowerShell script ex1.ps1 which takes user inputs and ex1.ps1 has commands to open a new PowerShell to execute an exe file:
Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList "-command C:\APPLICATION1.exe`
I want to execute ex1.ps1 on a remote host. I am trying to call ex1.ps1 using Ansible-playbook as:
# ansible-playbook script
- name: Run basic PowerShell script
win_powershell:
script: |
powershell.exe -ExecutionPolicy ByPass -File C:/Users/ex1.ps1
It is executing fine but in remote host there is no PowerShell prompt open to get the inputs.
You shouldn't be expecting manual input when deploying with a tool like Ansible. I don't know the actual program you are trying to run but the best solution here is to figure out the required parameters for the program to install/start/run without user interaction.
If you are able to provide the name of the program (and it's not something internal to your organization) a more complete answer may be able to be provided.
Unrelated to your question, unless you've over-generalized your code for this question there isn't a reason to call powershell.exe from within PowerShell just to run an executable. You can either use Start-Process or the call operator & directly with the exe path in question.
I have an answer here that goes over Start-Process and the usage of & in a bit more detail.

what is `powershell -c` or any execution parameters(e.g. powershell -nop -NonI)?

Apologize for the noob question but I did hours of research but still so confused...
The problem:
In powershell we can write this:
$i = 'hello'
echo $i # hello
easy. But:
powershell -c "$j = 'hello'; echo $j"
won't work and it throws error at our face.
The question: what is the error, and what is the correct grammar to use powershell -NoP -NonI -c "//..."? I see quite a few scripts written in this format. I even wonder if it is a linux thing...? but we are talking about powershell right?...
Any help would be appreciated.
It depends on where are you executing the command.
Inside cmd.exe this will work, because the commands don't render special meaning to cmd. But in powershell it will fail because of the special characters, use powershell -c '$j = ''hello''; echo $j' instead.
Also -c,-NoP etc. are parameters of powershell.exe:
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-ConfigurationName
Specifies a configuration endpoint in which Windows PowerShell is run.
This can be any endpoint registered on the local machine including the
default Windows PowerShell remoting endpoints or a custom endpoint having
specific user role capabilities.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -ConfigurationName AdminRoles
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
-NoP is no profile means not load powershell profile.
-NonI is to run non-interactive session.
-c execute command/scriptblock and exit.

How to sudo on powershell on Windows

Whenever I need to run a powershell script it complains of security, if I add powershell.exe -nologo -executionpolicy bypass -File .\install.ps1 I still get permission denied unauthorizedAccessException. I just want to run this install script, what is the sudo equivalent to type on the powershell on windows?
If you are using Chocolatey (a package manager), you can install a package named sudo.
Then you can use sudo like Linux 😋
Note: If you're looking to add general-purpose, prepackaged sudo-like functionality to PowerShell, consider the
Enter-AdminPSSession (psa) function from this Gist, discussed in the bottom section of this answer.
If you are running from PowerShell already, then use Start-Process -Verb RunAs as follows:
Start-Process -Verb RunAs powershell.exe -Args "-executionpolicy bypass -command Set-Location \`"$PWD\`"; .\install.ps1"
Note:
The script invariably runs in a new window.
Since the new window's working directory is invariably $env:windir\System32, a Set-Location call that switches to the caller's working directory ($PWD) is prepended.
Note that in PowerShell (Core) 7+ (pwsh.exe) this is no longer necessary, because the caller's current location is inherited.
Executing Set-Location necessitates the use of -Command instead of -File.
A general caveat is that -Command can change the way arguments passed to your script are interpreted (there are none in your case), because they are interpreted the same way they would be if you passed the arguments from within PowerShell, whereas -File treats them as literals.
If you're calling from outside of PowerShell, typically from cmd.exe/ a batch file, you need to wrap the above in an outer call to powershell.exe, which complicates things in terms of quoting, unfortunately:
powershell.exe -command "Start-Process -Verb RunAs powershell.exe -Args '-executionpolicy bypass -command', \"Set-Location `\"$PWD`\"; .\install.ps1\""
Interactively, of course, you can:
Right-click the PowerShell shortcut (in your taskbar or Start Menu, or on your Desktop), select Run as Administrator to open a PowerShell window that runs with admin privileges, and run .\install.ps1 from there.
Alternatively, from an existing PowerShell window, you can open a run-as-admin window with Start-Process -Verb RunAs powershell.exe, as in AdminOfThings' answer.
You can utilize the Start-Process command and then use parameter -Verb runas to elevate. This works great for starting an elevated process.
I created a sudo function like this and added it to my powershell profile:
function sudo {
Start-Process #args -verb runas
}
Example: Open notepad as Admin to edit hosts file
sudo notepad C:\Windows\System32\drivers\etc\hosts
If you want to elevate a Powershell command, you can create a simple function like this:
function Start-ElevatedPS {
param([ScriptBlock]$code)
Start-Process -FilePath powershell.exe -Verb RunAs -ArgumentList $code
}
Then, call the function and pass command wrapped in {} (script block)
Example: Elevate to create a symbolic link
Start-ElevatedPS { New-Item -ItemType SymbolicLink -Name mySymlink.ps1 -Target C:\myTarget.ps1 }
You can start PowerShell with the Run as Administrator option:
Start-Process powershell -Verb runAs
As of today (October 2021), winget install gerardog.gsudo did the trick (on windows 10 home edition). Edit: Tested on Windows 11 as well (April 2022)
after that, you can do this:
gsudo notepad C:\windows\system32\something-editable-by-admin-only.txt
To test if it's working, or in your case:
gsudo powershell.exe install.ps1
You will be prompted by windows` UAC to elevate your priveleges by gsudo, and you can read the source code here: https://github.com/gerardog/gsudo
If you have a corporate policy that blocks scripts execution, then yes. ByPass does not change your profile (user context) state. That is not the design (use case) for any of those switches regarding Execution Policies.
There is not a direct comparison of sudo in Windows, this has nothing to do with PowerShell. You are either admin in a session / app or you are not. If you are installing software, that means you must be admin. If you are doing global system-wide changes, that means you must be admin.
There are folks who have strived to implement scripts, wrapper functions and or modules to mimic sudo …
Module from the MS PowerShell gallery.
Sudo 0.9.3
Use functionality similar to sudo in PowerShell
From GitHub
Sudo for PowerShell
Sudo for PowerShell Installation From PowerShell, create a $profile if
you don't have one:
if (!(test-path $profile)) { new-item -path $profile -itemtype file -force }
Open the profile in notepad:
notepad.exe $profile
Add the following line and save the file:
. /path/to/sudo.ps1
sudo will be available in all new PowerShell windows Usage
sudo application [arguments ...]
...but that does not change what Windows expects when dealing with security boundaries.
See also this Q&A
Sudo !! equivalent in PowerShell
$^ is a variable that expands to the last executed Powershell command.
You can run a command as another user using runas, so the following
works:
runas /user:domain\administrator $^
To shorten that up a bit, you can do some magic with aliases. Take a
look at this Technet article for more info.
EDIT: One caveat - $^ only executes the first command in a pipeline or
multi-command line. If you need to redo an entire command that is
peppered with pipes or semicolons, use Invoke-History instead (which
defaults to the last full command in its entirety).

Running powershell command from cmd

I'm new in windows environment. How can I execute the following powershell command from cmd "hello gourav how are you1" | Out-File filename -append
Open cmd from Run and execute powershell /? to know all the options you have.
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-ConfigurationName
Specifies a configuration endpoint in which Windows PowerShell is run.
This can be any endpoint registered on the local machine including the
default Windows PowerShell remoting endpoints or a custom endpoint having
specific user role capabilities.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -ConfigurationName AdminRoles
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
Maybe a bit off-topic but this does the same trick without powershell (i.e. directly from cmd prompt):
echo Your text >>filename
simple
#ECHO off
SET LONG_COMMAND=^
if ($true)^
{^
$Resolution=Get-DisplayResolution;^
Write-Host $Resolution;^
}
START Powershell -noexit -command %LONG_COMMAND%
with return
#echo off
set "psCommand="[Environment]::GetFolderPath('DesktopDirectory')""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
echo DesktopDirectory = %folder%
you can use powershell.exe in cmd to execute powershell command.
powershell.exe "your command"
like
powershell.exe "\"hello gourav how are you1\" | Out-File filename -append"
And you can enter interact interface in powershell using powershell directly

powershell command invoke-sqlcmd in batch script

I have a powershell command that I want to be run in batch script. It works well in powershell window but I cannot call it properly in batch script.
the powershell command goes like this:
invoke-sqlcmd -inputfile "D:\Reports\sql.sql" -ServerInstance SERVER1 | export-csv "D:\Rpt\historical\sample1.csv" -Force -En UTF8
I hope somebody could help me out. Also, is it possible to include batch variable in replace of the file path for input and output file instead of putting the whole path in powershell command (stil run inside in batch script)?
Thanks.
I have found that works :)
to run the invoke-sqlcmd within batch script:
I have use this line:
powershell -Command "& {Add-PSSnapin SqlServerCmdletSnapin100; Add-PSSnapin SqlServerProviderSnapin100; invoke-sqlcmd -inputfile '%sqlPath1%' -ServerInstance %Server% | export-csv '%out_path1%\%out1_fn%' -Force -En UTF8;}"
works like charm yay! ^_^

Resources