Powershell - This command cannot be run - powershell

I have a C++ application that launches a ps1 script using the following command
ShellExecuteA(0, "open", "powershell.exe", -executionpolicy RemoteSigned -File script.ps1", NULL, SW_NORMAL)
The script contains the following
$version = [System.Environment]::OSVersion.Version.Major
if ($version -gt 9)
{
$app = 'C:\Windows\System32\uwfmgr.exe'
$appargs = 'servicing enable'
Start-Process $app $appargs
Start-Sleep -s 5
$appargs= 'filter restart'
Start-Process $app $appargs
}
The end result should be that the Windows 10 machine (protected by UWF) should request service mode on its next reboot and the computer should restart
What happens instead is that the following error is raised
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At script.ps1:6 char: 2
+ Start-Process $app $args
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Edit:
Added
$Error[0] | FL * -Force
and renamed $args to $appargs

Related

Powershell Error: Cannot validate argument on parameter 'FilePath'. The argument is null or empty

I am trying to test the uninstallation of a program that is installed on my device. I am not sure what I need to do to specify the file path to this exe located on my device. Eventually this will need to be deployed organization wide, that's why I am attempting to use $PSScriptRoot. How do I specify the filepath to the exe I need deleted? It's a simple script but I keep getting the below error:
Transcript started, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
2022-10-26-03-08-47 - Install
Start-Process : Cannot validate argument on parameter 'FilePath'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\grayvi02\Downloads\UpdatePython.ps1:13 char:27
+ $Process1 = Start-Process $Install_Path -ArgumentList $Install_Args - ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand
2022-10-26-03-08-47 - Error - Install error with exitcode
Transcript stopped, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
$OutputFile = "$env:WINDIR\TEMP\Python3.7.8Install.log"
Writelog $Install_File = "python-3.7.8-amd64.exe"
Writelog $Install_Path = "`"$PSScriptRoot\$Install_File`""
$Install_Args = " /quiet /uninstall"
##########ERROR LOGGING#####
Function Set-WriteToLog ($Write1)
{
Write-Host "$(Get-Date -format yyyy-MM-dd-hh-mm-ss)`t-`t$Write1"
}
#########START OF SCRIPT BODY#############
Start-Transcript -Path $OutputFile
set-WriteToLog "Install $Install_File"
$Process1 = Start-Process $Install_Path -ArgumentList $Install_Args -Wait -NoNewWindow -passthru
$ErrorVal = $Process1.exitcode
If (#(0,1641,3010) -contains $Process1.exitcode)
{
Set-WriteToLog "Success - Install $Install_File with exitcode $ErrorVal"
}
else
{
Set-WriteToLog "Error - Install error with exitcode $ErrorVal"
}
Stop-Transcript
Exit $LASTEXITCODE

tshark job on PowerShell does not output capture file

When I run the following command in my script I expect packet_dump.pcap to get generated after I stop the script but nothing gets generated.
Start-Job -Name $tsharkJobName -ScriptBlock { & $tsharkPath --interface $interfaceNo -w "packet_dump.pcap" } | Out-Null
When I run the line below:
Receive-Job $tsharkJobName -Force
This is the error message that I get (where $interfaceNo is 5 which is the ID for Wi-Fi):
Capturing on 'Wi-Fi'
+ CategoryInfo : NotSpecified: (Capturing on 'Wi-Fi':String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : localhost
I have this at the end of the script as well:
finally {
Stop-Job $tsharkJobName
Remove-Job $tsharkJobName -Force
}
$args = "--interface " + $interfaceNo + " -w packet_dump.pcap"
Start-Process $tsharkPath -ArgumentList $args -NoNewWindow
and
finally {
Stop-Process -Name "tshark"
}
Solves this.

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')

'Provider load failure' during installation process

I execute two Powershell scripts during a installation process from a desktop application under Windows 10 IoT Enterprise.
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\KeyboardFilter.ps1"
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\ShellLauncher.ps1"
But the execution of the Powershell scripts is not successful. I get the following errors:
Get-WMIObject : Provider load failure
At C:\Program Files\Application\KeyboardFilter.ps1:31 char:19
+ ... $predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Write-Error : A positional parameter cannot be found that accepts argument 'is'.
At C:\Program Files\Application\KeyboardFilter.ps1:41 char:9
+ Write-Error $Id is not a valid predefined key
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Error], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteErrorCommand
enable-windowsoptionalfeature : An attempt was made to load a program with an incorrect format.
At C:\Program Files\Application\ShellLauncher.ps1:4 char:1
+ enable-windowsoptionalfeature -online -featureName Client-EmbeddedShe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Enable-WindowsOptionalFeature], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.EnableWindowsOptionalFeatureCommand
The installation process starts with administration permissions.
The first script adds key combinations to the Keyboard Filter (Windows 10 IoT feature).
The second scripts enable and configure the Shell Launcher (also Windows 10 IoT feature).
KeyboardFilter.ps1:
param (
[String] $ComputerName
)
$CommonParams = #{"namespace"="root\standardcimv2\embedded"}
$CommonParams += $PSBoundParameters
function Enable-Predefined-Key($Id) {
$predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
where {
$_.Id -eq "$Id"
};
if ($predefined) {
$predefined.Enabled = 1;
$predefined.Put() | Out-Null;
Write-Host Enabled $Id
} else {
Write-Error $Id is not a valid predefined key
}
}
If I execute the Powershell scripts in a batchfile or on Powershell console, everything works fine. I also tried to execute the Powershell scripts during the installation process with Powershell x86 and x64, same errors in both cases.
Any hints, tips or solution for this problem?

Powershell codes throwing errors on Jenkins

I've added the following line of Powershell codes in Jenkins and it's throwing some errors, although it's working fine when I'm trying to execute it via Powershell ISE on the same desktop/machine.
I have configured the Jenkins service logon and the user ID got correct permission.
Kindly advise.
servers = Get-Content "C:\tmp\script\updated\SessionHost.txt"
foreach ($server in $servers)
{
$FolderWindows = Start-Process -FilePath "\\$server\C$\Temp" -WindowStyle Maximized
}
Error Message on Jenkins:
Start-Process : This command cannot be run due to the error: Server execution
failed.At C:\tmp\script\updated\MainTaiwanUAT.ps1:385 char:22
+ $FolderWindows = Start-Process -FilePath "\\$server\C$\Temp"
-WindowS ...
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand