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()
}
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
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
}
}
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
Trying to check if AD group exists or not using below script :
$Path = "LDAP://dc=cmc,dc=com"
$object = "CMC\QTKS-DEP-Admin-Temp"
$type = "Group"
$search = [System.DirectoryServices.DirectorySearcher]$Path
$search.Filter = "(&(name=$object)(objectCategory=$type))"
$Result = $search.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}
I know something wrong with the LDAP connection string or variables declarations. Or something else. Can someone please correct. The result always shows as "Group does not exist" even if it exists.
Got it finally :
$Search = New-Object DirectoryServices.DirectorySearcher
$Search.Filter = '(&(objectCategory=Group)(anr=CMC\QTKS-DEP-Admin-Temp))'
$Search.SearchRoot = 'LDAP://DC=cmc,DC=com'
$Result = $Searcher.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}