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 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
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"
}
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