Escape special chars in powershell commands - windows

I am new to powershell, but I am facing a very basic problem. When I am running the following command powershell complains. It seems to have issues with the special chars: [*, =, &, <, >]. Any ideas how do I escape them ? This is powershell version 2. [I am using winexe to run the powershell command from a linux box. If I copy paste the ps command it seems to work fine, but remotely running it cause powershell to complain.]
winexe "cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=&<+>%N' -extra_logging '0' "
dos charset 'CP850' unavailable - using ASCII The string starting: At line:1 char:106 + Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -lun <<<< 'B*= is missing the terminator: '. At line:1 char:110 + Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -lun 'B*= <<<< + CategoryInfo : ParserError: (B*=:String) [], ParentContainsErro rRecordException + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
The system cannot find the file specified. The system cannot find the file specified.

The problem isn't powershell but the regular command shell. Making a reasonable assumption about what winexe does, the relevant part of the command is
cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=&<+>%N' -extra_logging '0'
which contains some special characters interpreted by the command shell. Content in single quotes is not considered to be quoted, so you'll need to explicitly quote them. Just to make life difficult, because you're using piping, the characters are processed twice so you'll need to double-quote:
cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=^^^&^^^<+^^^>^%N' -extra_logging '0'
The caret makes the command shell take the following character literally.
Or, if it so happens winexe passes the command it is given to the command shell rather than executing it directly, you might need to triple-quote, i.e., seven carets before each special character.

I could be wrong, but I believe it is the backwards apostrophe or the grave symbol, i.e. `

Related

Powershell - Start-Process ArgumentList accepts only single variable with spaces

I'm trying to start my script from Explorer. I've found the solution and it works if script doesn't have any parameters.
$file = [System.IO.Directory]::GetCurrentDirectory() + "\Trees.ps1"
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File `"$($file)`""
However, if I add additionall parameters just like the first it ceases to work. Ie. this code throws "The string is missing the terminator: '." error.
$file = [System.IO.Directory]::GetCurrentDirectory() + "\Trees.ps1"
$Context = [System.IO.Directory]::GetCurrentDirectory()
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -Context '"$($Context)'" -File `"$($file)`""
I'm using this way of expecting variable:
[Parameter(Mandatory=$True)]
[string]$Context,
What can I do to pass more then one variable with spaces in ArgumentList?
I suspect that I should pass arguments for file content in other way than when just passing file name, but couldn't find solution.
In addition to the back ticks issue that Theo noted, -context should follow -file.
-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.
So your command line would be
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File `"$($file)`" -Context $($Context)"
Since you are using an external process call, you will need to use inside double quotes instead of single quotes. You can escape double quotes simply by adding another double quote ("").
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File ""$file"" -Context ""$Context"""

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 execute Windows command (Get-Content) from PowerShell in Windows Server

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.

Powershell Get-NetAdapterAdvancedProperty

I am trying to run Powershell command from batch file test.bat. I am actually calling this command from Python Popen not from test.bat.(I am using test.bat just for validation)
powershell.exe (Get-NetAdapterAdvancedProperty -Name "SLOT 1" -DisplayName "Jumbo Packet").DisplayValue
Same command works with out second argument -DisplayName "Jumbo Packet" from python and batch
Error I get when I use second argument is below:
Get-NetAdapterAdvancedProperty : A positional parameter cannot be
found that accepts argument '1'. At line:1 char:2
+ (Get-NetAdapterAdvancedProperty -Name SLOT 1 -DisplayName:Jumbo Packet).DisplayV ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-NetAdapterAdvancedProp erty], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Get-NetAdapterAdvanc edProperty
*
But if I run the same command from Powershell window I get my expected result.
(Get-NetAdapterAdvancedProperty -Name "SLOT 1" -DisplayName "Jumbo Packet").DisplayValue
I am new to Powershell.Thanks for your help
Python code:
iface="SLOT 1"
cmd= 'powershell.exe (Get-NetAdapterAdvancedProperty -Name "'+ iface +'" -DisplayName "Jumbo Packet").DisplayValue'
conn.modules.os.popen(cmd).read()
Brackets have special meaning in command. Escape them with a caret. The quotes may also need escaping with a caret.
But why the indirection. PS uses WMI. WMI is also available via COM. Python can do COM.
This is VBScript pulling out nics. You should be able to do this in any language that supports COM (nearly all).
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_NetworkAdaptor")
For Each objItem in colItems
msgbox objitem.name
Next
Put double quotes around the whole command string (to make the entire command a string for CMD). Use single quotes inside the double-quoted string to define the nested strings for PowerShell:
powershell.exe "Get-NetAdapterAdvancedProperty -Name 'SLOT 1' -DisplayName 'Jumbo Packet').DisplayValue"
Alternatively escape nested double quotes with backslashes:
powershell.exe "Get-NetAdapterAdvancedProperty -Name \"SLOT 1\" -DisplayName \"Jumbo Packet\").DisplayValue"
However, in general it's less troublesome to simply put PowerShell commands in a script and run that script with PowerShell:
powershell.exe -File "C:\path\to\your.ps1"

Executing a simple powershell command on the command line

I try to run a simple powershell command by setting a variable and printing it.
This is what I want to do:
powershell -command "& {$name=\"hi\"; echo $name}"
But it fails with:
The string is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
The invoke operator (&) works fine with commands such as:
powershell -command "& {&echo hi}"
I read about the invoking operator and how to execute commands with -command option and executing scripts with -File option etc. They are working as expected. But my attempts to do the same for setting a variable and printing it as above doesn't work. I suspect -command works with only commands. Any idea how to achieve what I do above?
from a DOS shell this works:
powershell -command "& {$name='hi'; echo $name}"
but also your code works.
From a Powershell console use this:
powershell -command {$name='hi'; echo $name}

Resources