Can we use SQLTransaction in Windows Powershell ISE? - powershell

I tried using SQLDataAdapter Object in Powershell ISE and its methods like below
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
and used its method like below
$SqlAdapter.Fill($DataSet)
Its working for me. But when I am trying like below
$trans= New-Object System.Data.SqlClient.SqlTransaction
and using its method like this
$trans = $connection.BeginTransaction("SampleTransaction")
where
$connection= New-Object System.Data.SqlClient.SqlConnection
Its giving me error
Exception calling "BeginTransaction" with "1" argument(s): "Invalid
operation. The connection is closed." At line:1 char:41
+ $trans = $SqlConnection.BeginTransaction <<<< ("SampleTransaction")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Anybody having any idea on this??

It seems that you haven't opened the connection.
Are you simply missing:
$connection.Open();
That would be my first guess.

I agree with Gisli on opening a connection. Where's the rest of your code? Another approach is to use a command object and assign the command transaction property to the command:
$cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
$cmd.Transaction = $transaction
This is what we do in the adolib module which is part of SQL Server Powershell Extensions. Check out Modules\adolib\adolib.psm1.

Related

PowerShell: Auto Login to a website using MS Edge instead of IE throws errors

Courtesy of this post, the following code auto-logs into a URL using MS IE and works great. The first two lines are the most important here. See below for what happens when I change them. I want to make it clear That I am not a professional web developer. I am only a system administrator forced to hack my way along when it comes to coding.
Working code when PowerShell calls IE:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$username="myname"
$RSAPIN="mypin"
$password="mypassword"
$ie.Navigate("https://www.tibia.com/mmorpg/free-multiplayer-online-role-playing-game.php")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('username')
$usernamefield.value = "$username"
$RSAPINfield = $ie.document.getElementByID('password_input')
$RSAPINfield.value = "$RSAPIN"
$passwordfield = $ie.document.getElementByID('secondary_password_input')
$passwordfield.value = "$password"
Non-working code is shown below; If I change the code to call MS Edge instead, I get a raft of errors and I think it's because PowerShell New-Object doesn't support MS Edge?
$msedge = New-Object -ComObject 'internetExplorer.Application'
$msedge.Visible= $true # Make it visible
$username="myname"
$RSAPIN="mypin"
$password="mypassword"
$msedge.Navigate("https://www.tibia.com/mmorpg/free-multiplayer-online-role-playing-game.php")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $msedge.document.getElementByID('username')
$usernamefield.value = "$username"
$RSAPINfield = $msedge.document.getElementByID('password_input')
$RSAPINfield.value = "$RSAPIN"
$passwordfield = $msedge.document.getElementByID('secondary_password_input')
$passwordfield.value = "$password"
Errors seen when calling MS Edge instead of IE:
New-Object : Retrieving the COM class factory for component with CLSID
{00000000-0000-0000-0000-000000000000} failed due to the following
error: 80040154 Class not registered (Exception from HRESULT:
0x80040154 (REGDB_E_CLASSNOTREG)). At
C:\Scripts\msedge.ps1:3
char:11
$msedge = New-Object -ComObject 'msedge.Application'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Visible' cannot be found on this object. Verify that the
property exists and can be set. At
C:\Scripts\msedge.ps1:4
char:1
$msedge.Visible= $true # Make it visible
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\Scripts\msedge.ps1:8
char:1
$msedge.Navigate("myurl")
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\Scripts\msedge.ps1:12
char:1
$usernamefield = $msedge.document.getElementByID('username')
I am at a loss here. According to this post, PowerShell New-Object only supports IE's COM Automation.
You can't automate the Edge Chromium browser like what you do with IE using PowerShell script. The COM automation interface are for IE, so it doesn't work with Edge. Besides, Edge doesn't have such interface.
It's recommended to use Selenium WebDriver to automate Edge. Selenium web driver supports many developing languages, you can choose the desired language.
You can also refer to the official doc of Selenium to learn how to get start with Selenium and refer to the code sample of different languages.

Why document object is null-value in my powershell script?

I want to use powershell to automate a web download request. But I got some errors that I can't fix.
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.visible = $true
$ie.Navigate("http://10.8.140.232/KPIReport/Admin/Login.aspx")
$usr_name = $ie.document.getElementById('TextBoxAccount')
$pwd = $ie.document.getElementById('TextBoxPassword')
$login_button = $ie.document.getElementById('ButtonLogin')
the first 3 lines can run successfully.
but from line 4, error occurs.
You cannot call a method on a null-valued expression.
At line:4 char:1
+ $usr_name = $ie.document.getElementById("TextBoxAccount")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And $ie.document return null in command line.
and by the way. all the element id are existed in source html code.
I don't what happens here.
thanks for your help.
As the comment above, the error is caused by the DOM hasn't been fully loaded. I use While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;} after $ie.Navigate. You could try to add it in your code.

PowerShell to Script Out SQL Server Agent Jobs

I'm trying to create a PowerShell script (based on two examples found on blogs) that will take a list of servers in a file passed in as an argument and then script out the SQL Server Agent jobs into T-SQL.
I'm getting this error on the last line:
$scrp.Script($job)
OBJECT DEFINITIONS
$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($ServerName)
$job in $s.JobServer.Jobs
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $ServerName
ERROR:
Exception calling "Script" with "1" argument(s): "Script failed for Job 'AX_Project_Contract_Monitor'. " At C:\Users\045810dl\Documents\PowerShell\Script Out SQL Agent Jobs\Script Out SQL Agent Jobs.ps1:101 char:6
+ $scrp.Script($job)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FailedOperationException
The object $scrp seems to be correctly connected to the SMO.Scripter method based on debugging output.
Thanks in advance!

Powershell compare size of local file to file on sharepoint

I am using the current code to download a file from a sharepoint...
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$webClient.DownloadFile($sharepointPathFile, $localPathFile) | Out-Null
But what if I wanted to check if the file is already at the local location and the size matches or is different? How would I do this using powershell?
Update
This was the closest I could get...
$url = $sharepointPathFile
$clnt = [System.Net.WebRequest]::Create($url)
$resp = $clnt.GetResponse()
$fileSize = $resp.ContentLength
Write-Host $fileSize
But I am getting the following error:
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (401) Unauthorized."
At C:\Scripts\Tests\testCheckUpdatedSearchFiles.ps1:345 char:2
+ $resp = $clnt.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I have full read and download rights, so is there something else not going right here?
I'm not sure if the "GetResponse" method will return exactly what you're looking for. And depending on the ContentLength, you may want to explicitly define your types. I would try something like this:
$webClient = New-Object System.Net.WebClient
$webClient.OpenRead("path/to/file")
[Int64]$fileSize = $webClient.ResponseHeaders["Content-Length"]
Write-Host $fileSize

PowerShell - Process multiple word docs (office 2010)

I am trying to write a PowerShell script to perform steps on multiple Word docs. I have Word 2010 installed on my machine, but I can't seem to get the script to open the docs. Here is the script
$path = "C:\MyPath"
Add-Type -AssemblyName Microsoft.Office.Interop.Word
$wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
$objWord = New-Object -ComObject "word.application"
$objWord.visible = $false
foreach($wd in $wordFiles)
{
$doc = $objWord.documents.open($wd.fullname)
#InsertProcessingFunctionsHere
$doc.Save()
$objWord.Documents.Close()
}
$objWord.Quit()
I try and run this, and the error I get back from PowerShell is:
Exception calling "Open" with "1" argument(s): "Command failed"
At C:\Scripts\Process-WordDocs.ps1:10 char:31
+ $doc = $objWord.documents.open <<<< ($wd.fullname)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
You cannot call a method on a null-valued expression.
At C:\Scripts\Process-WordDocs.ps1:13 char:10
+ $doc.Save <<<< ()
+ CategoryInfo : InvalidOperation: (Save:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "Close" with "0" argument(s): "This method or property is not available because a document window is not active."
At C:\Scripts\Process-WordDocs.ps1:14 char:25
+ $objWord.Documents.Close <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
MSDN states that documents.open only requires 1 argument, and the rest are optional. However, a C# example I have seen on the net, showed passing a "ReadOnly: False" parameter to documents.open. Stepping through the script in the ISE Debugger, I can see $wd.fullname is there and points to a valid file, so I am completely unclear why it is not opening. At first, I thought this was because I was using a 64-bit version of the OS (32-bit version of Office), but attempting the script from a 32-bit PowerShell Session resulted in the same error. Anyone have any insight here as to why this may be happening, and how I can fix it? I would prefer all the processing to happen invisible to the user. Any help would be greatly appreciated. Thank you in advance for your time.
I think you want to close the document using $doc.close() instead of $objWord.Documents.Close()