Output which Excel files are password protected - vba

I am trying to modify the below script to be able to search for multiple Excel files that contain macros. The issue I'm having is being able to access password protected files. It is prompting to enter a password for each password protected file. I would like to skip it and just process the unprotected ones. Is there a way or script that I could use to output which files are password protected and just process the unprotected ones?
Here is the script I'm currently using:
Get-ChildItem -path "server path" -recurse | where {$_.extension -match "^\.xls(m|)$"} | ForEach-
Object -Begin {
$thisThread = [System.Threading.Thread]::CurrentThread
$originalCulture = $thisThread.CurrentCulture
$thisThread.CurrentCulture = New-Object System.Globalization.CultureInfo('en-US')
$excel = new-object -comobject excel.application
Try{
$excel.Workbooks.open($path, 0, 0, 5, $password)}
Catch{
Write-Host 'Book is password protected.'}
} -Process {
$workbook = $excel.workbooks.Open($_.FullName)
$_.FullName + " : " + $workbook.HasVBProject
$workbook.Close($false)
} -end {
$excel.Quit()
$thisThread.CurrentCulture = $originalCulture
}| out-file c:\results.csv
Here is the errors:
Book is password protected.
Unable to get the Open property of the Workbooks class
At line:11 char:5
+ $workbook = $excel.workbooks.Open($_.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
At line:13 char:4
+ $workbook.Close($false)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Unable to get the Open property of the Workbooks class
At line:11 char:5
+ $workbook = $excel.workbooks.Open($_.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
At line:13 char:4
+ $workbook.Close($false)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Related

PowerShell script failing when run from SQL Agent

I have created a PowerShell script that does the following:
Copies a template Excel file to another directory
Imports data into this template file using the ImportExcel module created by Doug Finke ( https://www.powershellgallery.com/packages/ImportExcel/7.1.0 )
Runs a macro that is contained in the template file
Renames the file as an .xlsx file type
When I run this script from the server, it executes perfectly and does what is expected. But when I tried to set up a SQL Agent job to run this same PS script, it is failing and I cannot find the reason it would do so.
Here is my PS script:
# Directory Information
$RootDirectory = "D:\MSSQL\SSIS\BIN Commission Report\"
$ArchiveFolder = "Archive\"
$SourceFolder = "Source\"
$TemplateFolder = "Template\"
# File Information
$TemplateFile = "Commission_Invoices_Template.xlsm" #Template file with macro
$MacroFile = "Commission_Invoices.xlsm" #Macro-enabled file with vendor data
$VendorFile = "Commission_Invoices.xlsx" #File provided by the vendor
$DataImportFile = "Commission_Invoices_Import.xlsx" #File used to import data into SQL
$AppliedMacroFile = "Commission_Invoices_Import.xlsm"
#Full paths for each file
$TemplatePath = $RootDirectory, $TemplateFolder, $TemplateFile -Join ""
$MacroPath = $RootDirectory, $SourceFolder, $MacroFile -Join ""
$VendorPath = $RootDirectory, $SourceFolder, $VendorFile -Join ""
$DataImportPath = $RootDirectory, $SourceFolder, $DataImportFile -Join ""
$AppliedMacroPath = $RootDirectory, $SourceFolder, $AppliedMacroFile -Join ""
If ( Test-Path $MacroPath ) { Remove-Item $MacroPath }
If ( Test-Path $AppliedMacroPath ) { Remove-Item $AppliedMacroPath }
#Copy template file to use for date insertion and macro
Copy-Item $TemplatePath -Destination $MacroPath
# Copy data from vendor spreadsheet into macro-enabled workbook
Import-Excel -Path $VendorPath -WorksheetName Sheet1 | Export-Excel $MacroPath -WorksheetName Commission_Invoice
# Run the macro in Excel
$MacroName = "CommissionPrep"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$WB = $Excel.Workbooks.Add($MacroPath)
$Excel.Run($MacroName)
#Close Excel
$WB.Close($false)
$Excel.Quit()
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WB)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Remove-Variable -Name Excel
# Copy data to xlsx file from xlsm for data import into SQL
Import-Excel -Path $AppliedMacroPath -WorksheetName Commission_Invoice | Export-Excel $DataImportPath -WorksheetName Commission_Invoice -AutoSize
If ( Test-Path $MacroPath ) { Remove-Item $MacroPath }
If ( Test-Path $VendorPath ) { Remove-Item $VendorPath }
If ( Test-Path $AppliedMacroPath ) { Remove-Item $AppliedMacroPath }
This is what my SQL Agent job looks like:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File "D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1"
And here is the error message when run as a SQL Agent job:
Message
Executed as user: CompanyX\CompanyXSQLADMIN.
Microsoft Excel cannot access the file 'D:\MSSQL\SSIS\BIN Commission Report\Source\Commission_Invoices.xlsm'.
There are several possible reasons:
The file name or path does not exist.
The file is being used by another program.
The workbook you are trying to save has the same name as a currently open workbook.
At D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1:35 char:1 + $WB = $Excel.Workbooks.Add($MacroPath) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], COMException + FullyQualifiedErrorId : System.Runtime.InteropServices.COMExceptionException calling "Run" with "1" argument(s): "Cannot run the macro 'CommissionPrep'. The macro may not be available in this workbook or all macros may be disabled."
At D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1:36 char:1 + $Excel.Run($MacroName) + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : COMException
You cannot call a method on a null-valued expression.
At D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1:39 char:1 + $WB.Close($false) + ~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNullException calling "ReleaseComObject" with "1" argument(s): "Object reference not set to an instance of an object."
At D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1:45 char:1 + [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WB) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NullReferenceException 0 'D:\MSSQL\SSIS\BIN Commission Report\Source\Commission_Invoices_Import.xlsm' file not found
At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\7.0.1\Public\Import-Excel.ps1:105 char:17 + throw "'$($Path)' file not found" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: ('D:\MSSQL\SSIS\... file not found:String) [], RuntimeException + FullyQualifiedErrorId : 'D:\MSSQL\SSIS\BIN Commission Report\Source\Commission_Invoices_Import.xlsm' file not found. Process Exit Code 1. The step failed.
I am unclear as to how this script executes perfectly when run from the PowerShell ISE shell when run locally on the server but fails it is run via a SQL Agent job. Any suggestions on how to fix this?
have you tried to set the executionpolicy for your SQL Agent job:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -File "D:\MSSQL\SSIS\BIN Commission Report\Scripts\CommissionInvoices_PS.ps1"

Invoke SQL command not working in Power shell core 6.0.2

invoke sql command is not working it throws a below error can some one help me with it
invoke-sqlcmd : The term 'invoke-sqlcmd' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path
is correct and try again. At
D:\Process\VeevaNetwork\Code\HCP_HCO_External_ID_Network_Updates.ps1:7
char:9
+ $result=invoke-sqlcmd -inputFile "D:\Process\VeevaNetwork\cfg\SQL Scr ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (invoke-sqlcmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
invoke-sqlcmd : The term 'invoke-sqlcmd' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path
is correct and try again. At
D:\Process\VeevaNetwork\Code\HCP_HCO_External_ID_Network_Updates.ps1:8
char:10
+ $result1=invoke-sqlcmd -inputFile "D:\Process\VeevaNetwork\cfg\SQL Sc ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (invoke-sqlcmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Export-Csv : Cannot bind argument to parameter 'InputObject' because
it is null. At
D:\Process\VeevaNetwork\Code\HCP_HCO_External_ID_Network_Updates.ps1:9
char:10
+ $result |export-csv "D:\Process\VeevaNetwork\Out\HCP_EXTID_Update_Adh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind argument to parameter 'InputObject' because
it is null. At
D:\Process\VeevaNetwork\Code\HCP_HCO_External_ID_Network_Updates.ps1:10
char:11
+ $result1 |export-csv "D:\Process\VeevaNetwork\Out\HCO_EXTID_Update_Ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand

SQL Server error when updating/creating records in database from PowerShell

Here is the function I use to send queries to SQL
function Invoke-SQL
{
param (
[string]$server,
[string]$database,
[string]$Query
)
$connectionString = "Data Source=$server; " +
"Integrated Security=SSPI; " +
"Initial Catalog=$database"
$connection = new-object
system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($Query, $connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}
When I run a query like this:
Invoke-SQL -server 'ServerName' -database 'DBname' -Query "SELECT * FROM [DBname].[dbo].[TableName] WHERE UserID = '$userid' AND ComputerName = '$computername'"
I get the following error:
ERROR: Exception calling "Fill" with "1" argument(s): "Conversion failed when converting from a character string to uniqueidentifier."
PSDesk_Client.ps1 (358, 2): ERROR: At Line: 358 char: 2
ERROR: + $adapter.Fill($dataSet) | Out-Null
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : NotSpecified: (:) [],
MethodInvocationException
ERROR: + FullyQualifiedErrorId : SqlException
ERROR:
ERROR: Exception calling "Fill" with "1" argument(s): "Conversion failed when converting from a character string to uniqueidentifier."
PSDesk_Client.ps1 (358, 2): ERROR: At Line: 358 char: 2
ERROR: + $adapter.Fill($dataSet) | Out-Null
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : NotSpecified: (:) [],
MethodInvocationException
ERROR: + FullyQualifiedErrorId : SqlException
ERROR:
It seems it is having this error twice because:
First, it runs a query to get information from the database
Second, it runs a query to create/update information as needed on the database
Whether I have it return the data or just send a command it is unhappy with $adapter.Fill($dataSet) | Out-Null. Why are my two uniqueidentifiers causing this error and what can I do to fix this?
Upon trying to enter in a record manually, it throws an error:
Error Message: Guid should contain 32 digits with 4 dashes.
Is uniqueidentifier the wrong data type then? It needs to be a string but certainy shouldn't be required to be in that format or any format

How do I get the last file from a hot folder using PowerShell? [duplicate]

This question already has answers here:
Powershell: Count items in a folder with PowerShell
(8 answers)
Closed 8 years ago.
We have a client that uploads one .pkg file each hour to a specified folder on our FTP. I want to create a SQL Server Agent Job to grab that file, import the data into a table in a SQL Server DB, then move and rename the file.
I am successful in doing this (using the code below) except when there is only 1 file left. When there is only one file left it will not import... and then it moves the actual folder with the file in it (renaming the folder as it does this). I have also provided the errors below.
Script:
Function AutoImportCommaFlatFilesTopOne($location, $server, $database)
{
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "Data Source=" + $server + ";Database=" + $database + ";integrated security=true"
$files = Get-ChildItem $location
$fileName = $files[0]
$full = $location + $fileName
$table = "rawUSPS"
$insertData = New-Object System.Data.SqlClient.SqlCommand
$insertData.CommandText = "EXECUTE stp_CommaBulkInsert #1,#2"
$insertData.Parameters.Add("#1", $full)
$insertData.Parameters.Add("#2", $table)
$insertData.Connection = $connection
$connection.Open()
$insertData.ExecuteNonQuery()
$connection.Close()
move-item $full (("C:\Test\archiveFolder\{0:yyyyMMdd_HHmmss}" + "_" + $fileName.BaseName + ".log") -f (get-date))
}
AutoImportCommaFlatFilesTopOne -location "C:\Test\testFolder\" -server "LAN-DP-03" -database "FlatFileInsertTestingDB"
The errors:
PS C:\Users\rcurry> C:\Scripts\140627.ps1
Unable to index into an object of type System.IO.FileInfo.
At C:\Scripts\140627.ps1:8 char:24
+ $fileName = $files[ <<<< 0]
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CannotIndex
Exception calling "ExecuteNonQuery" with "0" argument(s): "Cannot bulk load because the file "C:\Test\testFolder\" could not be opened. Operating system error
code 3(The system cannot find the path specified.)."
At C:\Scripts\140627.ps1:21 char:32
+ $insertData.ExecuteNonQuery <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I figured out the problem. Per hydropowerdeveloper at stackoverflow.com/questions/14714284/… : > Well, it turns out that this is a quirk caused precisely because there was only one file in the directory. Some searching revealed that in this case, PowerShell returns a scalar object instead of an array. This object doesn’t have a count property, so there isn’t anything to retrieve. So I simply needed to force an array using '#'.

Powershell null-valued expression

I have the script below and for the life of me can not get why it is giving me "You cannot call a method on a null-valued expression." It errors on two spots.
Which computer?: NFDW2206
What is the AssetID?: 00000007
Checking NFDW2206 to see if the Registry Key exists..
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:11 char:33
+ $regassetid = $regKey.GetValue <<<< ("AssetID")
+ CategoryInfo : InvalidOperation: (GetValue:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The Key does not exist. Writing AssetID.....
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:18 char:20
+ $regKey.Setvalue <<<< ('AssetID', $AssetID, 'String')
+ CategoryInfo : InvalidOperation: (Setvalue:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The code is below
$Computer = Read-Host "Which computer?"
$AssetID = Read-Host "What is the AssetID?"
if (($Computer -eq "") -or ($AssetID -eq "")) {
Write-Host "Error: A blank parameter was detected" -BackgroundColor Black -ForegroundColor Yellow
} else {
if (Test-Connection -comp $Computer -count 1 -quiet) {
Write-Host "Checking $Computer to see if the Registry Key exists.."
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield")
$regassetid = $regKey.GetValue("AssetID")
if ($regassetid -eq $null) {
Write-Host "The Key does not exist. Writing AssetID....."
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
$regKey.Setvalue('AssetID', $AssetID, 'String')
} else {
$OverWrite = Read-Host "AssetID exists do you wish to continue?"
if (($OverWrite -eq "y") -or ($OverWrite -eq "yes")) {
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
$regKey.Setvalue("AssetID", $AssetID, "String")
}
}
} else {
Write-Host "Error: $computer is offline..." -BackgroundColor Black -ForegroundColor Yellow
}
}
The docs say that OpenSubKey will return null if the operation fails. It is likely it can't find the key. Is the remote system a 64-bit OS? If so, it could be you're running into a registry virtualization issue. Might need to look under SOFTWARE\WOW6432Node\Multek Northfield