PowerShell Script To Automatically Print SSRS 2008R2 Report - powershell

Can I use a Powershell to generate and print an SSRS report (with parameters) to a network printer.
I will use a SQL Agent job poll a table for new order entries. When an order comes in I want to generate an SSRS report and print it to one of many remote printers (printer will be one of the input parameters) on our network, e.g., print a pick ticket in the appropriate warehouse when an order is placed.
We currently use batch files to print to local printers, but the program hangs often and does not scale well.

In this case:
Report Name: Ticket System
Parameters are: Date and Department
Report Format:PDF
#Place adobe in your path
$env:Path = $env:Path + ";C:\Program Files (x86)\Adobe\Reader 11.0\Reader"
#Specify variables and pass parameters and specify format of report PDF (to keep things simple)
$url = "http://$serverName/ReportServer?/$reportFolder/Ticket+System&Date=3-31-2014&Department=Finance&rs:Format=PDF"
#Use alternative credentials as needed to access report server
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $TRUE
$file = "C:\temp\report.pdf"
$webclient.DownloadFile($url,$file)
#Specify printer \\server\name
$printer = "\\NorthSide\SharpPrinter"
#The /s /o switch may not be necessary. You can test it out.
AcroRd32.exe /s /o /t $file $printer
Get-Process AcroRd32.exe | kill
References:
This link will indicate how to pass parameters to a report via url
http://msdn.microsoft.com/en-us/library/ms155391.aspx
This link will indicate how to access a report in a printable format via url
http://msdn.microsoft.com/en-us/library/ms154040.aspx
This link will show you how to use powershell to write this file to the filesystem via url.
http://teusje.wordpress.com/2011/02/19/download-file-with-powershell/
This link will show you how to push the job to the spooler. Using Powershell version 4.0
http://technet.microsoft.com/en-us/library/hh849886.aspx
If you are having trouble using powershell in a sql agent job, I alternatively would do the polling with a Task Scheduler job and query your database using the SQLPS module.
Hope that helps.

Related

Read local group policy using powershell commands

Iam unable to get Gpresult of local group policy using powershell. I need help on this to get the local gpo's on windows Server 2022
not much you want to share with us about what you have tried. you could do:
#Export gpresult into xml
gpresult /x C:\Users\Administrator\Documents\gpo.xml
#Load xml
$xml = New-Object xml
$xml.Load("C:\Users\Administrator\Documents\gpo.xml")
$xml contains the information.

SSAS Deployment Via Powershell Corrupting Format String

I am having a problem when deploying cubes via PowerShell that I don’t know how to fix. In my solution I have some measures with FormatString: \£ #,##0;-\£ #,##0. If I deploy them normally via Visual Studio, the XMLA I pull from the SSAS server after deployment will have <FormatString>\£ #,##0;-\£ #,##0</FormatString> which is all good and expected. However, if I deploy via PowerShell, the resulting XMLA from the server is <FormatString>\£ #,##0;-\£ #,##0</FormatString>.
I realise the issue is with £ being parsed, but I am not sure how to resolve it.
The bit of background here is that I am using Octopus Deploy, and I've extracted the PowerShell below where the issue occurs:
$modelpath = "C:\...\Project_Name.xmla"
$Path_To_Microsoft_AnalysisServices_Deployment = "C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\Microsoft.AnalysisServices.Deployment.exe"
$SSAS_Project_Name = "Project_Name"
$Path_To_SSAS_Bin_Folder = "F:\Octopus Deploy\CustomInstallation\Project_Name\Content"
$FilePath_asdatabase = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.asdatabase"
$FilePath_deploymenttargets = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.deploymenttargets"
$FilePath_configsettings = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.configsettings"
$FilePath_deploymentoptions = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.deploymentoptions"
Start-Process -FilePath $Path_To_Microsoft_AnalysisServices_Deployment -ArgumentList "`"$FilePath_asdatabase`"","/s:`"$FilePath_DeploymentLog`"","/o:`"$SSAS_Project_Name.xmla`"","/d" -Wait -NoNewWindow
# Load the Adomd Client
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.AnalysisServices.AdomdClient”) | Out-Null;
# Connect to the server
Write-Host "Executing Deployment Script"
$serverName = “Data Source=.”
$conn = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdConnection $serverName
$conn.Open()
# Read XMLA
$xmla = Get-Content $modelpath
# Execute XMLA
$cmd = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdCommand $xmla, $conn
return $cmd.ExecuteNonQuery();
I have done some investigation and I’ve found the following:
The xmla file produced by PowerShell (not in the snippet) has the correct Format String \£ #,##0;-\£ #,##0
The .asdatabase file also has the correct format string
I suspect that something is happening either at:
Start-Process -FilePath $Path_To_Microsoft_AnalysisServices_Deployment -ArgumentList “`”$FilePath_asdatabase`””,”/s:`”$FilePath_DeploymentLog`””,”/o:`”$SSAS_Project_Name.xmla`””,”/d” -Wait -NoNewWindow
or further down at:
# Execute XMLA
$cmd = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdCommand $xmla, $conn
return $cmd.ExecuteNonQuery();
Any help would be appreciated.
PS: I’ve tried playing with the Format String when setting it in the solution but haven’t been able to find a solution. Note that I can’t simple use “Currency” b/c the server is set to English (US).
The answer to this is to specify the encoding. From Jeroen in the comment in response to my question:
It looks like PowerShell is auto-detecting the encoding of the XMLA incorrectly as Windows-1252, when it's actually UTF-8 (without a BOM). Try $xmla = Get-Content $modelpath -Encoding UTF8. It may also be the case that the XMLA itself is actually incorrect -- make sure to inspect it in an editor capable of reporting the encoding, like Notepad++, not just have it echo back by PowerShell itself. – Jeroen Mostert 15 mins ago

Make a .json-file more flexible with Variables for automation deploy

I've got a PowerShell-Script to create a VM from an Image in Azure and in this Script I deposited a .json (Parameter for VM, etc.). But if I want to create more than one VM the Names of the VM, Vnet, etc. cannot be the same for every execution (have to be in the same Resource Group).
So my Question: How can I insert Variables in the .json File to change the Name of the VM, etc. for every execution? Perhaps I have to rethink?
A very basic approach could be something like this:
# Grab the file contents
$contents = Get-Content -Path $templateFile
# Update some tokens in the file contents
$contents = $contents.replace("original value", "new value")
# Push the updated contents to a new file
Set-Content -Path $updatedFile -Value $contents
If you have a value that changes with every deployment, you could also consider using the -TemplateParameterObject parameter with the New-AzureRmResourceGroupDeployment cmdlet. That way, you can generate the values in your powershell script without having to output them to json file first.
For more details, have a look at the cmdlet specs

PowerShell scheduled task not converting CSV to EXCEL

I have a server health check script which i'm trying to get working by scheduled task.
The scheduled task has the following set for 'AddArguments"
Add Arguments: -NoLogo -ExecutionPolicy Bypass -File "C:\HealthCheck.ps1"
Everything in the server health portion of full script works fine to create the .csv report, except the last part, which does the CSV to excel conversion/save/close - I've not included the preceding code as it includes some confidential stuff, and i don't believe it's relevant.
When I run the script with the same ID, but from the GUI (not as a scheduled task) it works fine.
Note: The last part of the script definitely does launch excel briefly and performs the functions, and saves/closes it - i'm thinking the scheduled task isn't doing this because it's not supported by Microsoft?
I did find the following SpiceWorks post but the solution noted didn't resolve the issue for me in this case. That's where you create a DESKTOP folder under these paths depending on your version of Office (i'm using Office 2010 32-bit on Windows 7 x64 Pro)
C:\windows\system32\config\systemprofile
C:\windows\syswow64\config\systemprofile
Anyway, here's the code - Any help appreciated!
#Convert CSV to EXCEL, format, and save
#Create excel object
$xl = new-object -comobject excel.application
$xl.visible = $true
#Input
$Workbook = $xl.workbooks.open(“$Dir\Reports\SeverHealth-Results- $CurrentDate.csv”)
$worksheet = $workbook.worksheets.Item(1)
$xl.Rows.Item("2:2").Select()
$xl.ActiveWindow.FreezePanes = $true
$HeaderRow = $Worksheet.Range("A1:L1")
$HeaderRow.Font.Bold = $True
$HeaderRow.Font.Underline = $True
$range = $worksheet.UsedRange
$range.AutoFilter() | Out-Null
$range.EntireColumn.AutoFit() | Out-Null
$rowc = $WorkSheet.UsedRange.Rows.Count
$colc = $WorkSheet.UsedRange.Columns.Count
#Coloring
for ($z = 1; $z -le $rowc; $z++) {
$ActionReqCol = $worksheet.cells.item($z,7)
$ServerCol= $worksheet.cells.item($z,1)
if ($ActionReqCol.text -eq "YES") {
$ActionReqCol.interior.colorindex=3
$ACtionReqCol.font.colorindex=2
$ServerCol.interior.colorindex=3
$ServerCol.font.colorindex=2}}
#Save and close!
$EndDate = Get-Date
$EndDate = $EndDate.ToString('MM-dd-yyyy_hhmm')
$Worksheets = $Workbooks.worksheets
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$Workbook.SaveAs($Dir + "\Reports\SeverHealth-Results-$EndDate.xls”, $XLFixedFormat)
$Workbook.Saved = $True
$xl.Quit()
Write the command to invoke the PowerShell with arguments in a batch file. I believe from the comments that you are already able to do this successfully. Configure the Task Scheduler to execute the batch file.
Other advantage of this is, you have reduced dependency. If later you want to make modifications to your command or alter arguments, then you will be able to do so without altering or even opening the Task Scheduler.
Update: #Kenny reported that running task scheduler's task with highest privilege resolved this. The script required elevated access and the same was provided by checking the check box in Task Scheduler to run the task with highest privilege.

Win32_TCPIPPrinterPort WMI query is empty

When I query WMI (by any method so far) for printers:
select * from Win32_Printer
I get normal results. When I try to query for ports:
select * from Win32_TCPIPPrinterPort
the query "succeeds" but I get no results. There are over 100 ports on this server, but neither prnport.vbs, wbemtest, powershell, or my own code are getting any results.
Operating system in 2003R2 and the user has admin privs.
Turns out that local ports (and consequently redirected locals like ghostscript etc) are NOT listed by this WMI query. They are stored directly in the registry. This means that normal scripting to migrate these printer parameters will get the printers but not the port information.
They are stored in:
HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\Redirected Port\Ports
Live and learn.
I have a couple print servers with many queues on them and they are running on MS Windows 2003. I required the port configuration as well. Namely queue and protocol. I nested the following commands in my foreach loop and I was able to get the data I needed:
$PrintQueue = (Get-ItemProperty -Path Registry::"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\$Queue" -Name Queue).Queue
$Protocol = (Get-ItemProperty -Path Registry::"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\$Queue" -Name Protocol).Protocol
$Queue variable in the path string above is the print queue variable in my foreach loop. Change it to the Print Queue name as needed or set the variable earlier in the code.
I also ran into print queues that did not have a Queue value set so I added a if statement to set one, which I required in order to feed this data to another script that installs the print queue on a 2012R2 server.
if($PrintQueue = $null){
$PrintQueue = 'Print'
}#if
Hope this helps.