integrating FTP request in powershell script instead of calling .CMD file - shell

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.

Related

Error when running powrshell at prompt with TaskScheduler info - 'is not recognized as the name of a cmdlet, function, script file, or operable ..'

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.

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"

Execute a batch script as admin from inside powershell

I am trying to schedule a weekly task that takes a backup of some important data (Eventually, I want to run the PowerShell script from Windows task manager). The software provider already has a batch script for this (backup.bat). I have written a powershell script that invokes this batch script. But invoking backupdb from powershell fails throwing a "Permission denied" error message.
I tried the below, which did not work:
start-process $BackupCmd -verb runas -ArgumentList "$Flags `"$BackupFile`""
After looking at several posts on SO and other forums, I was able to find answers for running a powershell script from inside a batch script as admin and not the other way round.
how to run as admin powershell.ps1 file calling in batch file, Run a powershell script in batch file as administrator and How to run a PowerShell script from a batch file
EDIT 1:
1.I run the batch script and the PowerShell script as the same user.
2.I tried elevating the PowerShell using "-verb runas", but did not work. Running the PowerShell script from the same elevated window as the batch script does not work.
3.Pasting the PowerShell script below:
$CurrentDate = get-date -format yyyyMMdd
$BackupStartDate = (get-date).AddDays(-7).ToString("yyyyMMdd")
$BackupDir = "<directory path>"
$BackupFile = $BackupDir + "Backup-" + $BackupStartDate + "-to-" + $CurrentDate + ".txt"
$BackupCmd = "C:\Progra~1\bin\backup"
$Verbose = " -v "
$ArchiveStart = " -S " + $BackupStartDate
$Flags = $Verbose + $ArchiveStart
# Both commands below do not work
start-process $BackupCmd -verb runas -ArgumentList "$Flags `"$BackupFile`""
& $BackupCmd $Flags `"$BackupFile`"
4.Error:
backup.bat : Error writing to the debug log! <type 'exceptions.IOError'> [Errno 13]
Permission denied: 'C:\\Program Files\\tmp\\debug.log'
(2014/06/05 12:42:01.07) [8764] --> Exception encountered. <Unable to load config file!>
Error writing to the debug log! <type 'exceptions.IOError'> [Errno 13] Permission denied:
Thanks.
I have encountered problems using start-process with -verb runas on batch scripts.
Try using start-process on powershell instead, passing your batch file as the first argument:
$CurrentDate = get-date -format yyyyMMdd
$BackupStartDate = (get-date).AddDays(-7).ToString("yyyyMMdd")
$BackupDir = "C:\"
$BackupFile = $BackupDir + "Backup-" + $BackupStartDate + "-to-" + $CurrentDate + ".txt"
$BackupCmd = "C:\Progra~1\bin\backup.bat"
$Verbose = "-v"
$ArchiveStart = "-S $BackupStartDate"
$Flags = "$Verbose $ArchiveStart"
$Args = "$BackupCmd $Flags `"$BackupFile`""
start-process powershell -verb runas -ArgumentList $Args

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}

Escape special chars in powershell commands

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. `

Resources