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}
Related
I'm debugging why my script isn't running right in the TaskScheduler by running it at the command prompt in powershell ISE on the server like it's set up in TaskScheduler:
PS Microsoft.PowerShell.Core\FileSystem::\\w5server\ksupport\C_Adjust> c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -noninteractive -ExecutionPolicy bypass -Command "& .\\w5server\ksupport\C_Adjust\RunScan_MoveFiles_Admin.ps1"
I get this error:
c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe : & : The term '.\\w5server\ksupport\C_Adjust\RunScan_MoveFil
At line:1 char:1
+ c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -noninterac ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (& : The term '....Scan_MoveFil:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
es_Admin.ps1' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:3
+ &
.\\w5server\ksupport\C_Adjust\RunScan_MoveFiles_Admin.ps1
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\\w5server\k...Files_Admin.p
s1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I'm not sure why it's splitting the full command line info like that in the error message either; hopefully it's not part of the problem.
I tried removing the '&' before the .\w5server...scriptname.ps1 but got the same error message. I've never given a full path with this type of path before, but that's where the script is. Last time I did this it was in c:\Scripts\B... on that server.
This server is Windows Server 2012 R2. Previously, my server I was working on was 2008 R2, I'm not sure if that matters or not. Otherwise my syntax is the same, other than the script name and full path.
I saw this link is not recognized as the name of a cmdlet, but I think it's spelled correctly.
I was playing around with what I was using to run it at the command line, and this is working:
PS Microsoft.PowerShell.Core\FileSystem::\\w5server\ksupport\C_Adjust> c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -noninteractive -ExecutionPolicy bypass -Command \\w5server\ksupport\C_Adjust\RunScan_MoveFiles_Admin.ps1
So I got rid of the double quotes, '.' and '&' for the script location.
How do I start a new powershell instance and tell that instance to execute a certain command?
What I've tried:
(Assuming vim.exe and file.txt is in cwd)
Start-Process powershell.exe .\vim.exe .\file.txt
vim.exe is the parameter to powershell.exe
file.txt is the parameter to vim.exe
Error says:
Start-Process : A positional parameter cannot be found that accepts argument
'.\file.txt'.At line:1 char:1
+ Start-Process powershell.exe .\vim.exe .\file.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
I've also tried powershell.exe -ArgumentList {.\vim.exe .\file.txt} and no dice.
The Argument list is an array... say start-process doesn't know what to do with .\file.txt
Here is how I would write it
Start-Process powershell.exe -ArgumentList #('.\vim.exe', '.\file.txt')
The following will also work, but I like the above where you explicitly say you want an array
Start-Process powershell.exe -ArgumentList '.\vim.exe', '.\file.txt'
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"
Right now I have a powershell script that is callign an FTP request bundled in a CMD file.
It works, but I want to integrate the FTP request in the powershell script because it'll give me 1 less file to keep track of.
So far I have tried doing this, but it produces an error (see below).
# run the command script to extract the file
#defines command to be run
$command = '
#echo off
setlocal
set uname=name
set passw=pass
set hostname=hstname
set filespec=spec
echo %uname%> test.ftp
echo %passw%>> test.ftp
echo cd DIRNAME>> test.ftp
echo binary>> test.ftp
echo get %filespec%>> test.ftp
echo bye>> test.ftp
ftp -s:test.ftp %hostname%
if errorlevel 1 pause
endlocal
'
# runs command
iex $command
Error:
Invoke-Expression : The splatting operator '#' cannot be used to
reference variables in an expression. '#echo' can be used only as an
argument to a command. To reference variables in an expression use
'$echo'. At
Dir\File.ps1:32
char:4
+ iex <<<< $command
+ CategoryInfo : ParserError: (echo:String) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : SplattingNotPermitted,Microsoft.PowerShell.Commands.InvokeExpressionCommand
I also tried changing the script to $echo but it produces the following error:
Invoke-Expression : Unexpected token 'off' in expression or statement.
At
Dir\File.ps1:32
char:4
+ iex <<<< $command
+ CategoryInfo : ParserError: (off:String) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Alex,
This may not be exactly what you want but here is how I could make it work.
Once you have the commands, pipe all of them to create a batch file. For example:
Set-Content -path $env:temp\mycommands.cmd -value $command
Then, execute that file
iex "cmd /c $env:temp\mycommands.cmd"
The reason what you are doing is not working is because each of these lines are still getting interpreted by PowerShell and some of them have meanings in PowerShell that is not matching what is in CMD shell.
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. `