ProcessStartInfo and Process in PowerShell - Authentication Error - powershell

I have code that uses ProcessStartInfo and Process to invoke another script, and to return the output of that script.
Unfortunately, I am getting errors, and I am unsure how to troubleshoot them.
#script1.ps1
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\script2.ps1", $abc
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "DOMAIN\Username"
$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
# $standardOut should contain the results of "C:\script\script2.ps1"
$standardOut
The errors I get are:
Exception calling "Start" with "0" argument(s): "Logon failure: unknown user name or bad password"
At C:\script\script1.ps1:46 char:15
+ $process.Start <<<< () | Out-Null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At C:\script\script1.ps1:47 char:49
+ $standardOut = $process.StandardOutput.ReadToEnd <<<< ()
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script1.ps1:48 char:21
+ $process.WaitForExit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How can I fix this problem?

It's pretty much spelled out to you, isn't it?:
"Logon failure: unknown user name or bad password"
(first error line).
Note that DOMAIN should be provided in separate property:
$startInfo.Username = "Username"
$startInfo.Domain = "DOMAIN"

Related

How to download multiple files via PowerShell script?

I have multiple files to download, as many as 7 at a time, it downloads the first file then peters out.
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:17 char:5
$IE.Navigate2("https://mdf.mydomain.com/SeaNet//DownloadFile ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], COMException
FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
$BinaryID = 7458,7457,7446,7317
# open IE
$IE = New-Object -COMObject "InternetExplorer.Application"
$IE.Visible = $True
$MyUser = ""
$MyCreds = Get-Credential -Credential $MyUser
$MyPass = $Creds.GetNetworkCredential().Password
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/CustomReport.aspx?reportId=692")
While($IE.Busy -eq $true) {Start-Sleep -Seconds 30}
$IE.document.getElementById('UserNameTB').value = "$MyUser"
$IE.document.getElementById('PasswordTB').value = "$MyPass"
$Link = $IE.Document.getElementByID('LoginIBtn')[0].Item().Click()
ForEach ($ID in $BinaryID) {
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/DownloadFile.aspx?binaryid=$ID")
Pause
}

You cannot call a method on a null-valued expression in PowerShell using another credentials

Well, i'm trying to execute a script with another credentials and i got the next error:
You cannot call a method on a null-valued expression.
At C:\Automation\SoftwareInstallation\runas_test\whoami_test.ps1:10 char:1
+ Write-Host $result.StandardOutput.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This is my code:
$username = 'idb\frida_automation_scc'
$pass = Get-Content -Path C:\Automation\SoftwareInstallation\runas_test\settings.txt -Raw
$password = ConvertTo-SecureString $pass -AsPlainText -Force
$MyCredential=New-Object -TypeName PSCredential -ArgumentList $username, $password
$result=Start-Process -NoNewWindow powershell.exe -ArgumentList "-file C:\Automation\SoftwareInstallation\runas_test\whoami_test2.ps1" -Credential $MyCredential -PassThru -RedirectStandardOutput test1.txt
Write-Host $result.StandardOutput.ReadToEnd()
And this is the another command:
$result= whoami
Write-Host $result
return $result
I donĀ“t know why this error happens if the command are well written and the script brought back the value in a .txt file.

You cannot call a method on a null-valued expression. + $submitButton.click()

I'm running a script that I've used for some time successfully, but I am now getting the following error message:
You cannot call a method on a null-valued expression. At
G:\Backup\2021\DownloadASX300 v1.ps1:14 char:1
$submitButton.click()
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
The script I'm running is as follows:
$OutputFilePath = "c:\_Temp\ASX300html.htm
$url = 'https://www.marketindex.com.au/asx300'
$IE = New-Object -ComObject InternetExplorer.Application
$IE.Navigate($url)
$IE.Visible = $true
while ($IE.Busy -eq $true){Start-Sleep -seconds 5;}
$submitButton=$IE.Document.IHTMLDocument3_getelementsbytagname("a") | Where-Object {$_.innerhtml -like '*SHOW ALL COMPANIES*'}
$submitButton -eq $null
$submitButton.click()
Start-Sleep -s 5
$IE.Document.body.innerHTML | Out-File -FilePath $OutputFilePath
$IE.Quit()
This script basically downloads share prices from a website after opening the full list on that site.
Any help you can offer will be greatly apprreciated.

Passing filepath parameters to function

Below mentioned code is giving error, and I'm not able to troubleshoot issue. Can anyone please help, we are just passing SourceFile and DestinationFile location to this function...
ProcessDocumentsData "D:\Files\Scan1.doc","D:\Files\Scan1.csv"
Clear-Host
function ProcessDocumentsData {
Param(
[string]$SourceFile,
[string]$DestinationFile
)
$DestinationFileName = $DestinationFile
$SourceFileName = $SourceFile
$tableNum = 13
$delimiter = ','
$objWord = New-Object -Com Word.Application
$objWord.Visible = $false # $false
$objDocument = $objWord.Documents.Open($SourceFileName)
$LETable = $objDocument.Tables.Item($tableNum)
$LETableCols = $LETable.Columns.Count
$LETableRows = $LETable.Rows.Count
$RawCSV = for($r=1; $r -le $LETableRows; $r++) {
$content= #()
for($c=1; $c -le $LETableCols; $c++) {
#Write-Host ("R:{0},C:{1}" -f $r,$c)
$content += ("`"{0}`"" -f $LETable.Cell($r,$c).Range.Text -replace "(`r|`n|`t)|$([char]7)?")
}
$Content -join $delimiter
}
$Csv = $RawCSV | ConvertFrom-Csv
$objDocument.Close()
$objWord.Quit()
# Stop Winword Process
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
$Csv
$Csv | Export-Csv $DestinationFileName -NoTypeInformation
}
I'm getting the following error:
ProcessDocumentsData "D:\Files\Scan1.doc","D:\Files\Scan1.csv"
Command failed
At line:7 char:1
+ $objDocument = $objWord.Documents.Open($filename)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
You cannot call a method on a null-valued expression.
At line:8 char:1
+ $LETable = $objDocument.Tables.Item($tableNum)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:21 char:1
+ $objDocument.Close()
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
In PowerShell, when calling a function multiple parameters are delimited by a whitespace.
Try to call the function like that:
ProcessDocumentsData "D:\Files\Scan1.doc" "D:\Files\Scan1.csv"

powershell get-content path null error

$commonElementsLocation = ((Get-Location).Path + "\FolderMatchingCommonWords.txt")
if ($commonElementsLocation) {
$result += Start-Job -InitializationScript {
$commonElements = Get-Content -Path $commonElementsLocation
} -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job
}
Not sure what I am doing wrong here - probably a stupid mistake, but I put a condition around the Start-Job statement, and powershell still gives the following error:
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:39
+ $commonElements = (Get-Content -Path $commonElementsLocation)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentC
ommand
Running startup script threw an error: Cannot bind argument to parameter 'Path' because it is null..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
In v3 add $using:
....(Get-Content -Path $using:commonElementsLocation...
You have already used a variable for a script block once with $testScriptBlock. You could just do that again for -InitializationScript?
$anotherSB = [scriptblock]::create("$commonElements = (Get-Content -Path $commonElementsLocation)")
$result += Start-Job -InitializationScript $anotherSB -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job