PowerShell 3.0 behavior when getting external process exit code - powershell

I have been using this code from another post from this site:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
**$p.Start() | Out-Null**
#Do Other Stuff Here....
**$p.WaitForExit()**
$p.ExitCode
It has worked fine under PowerShell 2.0. The server was upgraded to PowerShell 3.0, and now the two bold like fail with:
Exception calling "Start" with "0" argument(s): "The system cannot find the
file specified"
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:126 char:1
+ $p.Start() | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is
associated with this object."
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:128 char:1
+ $p.WaitForExit()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Why did it broke and how do I correct it so it works for both version 2.0 and 3.0?

Hmm, I can't repro the error on my V3 system. But why are you going to all this trouble when you can just use the Start-Process command to do this e.g.:
$p = Start-Process Notepad -Wait -PassThru
$p.ExitCode

You might want to try providing a fully-qualified path to notepad.exe, like "C:\Windows\notepad.exe".

Related

Using Powershell to download and run exe file

I am trying to download Malwarebytes Anti-Rootkit Beta but my PowerShell script throws the error below. How do I fix this?
My Script:
$url = "https://data-cdn.mbamupdates.com/web/mbar-1.10.3.1001.exe"
$outpath = "$PSScriptRoot/mbar-1.10.3.1001.exe"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $outpath)
$args = #("Comma","Separated","Arguments")
Start-Process -Filepath "$PSScriptRoot/mbar-1.10.3.1001.exe" -ArgumentList $args
The Error:
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At line:8 char:1
+ Start-Process -Filepath "$PSScriptRoot/mbar-1.10.3.1001.exe" -Argumen ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

'Run As Different Users' behaves differently with PowerShell

I'm using "Run As Different User" when running a PowerShell script, and it is behaving differently than when I run the script in a normal PowerShell Terminal. For example, if I try to run the following code in the "Run As" terminal, it runs into an error. But if I run it with a normal terminal it works just fine.
function Replace-Word(
[string]$Document,
[string]$FindText,
[string]$ReplaceText
)
{
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
$Word = New-Object -comobject Word.Application
$Word.Visible = $False
$OpenDoc = $Word.Documents.Open($Document)
$Selection = $Word.Selection
$Selection.Find.Execute(
$FindText,
$MatchCase,
$MatchWholeWord,
$MatchWildcards,
$MatchSoundsLike,
$MatchAllWordForms,
$Forward,
$Wrap,
$Format,
$ReplaceText,
$ReplaceAll
) | Out-Null
$OpenDoc.Close()
$Word.quit()
}
Copy-Item "C:\Welcome.DOC" "C:\test.DOC"
Replace-Word -Document "C:\test.DOC" -FindText '<UserName>' -ReplaceText "JohnDoe"
Replace-Word -Document "C:\test.DOC" -FindText '<EmailAddress>' -ReplaceText "JohnDoe#example.com"
The errors I get when running as a different user are:
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2668 char:9
+ $Selection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2670 char:9
+ $OpenDoc.Close()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2668 char:9
+ $Selection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2670 char:9
+ $OpenDoc.Close()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Both terminals are running the same version of PowerShell:
Major Minor Build Revision
----- ----- ----- --------
5 1 14409 1012
I would run this code in a normal terminal if I could, but this is only part of a larger script I am running. The rest of the script needs administrative privileges to run, which is why I use the "Run As" feature. Any ideas about why the code would execute differently between the two user accounts? Any suggestions would be very appreciated!
Everyone else's suggestion still apply (once permissions and ACL to the file has been sorted) and it is still giving you this error... THEN:
This is a classic case of locked file in Word. You need to release the COM Object from your last PowerShell session because it is probably still accessing the file and causing issues.
Once you release the COM Object or close all word processes, try running as again and it should work.

Signing password and get value back

We migrated one Windows Server 2008 to Server 2016.
Now I'm getting an error at this script:
cls
$key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23)
$pass = Read-Host -AsSecureString
$securepass = $pass | ConvertFrom-SecureString -Key $key
$bytes = [byte[]][char[]]$securepass
$csp = New-Object System.Security.Cryptography.CspParameters
$csp.KeyContainerName = "SuperSecretProcessOnMachine"
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
$rsa.PersistKeyInCsp = $true
$encrypted = $rsa.Encrypt($bytes,$true)
$encrypted | Export-Clixml 'C:\Temp\encrypted_ysastaginpro_PRE.txt' -Force
Error Code:
New-Object : Exception calling ".ctor" with "2" argument(s): "Object already
exists."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:13 char:10
+ ... $rsa = New-Object System.Security.Cryptography.RSACryptoServiceP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "Encrypt" with "2" argument(s): "Bad Length."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:18 char:3
+ $encrypted = $rsa.Encrypt($bytes,$true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CryptographicException
I found the the solution.
Run the PS Script as adminstrator.

Powershell to press a button in Explorer

I have a web page with the following code relevant to the button:
<td width=300 align=left>Click here to run the batch tool:</td>
<td align='left' width=100><input id="Submit1" type="submit" value="Run" onClick='showSts();'/></td>
And my attempts to programmatically press it from Powershell using this code:
$username='username' $password='password'
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true
$ie.Navigate("name of Web site")
while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}
# $usernamefield = $ie.Document.getElementByID('memberemail')
# $usernamefield.value = $username
# $passwordfield = $ie.Document.getElementByID('memberpassword')
# $passwordfield.value = $password
$submitebutton=$ie.Documentelement.getElementByclassname('submit1') | Select-Object -First
$submitebutton.click()
Gives this error:
You cannot call a method on a null-valued expression. At
C:\Users\zkf4bi4\Documents\houdini_click.ps1:15 char:1
+ $submitebutton=$ie.Documentelement.getElementByclassname('submit1') | Select-Ob ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\Users\zkf4bi4\Documents\houdini_click.ps1:16 char:1
+ $submitebutton.click()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any ideas on how to proceed? I'm an experienced developer but am new to Powershell
Well, I can't help but notice that you're calling GetElementsByClassName but 'Submit1' is the elements id. I suspect the error message is trying to tell you that $submitebutton is null. You might find this question an almost exact duplicate.

Run remote PowerShell Office uninstallation script

KB2956128 is causing headache for users in my network. I do not run WSUS in this environment so I was going to employ PS script to take care of uninstallation.
By all means the script below should work
$comp = 'PC03'
$scrblock =
{
$TitlePattern = 'KB2956128'
$Session = New-Object -ComObject Microsoft.Update.Session
$Collection = New-Object -ComObject Microsoft.Update.UpdateColl
$Installer = $Session.CreateUpdateInstaller()
$Searcher = $Session.CreateUpdateSearcher()
$Searcher.QueryHistory(0, $Searcher.GetTotalHistoryCount()) |
Where-Object { $_.Title -match $TitlePattern } |
ForEach-Object {
Write-Verbose "Found update history entry $($_.Title)"
$SearchResult = $Searcher.Search("UpdateID='$($_.UpdateIdentity.UpdateID)' and RevisionNumber=$($_.UpdateIdentity.RevisionNumber)")
Write-Verbose "Found $($SearchResult.Updates.Count) update entries"
if ($SearchResult.Updates.Count -gt 0) {
$Installer.Updates = $SearchResult.Updates
$Installer.Uninstall()
$Installer | Select-Object -Property ResultCode, RebootRequired, Exception
# result codes: http://technet.microsoft.com/en-us/library/cc720442(WS.10).aspx
}
}
}
Invoke-Command -ComputerName $comp -ScriptBlock $scrblock -Credential 'myDomain\administrator'
Instead I get this error
Exception calling "CreateUpdateInstaller" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
Exception calling "QueryHistory" with "2" argument(s): "Exception from HRESULT: 0x80240007"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
I don't quite understand why the access is denied. Any ideas?
Short answer is that the ComObject does not allow the CreateUpdateInstaller to be called remotely. You can only do this locally, not over sessions or any other remoting. You can however use psexec to remotely execute your script as system.