SSIS Powershell - sql-server

I'm trying to run the following Poweshell command via SSIS using the following argument..
(get-content z:\2.html) | foreach-object {$_ -replace "><", ">`r`nE<"} | set-content z:\2.html
This works in Powershell at the command line, but I cannot get this to work in SSIS.
I get the error
at "", The process exit code was "1" while the expected was "0".
In SSIS I have :
1. Created an "Execute process Task"
2. Pointed the Executable to system32\WIndowsPowershell .. etc
3. Added the argument as detailed above using a variable as the filename
Any ideas?

Seems like the syntax should have been....
(get-content z:\3.html) | foreach-object {$_ -replace '><', '>`r`nE<'} | set-content z:\3.html
it works now!

Related

PowerShell SQL Server Cannot Find Path

I have 2x mini scripts which are fairly similar.
The first backs up our SQL Jobs and runs fine:
Import-Module "SQLPS" Get-ChildItem -Path SQLSERVER:\SQL\MYSERVERNAME\Default\JobServer\Jobs\ | %{$_.script()} | out-file -Filepath "MYFILEPATH_$(get-date -f yyyyMMdd).sql"
The second is meant to back up our SQL Stored Procedures, and does not produce results in the output file:
Import-Module "SQLPS" Get-ChildItem -Path SQLSERVER:\SQL\MYSERVERNAME\Default\Databases\MYDBNAME\StoredProcedures\ | %{$_.script()} | out-file -Filepath "MYFILEPATH_$(get-date -f yyyyMMdd).sql"
This problematic second script gives the below error:
Get-ChildItem : Cannot find path 'SQLSERVER:\SQL\MYSERVERNAME\Default\Databases\MYDBNAME\StoredProcedures\' because it does not exist.
It used to run successfully until around the time I upgraded to Windows10. Any suggestions on how to correct this second script?

PowerShell SQL scripting USPs and Users

I have put together the below PowerShell script which scripts out all the USPs on a server.
Is there an option to split the output into individual files (instead of saving as one whole/large file)?
Get-ChildItem -Path SQLSERVER:\SQL\myserver\Default\Databases\mydb\StoredProcedures\ | %{$_.script() | out-file -Filepath "myfilelocation.sql"}
Try the following; it should append the procedure name to the file.
Get-ChildItem -Path SQLSERVER:\SQL\myserver\Default\Databases\mydb\StoredProcedures\ |
%{
#Deal with invalid chars in Procedure name i.e. [Customers\Remove]
$SProc = "$($_.name -replace '\\', '_')"
# $Sproc | Out-Host # Uncomment this to check the procedure names...
$_.script() |
out-file -Filepath "myfilelocation_$SProc.sql"
}
This should make the file name unique per database and not have the file over-written each time. That is what is currently happening with your script.

Output overwrites previous entry in file

If I get rid of the last line Out-File "HDDresults.txt" then the output shows on the screen in the correct format, just a long list of all the computers and their serial numbers. If I try to output to a file, each computer entry overwrites the previous entry, so when the script finishes executing there is only the last entry in the file. How do I get the file output to look exactly like the console output?
I don't know how to script. I just copied and pasted from multiple sources until I got something that works.
Import-Module ActiveDirectory
Get-ADComputer -filter * | Foreach-Object {
Get-WmiObject Win32_PhysicalMedia -computer $_.name |
Format-Table __server, Tag, SerialNumber |
Out-File "HDDresults.txt"
}
You simply need to set the -Append flag:
Out-File "HDDresults.txt" -Append
By default, Out-File overwrites the content of the file for each write operation. This will cause it to add text to the end of the file instead.
While adding the -Append argument makes the script function, I think a better fix to this is to move the Select statement and all that follows it outside of the ForEach loop so that the file is written once with all of the information once it is processed, and not having to open the file, write to it, close it, open it again, write to it, close it again, for each system.
Import-Module ActiveDirectory
Get-ADComputer -filter * |
Foreach-Object { Get-WmiObject Win32_PhysicalMedia -computer $_.name } |
Format-Table __server, Tag, SerialNumber |
Out-File "HDDresults.txt"

Get Active Directory Information from PC's in a text file - Powershell

I am running to an issue with a Powershell command line I'm attempting to run. What we are needing is to get the PC Name and LastLogonDate from PC's in a list of text files with Powershell.
Here is the code I'm attempting to run:
Get-Content C:\Hosts.txt | ForEach-Object{Get-ADComputer $_ -Properties Name,LastLogonDate | Select-Object Name,LastLogonDate | Export-Csv C:\Output.csv}
When I run that code I get an error stating: "Cannot find a object with identity: 'ComputerName'" despite the fact that the PC is truly in AD. What is confusing me is that everything after the ForEach-Object runs great if you run it by itself. When you add the Get-Content and ForEach-Object the errors begin. I can see from the error messages that each individual computer name is being read from the text file, but I wonder if it is passing it in a way the Get-ADComputer doesn't like.
A couple things. First is to see what's in the hosts.txt file. Second thing is to move the Export-Csv command outside of the ForEach-Object statement. If you leave it how it is, it will only return the last object it processed in the csv file. I've posted an example of how it should be.
Get-Content C:\Hosts.txt | ForEach-Object {Get-ADComputer $_ -Properties Name,LastLogonDate | Select-Object Name,LastLogonDate} | Export-Csv C:\Output.csv
I'm not able to replicate your problem and the only thing different is the contents of the hosts.txt file so it would be helpful to see it.

Powershell Script using Invoke-SQL command,needed for SQL job, the SQL Server version of Powershell is somewhat crippled, is there a workaround?

Full Question: Have Powershell Script using Invoke SQL command, using snappins, I need them to be included in a SQL job, the SQL Server version of Powershell is somewhat crippled, does anyone know a workaround?
From what I have gathered, SQL Management Studio's version of powershell is underpowered, not allowing for the use of snappins, as such it does not recognize the cmdlets that I used in the script. I have tried running it in the job as a command line prompt rather than a Powershell script, which causes the code to work somewhat, however I check the history on the job and it says that invoke-sql is still not a recognized cmdlet. I speculate that because I am running the code on a remote server, with different credentials than my standard my profile with the snappins preloaded isn't being loaded, though this is somewhat doubtful.
Also, as I am a powershell rookie, any advice on better coding practices/streamlining my code would be much appreciated!
Code is as follows:
# define parameters
param
(
$file = "\\server\folder\file.ps1"
)
"invoke-sqlcmd -query """ | out-file "\\server\folder\file.ps1"
# retrieve set of table objects
$path = invoke-sqlcmd -query "select TableName from table WITH (NoLock)" -database db -server server
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
$so.DriPrimaryKey = $false
$so.Nocollation = $true
$so.IncludeIfNotExists = $true
$so.NoIdentities = $true
$so.AnsiPadding = $false
# script each table
foreach ($table in $path)
{
#$holder = $table
$table = get-item sqlserver:\sql\server\default\databases\database\tables\dbo.$($table.TableName)
$table.script($so) | out-file -append $file
}
(get-content "\\server\folder\file.ps1") -notmatch "ANSI_NULLS" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch " AS "| out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch "Quoted_" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\) ON \[PRIMARY\].*", ")" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\[text\]", "[nvarchar](max)" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace " SPARSE ", "" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "COLUMN_SET FOR ALL_SPARSE_COLUMNS", "" | out-file "\\server\folder\file.ps1"
""" -database database -server server" | out-file "\\server\folder\file.ps1" -append
So I figured out the answer to my own question. Using this site: http://www.mssqltips.com/tip.asp?tip=1684 and
http://www.mssqltips.com/tip.asp?tip=1199
I figured out that he was able to do so using a SQL Server Agent Proxy, so I followed the yellow brick road, and basically I set up a proxy to my account and was able to use the external powershell through a feature. A note, you need to create a credential under the securities tab in object explorer prior to being able to select one when creating the proxy. Basically I ended up creating a proxy named powershell, using the powershell subsystem, and use my login info to create a credential. VOILA!
You have to add the snapins each time. In your editor you likely already have them loaded from another script/tab/session. In SQL Server you will need to add something like this to the beginning of the script:
IF ( (Get-PSSnapin -Name sqlserverprovidersnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlserverprovidersnapin100
}
IF ( (Get-PSSnapin -Name sqlservercmdletsnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlservercmdletsnapin100
}
I'm not sure the error you are trying to workaround - can you post that?
Have you tried this from a PowerShell prompt?
Add-PSSnapin SqlServerCmdletSnapin100

Resources