PowerShell trying to code a SQL factory... - sql

I am working on a script that needs several sql connections over and over again. I need paralleism to speed up things. That's why I would like to have kind of SQL factory that returns me a connection handle. But somehow my code isn't working. What am i doing wrong here?
$m = New-Module -Name sql_factory -AsCustomObject -ScriptBlock {
Function new_session {
$db_host = 'my.sqlhost.tld';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'db';
$table_name = $env:COMPUTERNAME;
$conn = New-Object system.data.sqlclient.sqlconnection;
$conn.ConnectionString = "Server=${db_host};Database=${db_name};User ID=${db_user};Password=${db_pass};";
$cmd = New-Object System.Data.SqlClient.SqlCommand;
$cmd.connection = $conn;
return $cmd, $conn;
}
}
$test = {
$cmd, $conn = $m.new_session();
$conn.Open();
$cmd.CommandText = "INSERT INTO tableXXX (date, time, action, protocol, src_ip, dst_ip, src_port, dst_port, size, tcp_flags, tcpsyn, tcpack, tcpwin, icmptype, icmpcode, info, path) VALUES ('xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx')";
$cmd.ExecuteNonQuery();
$conn.Close();
}
start-job -ScriptBlock $test | Out-Null
get-job | receive-job -AutoRemoveJob -Wait
This is the error message i am receiving...
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost
Property 'CommandText' cannot be found on this object; make sure it exists and is settable.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
+ PSComputerName : localhost
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost

The script block doesn't know anything about the module you created. You'd need to pass it as an argument when you start the job:
$test = {
param($db_factory)
$cmd, $conn = $db_factory.new_session()
...
}
Start-Job -ScriptBlock $test -ArgumentList $m | Out-Null
...
However, since you're creating a new connection for each job anyway, you could just as well put the code establishing the database connection inside the script block:
$test = {
param($db_host, $db_user, $db_pass, $db_name)
$table_name = $env:COMPUTERNAME
$cs = "Server=$db_host;Database=$db_name;User ID=$db_user;Password=$db_pass;"
$conn = New-Object system.data.sqlclient.sqlconnection
$conn.ConnectionString = $cs
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $conn
$conn.Open()
...
}
Start-Job -ScriptBlock $test -ArgumentList 'my.sqlhost.tld','user','pass','db' |
Out-Null
...

Also you can use SQL Server Management Objects (SMO)
$m = {
param($instanceName, $login, $pass, $dbName)
#import SQL Server module
Import-Module SQLPS -DisableNameChecking
#Create server connection
$srvConn = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$srvConn.ServerInstance = $instanceName
$srvConn.LoginSecure = $false
$srvConn.Login = $login
$srvConn.Password = $pass
#Initiate the object and set the database
$srv = New-Object Microsoft.SqlServer.Management.SMO.Server($srvConn)
$db = $srv.Databases[$dbName]
#Execute T-SQL
$db.ExecuteNonQuery("INSERT INTO tableXXX (date, time, action, protocol, src_ip, dst_ip, src_port, dst_port, size, tcp_flags, tcpsyn, tcpack, tcpwin, icmptype, icmpcode, info, path) VALUES ('xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx','xxx')")
}
start-job -ScriptBlock $m -ArgumentList 'my.sqlhost.tld','user','pass','db' | Out-Null
get-job | receive-job -AutoRemoveJob -Wait

Related

Azure Runbook not deleting Files in Fileshare

I am trying to to use Azure Powershell Runbooks to delete files out of the Azure Fileshare. There are no errors returned, but the file is not deleted. The Automation Account has a Run As account setup that is not expired or anything and the script works if I run it from my local machine. Looking for some advise on this.
$ctx = New-AzureStorageContext -StorageAccountName "" -StorageAccountKey ""
$shareName = ""
$directoryPath = ".cloudconsole"
$DirIndex = 0
$day = 1
$startdate = (Get-Date).AddDays(-180)
$endDate = (Get-date).AddDays(-32)
$dirsToList = New-Object System.Collections.Generic.List[System.Object]
$shareroot = Get-AzureStorageFile -ShareName $shareName -Path $directoryPath -context $ctx
$dirsToList += $shareroot
While ($dirsToList.Count -gt $DirIndex)
{
$dir = $dirsToList[$DirIndex]
$DirIndex ++
$fileListItems = $dir | Get-AzureStorageFile
$dirsListOut = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFileDirectory"}
$dirsToList += $dirsListOut
$files = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFile"}
foreach($file in $files)
{
$task = $file.CloudFile.FetchAttributesAsync()
$task.Wait()
if ($file.CloudFile.Properties.LastModified -ge $startdate -and $file.CloudFile.Properties.LastModified -ge $endDate )
{
if ($file.CloudFile.Properties.LastModified.day -ne '01' )
{
$file | Remove-AzureStorageFile
}
}
if ($file.CloudFile.Properties.LastModified -lt $startdate)
{
$file | Remove-AzureStorageFile
}
}
}
BoxJumper: As kavyasaraboju-MT referred, below piece of script should help you.
$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $key
$shareName = <shareName>
$startdate = (Get-Date).AddDays(-180)
$endDate = (Get-date).AddDays(-32)
$DirIndex = 0
$dirsToList = New-Object System.Collections.Generic.List[System.Object]
# Get share root Dir
$shareroot = Get-AzStorageFile -ShareName $shareName -Path . -context $ctx
$dirsToList += $shareroot
# List files recursively and remove file older than 14 days
While ($dirsToList.Count -gt $DirIndex)
{
$dir = $dirsToList[$DirIndex]
$DirIndex ++
$fileListItems = $dir | Get-AzStorageFile
$dirsListOut = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFileDirectory"}
$dirsToList += $dirsListOut
$files = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFile"}
foreach($file in $files)
{
# Fetch Attributes of each file and output
$task = $file.CloudFile.FetchAttributesAsync()
$task.Wait()
# remove file if it's modified between after last 180 days and before last 30 Days
if ($file.CloudFile.Properties.LastModified -lt (Get-Date).AddDays(-32) -and $file.CloudFile.Properties.LastModified -ge (Get-Date).AddDays(-180))
{
## print the file LMT
# $file | Select #{ Name = "Uri"; Expression = { $_.CloudFile.SnapshotQualifiedUri} }, #{ Name = "LastModified"; Expression = { $_.CloudFile.Properties.LastModified } }
# remove file
$file | Remove-AzStorageFile
}
}
#Debug log
# Write-Host $DirIndex $dirsToList.Length $dir.CloudFileDirectory.SnapshotQualifiedUri.ToString()
}

Powershell script- send email to all users that are outputted

This is my code below-
I am new to Powershell so Im looking for a way to send an email to all the users that are outputted and also send an an email to myself with the CSv file of output?
get-module azuread
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
$dt = (Get-Date).AddDays(-90)
$Users = Get-AzureADUser -Top 100000 | Where {$_.UserPrincipalName -like "*gmail.com"} | Select UserPrincipalName,ObjectId
$Users | ForEach-Object {
Get-AzureADDevice -All:$true | Where {$_.ApproximateLastLogonTimeStamp -le $dt}
$user = $_
Get-AzureADUserRegisteredDevice -ObjectId $user.ObjectId | ForEach-Object {
$Result += New-Object PSObject -property #{
DeviceOwner = $user.UserPrincipalName
DeviceName = $_.DisplayName
DeviceOSType = $_.DeviceOSType
ApproximateLastLogonTimeStamp = $_.ApproximateLastLogonTimeStamp
IsCompliant = $_.IsCompliant
}
}
}
thANK YOU

Efficient Script to get all Extended File Properties

I'm pretty new working with Powershell and i have some working code but I'm not sure how to get it into an efficient routine to return all of the extended file properties of some video files i have.
I have:
# The basic setup for the next steps
$path = 'C:\test\videotocheck.mp4'
$shell = New-Object -COMObject Shell.Application
$folder = Split-Path $path
$file = Split-Path $path -Leaf
$shellfolder = $shell.Namespace($folder)
$shellfile = $shellfolder.ParseName($file)
# This command gets a list of all the extended attributes available for this file
0..500 | Foreach-Object { '{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_) }
# These commands get the individual attributes picked out of the list above
$shellfolder.GetDetailsOf($shellfile, 314)
$shellfolder.GetDetailsOf($shellfile, 316)
All i want to do is provide a filename and have it give me a list back of all of the attributes and their values (if they have one.)
Example:
I intend to use this in a SQL stored procedure. I can work with different types of output if that's easier.
I'm mostly interested in dimensions
Any guidance would be appreciated.
To get all of this extended metadate you could use the function below.
You can give it the path to a single file, or the path to a folder where the files are.
function Get-MetaData {
[CmdletBinding()]
[OutputType([Psobject[]])]
Param (
# Path can be the path to a folder or the full path and filename of a single file
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path,
# Pattern is unused if Path is pointing to a single file
[Alias('Filter')]
[string]$Pattern = '*.*',
[Alias('Indices')]
[int[]]$Properties = 1..500,
# Recurse is unused if Path is pointing to a single file
[switch]$Recurse,
[switch]$IncludeEmptyProperties
)
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if (!$item) { Write-Error "$Path could not be found."; return }
if (!$item.PSIsContainer) {
# it's a file
$files = #($item)
$Path = $item.DirectoryName
}
else {
# it's a folder
$files = Get-ChildItem -Path $Path -Filter $Pattern -File -Recurse:$Recurse
}
$shell = New-Object -ComObject "Shell.Application"
$objDir = $shell.NameSpace($Path)
foreach($file in $files) {
$objFile = $objDir.ParseName($file.Name)
$mediaFile = $objDir.Items()
foreach($index in $Properties) {
$name = $objDir.GetDetailsOf($mediaFile, $index)
if (![string]::IsNullOrWhiteSpace($name)) {
$value = $objDir.GetDetailsOf($objFile, $index)
if (![string]::IsNullOrWhiteSpace($value) -or $IncludeEmptyProperties) {
[PsCustomObject]#{
Path = $file.FullName
Index = $index
Property = $name
Value = $value
}
}
}
}
}
# clean-up Com objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objFile)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objDir)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
You can of course play around with the different parameters the function can take like -Pattern '*.mp4' to only list properties for mp4 files or add switch -IncludeEmptyProperties to also list properties that exist for that file type, but have no value for the specified file.
With parameter Properties you can give the function an array of int32 values of the property indices to return. If you leave that open, the function tries to get all properties from index 1 to index 500 (if available).
Most of the interesting property indices can be found at:
audio/video files: 0,1,2,3,4,5,9,11,12,13,14,15,16,17,18,19,20,21,22,26,27,28,36,164,165,194,213,220,223,237,243
font files:
0,1,2,3,4,5,20,21,25,33,34,164,165,166,196,310
image files:
0,1,2,3,4,5,9,11,31,164,165,174,175,176,177,178,194,196
Use it like this:
$result = Get-MetaData -Path '<pathToTheFile_OR_pathToTheFolder>'
# output to GridView
$result | Out-GridView
# output to CSV file
$result | Export-Csv -Path '<pathToTheOutput.csv>' -NoTypeInformation
Here's a simplified version similar to Theo's. It will accept file/folder paths or objects via pipeline or as parameter.
Function Get-FileMetaData {
[cmdletbinding()]
Param
(
[parameter(valuefrompipeline,ValueFromPipelineByPropertyName,Position=1,Mandatory)]
$InputObject
)
begin
{
$shell = New-Object -ComObject Shell.Application
}
process
{
foreach($object in $InputObject)
{
if($object -is [string])
{
try
{
$object = Get-Item $object -ErrorAction Stop
}
catch
{
Write-Warning "Error while processing $object : $($_.exception.message)"
break
}
}
try
{
Test-Path $object -ErrorAction Stop
}
catch
{
Write-Warning "Error while processing $($object.fullname) : $($_.exception.message)"
break
}
switch ($object)
{
{$_ -is [System.IO.DirectoryInfo]}{
write-host Processing folder $object.FullName -ForegroundColor Cyan
$currentfolder = $shell.namespace($object.FullName)
$items = $currentfolder.items()
}
{$_ -is [System.IO.FileInfo]}{
write-host Processing file $object.FullName -ForegroundColor Cyan
$parent = Split-Path $object
$currentfolder = $shell.namespace($parent)
$items = $currentfolder.ParseName((Split-Path $object -Leaf))
}
}
try
{
foreach($item in $items)
{
0..512 | ForEach-Object -Begin {$ht = [ordered]#{}}{
if($value = $currentfolder.GetDetailsOf($item,$_))
{
if($propname = $currentfolder.GetDetailsOf($null,$_))
{
$ht.Add($propname,$value)
}
}
} -End {[PSCustomObject]$ht}
}
}
catch
{
Write-Warning "Error while processing $($item.fullname) : $($_.exception.message)"
}
}
}
end
{
$shell = $null
}
}

PowerShell script with looping can not work after encryption

I have powershell script with looping. But After I encrypt the script. The looping is always running and never stop.
Anyone can help please. THank you
Function 101_Pr
{
Write-Host " 101_Pr"
}
Function CleanUp
{
Write-Host "CleanUp"
}
Function Image
{
$Stoploop = $false
[int]$Retrycount = "0"
do {
try {
$Get = "123AB"
$connectionString = "Server=$IP;uid=$UID;pwd=$Pswd;Database=$Database;Integrated Security=False;"
Write-Host $connectionString
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "select Number='$Get'"
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
[array] $DB = $table.Number
Write-Host "Result: $DB"
if($null -ne $DB)
{
$Stoploop = $true
101_Pr
break
}
}
catch {
if ($Retrycount -gt 2)
{
Write-Host "Could not get after 3 retrys."
$Stoploop = $true
CleanUp
break
}
else{
Write-Host "Retry"
Start-Sleep -s 1
$Retrycount = $Retrycount + 1
}
}
}
While ($Stoploop -eq $false)
}
Image
The output is always print this Write-Host $connectionString
I use this script for encryption
ps2exe.ps1
anyone can help really appreciated. THank you

Powershell run multiple SQL queries

I am trying to run multiple SQL queries and get the result in some txt/csv file, but I am getting an error that I am not able to fix. Any advice?
$dbServer = "dbserver"
$extractFile = "C:\test\" + $timer + ".csv"
$Database = "b
$User = "Admin"
$Pass = "psswd"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$dbServer;Database=$db;uid=$User;password=$Pass;"
$SQLConnection.Open()
$SQLCommand = $SQLConnection.CreateCommand()
$SQLCommand.CommandText =
"select count(*) 'Nombre de Address mail' FROM dbo.UsersParticipations"
"select count(*) 'Nombre de Transactions' FROM dbo.Transactions;"
$readAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$readSet = New-Object System.Data.DataSet
$readAdapter.SelectCommand = $SQLCommand
$readAdapter.Fill($readSet) |out-null
$SQLConnection.Close()
Foreach ($row in $readSet.Tables[0].rows) {
Write-Output "Adress"
Write-Output "$($row.size) $($row.job)"
}
Foreach ($row in $readSet.Tables[1].rows) {
Write-Output "Transactions"
Write-Output "$($row.free) "
}
This is the error I get:
Exception calling "Fill" with "1" argument(s): "Invalid object name 'dbo.UsersParticipations'."
At C:\Efiester\test2.ps1:18 char:1
+ $readAdapter.Fill($readSet) |out-null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
this bit should be:
...
$SQLCommand.CommandText =
"select count(*) 'Nombre de Address mail' FROM dbo.UsersParticipations; select count(*) 'Nombre de Transactions' FROM dbo.Transactions"
...
not sure if that will sort all the errors but it's a start