Get-Content -Raw parameter error - sql

I have a PowerShell script that would recursively loop a dir and subdir and run all SQL files inside of it and log the execution in .log files 1 for success and 1 for exceptions. The PowerShell script does what its supposed to do but in the cmd window, I see this error:
Get-Content : A parameter cannot be found that matches parameter name 'Raw'
from this line
$query = Get-Content -Path $_.FullName -Raw
This statement runs within a loop, so FullName changes per iteration. This is the version I use.
Name : Windows PowerShell ISE Host
Version : 5.0.10586.117
Sample script goes below:
Get-ChildItem $ScriptFolder -Recurse -Exclude "*Archive*" -Filter *.sql |
sort Directory |
ForEach-Object {
$query = Get-Content -Path $_.FullName -Raw
$result = SQLCMD -S $FullDBServer -E -I -Q $query -d $Database
Any thoughts?

The -Raw parameter of Get-Content was introduced in PS3.
To get file contents in one string there are several methods.
The fastest method that works in any PS version:
$text = [IO.File]::ReadAllText('c:\path\file.ext')
The 2 times slower method for PS3+:
$text = Get-Content 'c:\path\file.ext' -Raw
The 100 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' | Out-String
The 30 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' -ReadCount 1000 | Out-String

I've experienced this error in ps v 5 when the -path parameter wasn't actually a path.
Try adding Write-Host $_.fullname above the line throwing the error to make sure $_.fullname is actually what you think it is.

You're using PowerShell v2 or earlier. The parameter -Raw was introduced with PowerShell v3. Either upgrade PowerShell or pipe the output of Get-Content through Out-String:
$query = Get-Content -Path $_.FullName | Out-String
You should also be able to run the files directly with sqlcmd (i.e. without reading their content and passing that to the command):
$result = SQLCMD -S $FullDBServer -E -I -i $_.FullName -d $Database

Related

Using sql query on ssis server sql job using powershell

I want to invoke a sql query/SP on sql job in a ssis server using a powershell script but I don't know how to do that. I've used powershell to run sql queries on sql database but not jobs on ssis. Here is what I have till now-
$ssisServer = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($name_of_server)
$IntegrationServices = New-Object "Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices" $ssisServer
$catalog = $IntegrationServices.Catalogs[$catalog]
$folder = $catalog.Folders[$folder]
$project = $folder.Projects[$project]
$sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name]
query= " some sql query "
if ($sqlJob) {
$sqlJob.CurrentRunStatus()
# here I need to run a query on the job
}
The query could be to get details of the job or perform some action on it. Also is this enough as we are just giving the server name here $sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name] to get the job which in a particular folder->project->job? I couldn't try this yet and haven't found much resources on it. Please give me some help to work with.
I didn't work with the SSIS server. But the principle of running SQL queries from SQL is pretty simple.
You should have proper module or you can use snapin of SQL.
I will continue from the second one.
# If you have an SQL server on your server, so this is the possible path where they can be.
$PossiblePaths = 'C:\Program Files\Microsoft SQL Server','C:\Program Files (x86)\Microsoft SQL Server'
# Lets check where we have PSProvider.dll and PSSnapins.dll
$PossiblePaths | ForEach-Object {
Test-Path -Path $_
{
$SQLPSProvider = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSProvider.dll" -Path $_ -Recurse).FullName
$SQLPSSnapIn = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSSnapins.dll" -Path $_ -Recurse).FullName
}
}
# Lets find Install Utility to add them with it.
$InstallUtil = (Get-ChildItem -Filter "InstallUtil.exe" -Path "$env:windir\Microsoft.NET\Framework64\v2.0*" -Recurse).FullName
if (($null -eq $SQLPSProvider) -or ($null -eq $SQLPSSnapIn))
{
Write-Host "Sorry, SQL PowerShell SnapIn or PowerShell Provider not found." -ForegroundColor Red
}
else
{
# Adding them to our system.
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSProvider"
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSSnapIn"
}
# Now they should be in the system and we can add them to our PowerShell session.
Add-PSSnapin -Name SqlServerCmdletSnapin100
Add-PSSnapin -Name SqlServerProviderSnapin100
# Now we should have Invoke-Sqlcmd like if we had SQLServer module.
$SQLServer = "SQL2012"
$SQLInstance = "JustForExample"
$ServerInstance = $SQLServer + '\' + $SQLInstance
# So you typing query for example like attaching DB.
$Query = "CREATE DATABASE ExamleDB ON (FILENAME = `'C:\DBs\ExamleDB.mdf`'), (FILENAME = `'C:\DBs\ExamleDB_log.ldf`') FOR ATTACH"
# And then executing it with Invoke-Sqlcmd like that.
Invoke-Sqlcmd -ServerInstance $ServerInstance -Username 'sa' -Password 'Abcde12345' -Query "Query"

Automatic extract zipped files with passwords in the file name

I analyse data from being sent multiple ZIP files.
They are always in this format:
service_SC30COM_####_20191130_1834.zip
#### is a random number generated by the computer.
Password is SC30COM_####, which is always part of the file name.
Any suggestions on an automation to unzip in bulk?
There is no way to do it on the command prompt without any application.
You can check this
If your remove the password, the code you need, as explain in that microsoft article should be:
$shell=new-object -com shell.application
$CurrentLocation=get-location
$CurrentPath=$CurrentLocation.path
$Location=$shell.namespace($CurrentPath)
$ZipFiles = get-childitem *.zip
$ZipFiles.count | out-default
foreach ($ZipFile in $ZipFiles)
{
$ZipFile.fullname | out-default
$ZipFolder = $shell.namespace($ZipFile.fullname)
$Location.Copyhere($ZipFolder.items())
}
If you install any application that can run on command prompt, you can extract with password. As example, for a individual file, the maximum you will get on Windows 10 is:
PowerShell Expand-Archive -Path "C:\Users\Tuffy\Desktop\PowerShell
Expand-Archive -Path "C:\Users\Whatever\Desktop\service_SC30COM_####_20191130_1834.zip"
-DestinationPath "C:\Users\Whatever\Desktop"p" -DestinationPath "C:\Whatever\Tuffy\Desktop"
Hope it helps!
You can run the following code as a bash script:
#!/bin/bash
for FILE in *.zip
do
echo "Unzipping $FILE ..."
PASSWORD=$(echo $FILE | grep -o -P '(?<=service_)[A-Za-z0-9]*_[0-9]*(?=_)')
unzip -P $PASSWORD $FILE
done
Copy the code
Paste it into FILENAME.sh
Make it executable (chmod +x FILENAME.sh)
Put it besides the zip files
Run it (./FILENAME.sh)

SQL BCP within Powershell hangs

I am new to BCP. I am tying to launch bcp.exe utility from Powershell but it hangs. Same command works fine command prompt. I am using Invoke-Expression to launch bcp.exe.
I am able to launch SQLCMD.exe without any problems.
This is my powershell.
Set-Location -Path "C:\Program Files\Microsoft SQL Server\110\Tools\Binn"
SQLCMD.EXE -b -E -S CORPSYSSQLDEV -d CORPSYSDM -Q "select top 10 * from t_test"
$psCommand = "bcp.exe ""testDB.dbo.t_test"" in ""C:\temp\test\testFile20180919.txt"" -c -t""\t"" -T -S ""TESTSQLDEV"" -e c:\temp\NoahFolder\error.csv"
Write-Host $psCommand
Invoke-Expression $psCommand
This is the result of $psCommand.
bcp.exe "testDB.dbo.t_test" in "C:\temp\test\testFile20180919.txt" -c -t"\t" -T -S "TESTSQLDEV" -e c:\temp\test\error.csv
Which works fine from command prompt but when I run the powershell script its stuck.
I am able to launch SQLCMD.exe from powershell fine.
What am I doing wrong? Any ideas or pointers.
I should have searched more before asking here. This post helped me. I was able to run BCP from powershell using Start-Process command.
$bcp = 'c:\Program Files\Microsoft SQL Server\110\Tools\Binn\bcp.exe'
$arglist = #(
#add all arguments.
)
Start-Process -FilePath $bcp -ArgumentList $arglist

Powershell script to detect OS and then display versions of SQL installed on system IF system is a server

Not sure why this script isn't working for me. When I try to run it it just goes to the next line and has ">>" on the left instead of PS C:\Users\username>
$Version = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\Currentversion" -Name Productname).Productname | if ($version -like "*server*") {Get-ItemProperty HKLM:\software\microsoft\windows\currentversion\uninstall\* | Where-Object {$_.displayname -match "sql server"}
Does anyone see what I've done wrong here? I can verify that both parts work independantly, I seem to just be having a problem when I put them together with an if statement.
Edit: $version = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\Currentversion" -Name Productname).Productname ; if ($version -like "*server*") { Get-ItemProperty HKLM:\software\microsoft\windows\currentversion\uninstall\* | Where-Object {$_.displayname -match "sql server"} }
This worked!
You need to assign $version first. That can then be used in your if statement.
$version = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\Currentversion" -Name Productname).Productname
if ($version -like "*server*")
{
Get-ItemProperty HKLM:\software\microsoft\windows\currentversion\uninstall\* | Where-Object {$_.displayname -match "sql server"}
}
Thanks, Tim.

Automatic confirmation of deletion in powershell

I'm running the following command:
get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname}
Which prompts me very frequently like this:
Confirm
The item at C:\temp\f\a\d has children and the Recurse parameter was not specified. If you continue,
all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
How can I have it automatically set to "A"?
The default is: no prompt.
You can enable it with -Confirm or disable it with -Confirm:$false
However, it will still prompt, when the target:
is a directory
and it is not empty
and the -Recurse parameter is not specified.
-Force is required to also remove hidden and read-only items etc.
To sum it up:
Remove-Item -Recurse -Force -Confirm:$false
...should cover all scenarios.
Add -confirm:$false to suppress confirmation.
Try using the -Force parameter on Remove-Item.
Add -recurse after the remove-item, also the -force parameter helps remove hidden files
e.g.:
gci C:\temp\ -exclude *.svn-base,".svn" -recurse | %{ri $_ -force -recurse}
Remove-Item .\foldertodelete -Force -Recurse
Just an additional tip:
Let's say the PS1 (helloworld.ps1) has a code like below:
Set-ExecutionPolicy Unrestricted -Confirm:$false -Force
Write-Host "Hello, World!"
And if we expect that each time the code runs, it would automatically run the Set-ExecutionPolicy without prompting the user & run the code silently...
It won't work that way!! I'm still figuring out how to run a PS code without prompting the user & will post the solution if I find out
You just need to add a /A behind the line.
Example:
get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a