Basically, I run this application a lot with different launch parameters.
I usually open up PowerShell in the folder of application and write something like this.
.\Name.exe -specific -launch -parameters
The application will start running, so I'm trying to streamline this a little bit and grab the syntax for launching the application from its cfg file.
What I've been trying
function startfunction {
cls
echo "---------------------------------------------------------"
echo ""
echo " Enter Config Name"
echo ""
echo "---------------------------------------------------------"
$name = Read-Host -Prompt 'Enter Config';
Get-Content -Path .\application\configs\$name.cfg |
Write-Output -OutVariable launch;
Start-Process $launch;
}
Contents of $name.cfg:
.\Name.exe -specific -launch -parameters
Results/Error:
Enter Config: Name
.\Name.exe -specific -launch -parameters
Start-Process : Cannot convert 'System.Collections.ArrayList' to the type
'System.String' required by parameter 'FilePath'. Specified method is not
supported.
At C:\PSM0001.ps1:38 char:17
+ Start-Process $launch;
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.StartProcessCommand
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
If i run this code it will run the file
{Write-host "Please Enter the email address of the user you want to check the permissions"
$user = Read-Host
Powershell.exe C:\Temp\Report\Reports.ps1}
But if i run it like this which is what i need to do
{ Write-host "Please Enter the email address of the user you want to check the permissions"
$user = Read-Host
Powershell.exe C:\Temp\Report\Reports.ps1 -processOneDrive $true -OneDriveEmail $user}
I get this error
Powershell.exe : C:\Temp\ReportSharedFiles\ReportSharedFiles.ps1 : Missing an argument for parameter 'OneDriveEmail'. Specify a
At C:\Temp\ReportSharedFiles\Full Exchange Script Menu.ps1:88 char:2
+ Powershell.exe "c:\Temp\ReportSharedFiles\ReportSharedFiles.ps1" -pr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (C:\Temp\ReportS...il'. Specify a :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
parameter of type 'System.String' and try again.
At line:1 char:71
+ ... haredFiles\ReportSharedFiles.ps1 -processOneDrive True -OneDriveEmail
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ReportSharedFiles.ps1], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,ReportSharedFiles.ps1
What am i doing wrong and how can i get this to work? any help will be appreciated
I believe its asking you for a sting parameter in the error
parameter of type 'System.String' and try again.
Hope this works out>
{ [string]$user = Read-Host "Please Enter the email address of the user you want to check the permissions"
Powershell.exe C:\Temp\Report\Reports.ps1 -processOneDrive $true -OneDriveEmail $user}
Type String >
I have figured it out. It seems when running the powershell script within another script and to have the arguments in. when it comes to the -processOneDrive $true It tried to convert that to boolem which caused errors. i changed this to 1 which im sure means true so code looks like this
Powershell.exe "c:\Temp\Report\Reports.ps1" -processOneDrive 1 -OneDriveEmail $user
Now it runs smoothly. Thanks for everyone that tried to help me with this :)
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')
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
What am I doing wrong here? I am trying to open a second PS1 file if True but an error is thrown (shown below).
#ABOUT
#GLOBALS
$userID = "admin"
$pswrd = "test"
$name = Read-Host 'What is your username?'
$pass = Read-Host 'And your password?' #-AsSecureString | ConvertFrom-SecureString
#$script = '.\sdsSysMain.ps1'
if($name -eq $userID -and $pass -eq $pswrd) #or blank?
{
#write-host "Well done! You're in. "
#Start-Sleep -s 5
Powershell -noexit ".\sdsSysMain.ps1"
}
elseif($name -ne $userID -or $pass -ne $pswrd)
{
write-host "Login Failed... :("
}
This is the error I'm getting:
powershell.exe : The term '.\sdsSysMain.ps1' is not recognized as the name of a cmdlet, function
At C:\Users\1234\Documents\Projects\sdsSys\sdsSysLogin.ps1:19 char:15
+ Powershell <<<< -noexit ".\sdsSysMain.ps1"
+ CategoryInfo : NotSpecified: (The term '.\sds...mdlet, function:String) [],
RemoteException
+ FullyQualifiedErrorId : NativeCommandError
, 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:17
+ .\sdsSysMain.ps1 <<<<
+ CategoryInfo : ObjectNotFound: (.\sdsSysMain.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The error is rather self-explanatory. The script doesn't find sdsSysMain.ps1 in the current working directory. You can output the current working directory in your script like this:
(Get-Location).Path
If you want to run sdsSysMain.ps1 from the same directory as the script calling it, change this:
Powershell -noexit ".\sdsSysMain.ps1"
into this:
$scriptPath = Split-Path -Parent $script:MyInvocation.MyCommand.Path
Powershell -NoExit -File "$scriptPath\sdsSysMain.ps1"