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.
Related
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
I have this simple script that will execute text.bat in cmd tool and print result in hello.txt. This is done to target remote server.
Invoke-Command -ComputerName 1.1.1.1 -Credential KOPI\Administrator -ScriptBlock {
Invoke-Expression -Command:"cmd.exe /c 'C:\Users\Administrator.KOPI\Documents\test.bat'"
} | out-file $psscriptroot\hello.txt
However, the bat file encounter error as shown below.
ERROR: The system was unable to find the specified registry key or value.
+ CategoryInfo : NotSpecified: (ERROR: The syst...y key or value.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : 1.1.1.1
So my question is, if it is possible to print just the error message ERROR: The system was unable to find the specified registry key or value. into hello.txt?
Yes, what you are looking for is catching an exception message ($_.Exception.Message).
For example:
try {
Invoke-Command -ComputerName 1.1.1.1 -Credential KOPI\Administrator -ScriptBlock {
Invoke-Expression -Command:"cmd.exe /c 'C:\Users\Administrator.KOPI\Documents\test.bat'"
} | out-file $psscriptroot\hello.txt
}
catch {
$_.Exception.Message | Out-File $psscriptroot\hello.txt
}
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
I have a script that works to run an executable and wait until done in PS but I need to modify it to use a path defined in a variable earlier in the script.
Working:
$job = Start-Job `
-InitializationScript { Set-Location C:\MyDirectory\ } `
-ScriptBlock { C:\MyDirectory\MyCmdLineExecutable.exe }
Wait-Job $job
Receive-Job $job
Not working:
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job `
-InitializationScript { Set-Location $Path } `
-ScriptBlock { $ExePath }
Wait-Job $job
Receive-Job $job
Here's the error:
Set-Location : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
At line:1 char:2
+ Set-Location $Path
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], PSArgumentNullException
+ FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
49 Job49 BackgroundJob Failed False localhost $ExePath
Running startup script threw an error: Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
Combining info from Start-Job docs with About_Scopes article, I am certain of that you need to use -InputObject parameter:
Specifies input to the command. Enter a variable that contains the
objects, or type a command or expression that generates the
objects. In the value of the ScriptBlock parameter, use the
$Input automatic variable to represent the input objects.
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job -InputObject #( $Path, $ExePath) `
-InitializationScript { <# $Input variable isn't defined here #> } `
-ScriptBlock {
$aux = $Input.GetEnumerator()
Set-Location $aux[0]
& $aux[1] }
Wait-Job $job
Receive-Job $job
BTW, to run commands that are stored in variables and represented by strings, use & Call operator. See the difference:
$ExePath ### output only
& $ExePath ### invocation
I think you want Start-Process with the -Wait parameter. You can also specify the -WorkingDirectory parameter to specify the working directory for the new process. Example:
Start-Process notepad -WorkingDirectory "C:\Program Files" -Wait
Write-Host "Finished"
When you run this script, Notepad will open but the script won't continue until it closes. When you close Notepad, the Write-Host line runs.
this is probably an easy answer for you experts but not sure the best command to use. I want to execute the following command from within powershell :
stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd "status bobRRC_ADT_OUT_FMT"
and return the result.
The code i have so far is :
$sCmd = #'
"stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb
nsccahs_dev_cb -cmd '\"status bobRRC_ADT_OUT_FMT\"'"
'#
$Result = Invoke-Command $sCmd | Out-String
The error i am getting is :
Invoke-Command : Parameter set cannot be resolved using the specified named par
ameters.
At E:\Andrew\MonitoreGate.ps1:20 char:25
+ $Result = Invoke-Command <<<< $sCmd | Out-String
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], Parameter
BindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Comma
nds.InvokeCommandCommand
If i use Invoke-Expression, instead i get the following :
Invoke-Expression : Unexpected token 'status' in expression or statement.
At E:\Andrew\MonitoreGate.ps1:20 char:28
+ $Result = Invoke-Expression <<<< $sCmd | Out-String
+ CategoryInfo : ParserError: (status:String) [Invoke-Expression]
, ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.In
vokeExpressionCommand
Should i be using Invoke-Command or Invoke-Expression or some other way? Is the $sCmd structure correct in regards to quotes?
The program is to run on same machine (not remotely).
Any help greatly appreciated,
Andrew
neither, instead use:
Start-Process -FilePath 'path_to_stccmd.exe' -ArgumentList "-rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd 'status bobRRC_ADT_OUT_FMT'" -nonewwindow
if you dont see the output using the above...try this:
$exepath = 'path_to_stccmd.exe'
&$exepath arguments