Category Archives: PowerShell

Configure schedule task that runs every 5 minutes for N years


Hi all,

Here is the sample PowerShell script to configure schedule task that runs every 5 minutes for 3 years.

You can change the years , why did I not mentioned infinite time is because of some limitation that I had explained in the other article.

https://sqlblogging.com/2017/08/16/fixethe-task-xml-contains-a-value-which-is-incorrectly-formatted-or-out-of-range-durationp99999999dt23h59m59s/

Script:

$mycredentials = Get-Credential

Invoke-Command -ComputerName “Server1”,”Server2” -Credential $mycredentials -ScriptBlock {

$dt= ([DateTime]::Now)

$timespan = $dt.AddYears(3) -$dt;

$Action = New-ScheduledTaskAction -Execute ‘powershell.exe’ -Argument ‘-command “D:\PS_Jobs\PS_Job1.ps1” -ExecutionPolicy RemoteSigned -NoProfile’

$Trigger = New-ScheduledTaskTrigger -Once -At 9am -RandomDelay (New-TimeSpan -Minutes 30) -RepetitionDuration $timespan -RepetitionInterval (New-TimeSpan -Minutes 60)

$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)

$Task | Register-ScheduledTask -TaskName ‘Job1 Task’

}

Regards,

Chaitanya

Advertisements

Convert datetime::Now value to specific format for comparison-Power Shell


Hi All,

How to convert datetime value to specific format for comparison

For get-date cmdlet, we have property called format , using that I can convert the date into specific format.

But for [datetime]::Now as it is c# static class, for that to convert the date time into specific format, you could use the toString method like below

$date = get-date -Format "yyyyMMddhhmm" – input value

$date2=([datetime]::Now).ToString("yyyyMMddhhmm") -comparing against time

if ( $date -eq $date2)

{

"yes"

}

else

{

"no"

}

Regards,

Chaitanya

Check if the Server is Clustered or not


Hi All,

Below is the simple PowerShell snippet, which could check if the server is cluster or not

$ServerName=’Server1’

$sObj = Get-WmiObject -Class Win32_SystemServices -ComputerName $ServerName

if ($sObj | select PartComponent | where {$_ -like "*ClusSvc*"})

{

Write-Output "$ServerName is Clustered"

}

else

{

Write-Output "$server is Not clustered"

}

Regards,

Chaitanya

Finding Services dependency


If you Want to check Services dependency using PowerShell, here is little snippet.

Get-Service -ComputerName localhost |

where Status -EQ Running |

Select-Object -Property Name,

@{Name = ‘RequiredServices’ ; Expression = { $_.RequiredServices -join ‘,’}},

CanPauseAndContinue,

CanShutdown,

CanStop,

DisplayName,

@{Name=’DependentServices’;Expression = { $_.DependentServices -join ‘,’}},

MachineName,

ServiceName,

@{Name=’ServicesDependedOn’;Expression = { $_.ServicesDependedOn -join ‘,’}},

ServiceHandle,

Status,

ServiceType,

Site,

Container

Regards,

Chaitanya

Finding Method Definitions


I am creating new variable of type string

$str=[string]"Hi, How are you"

You can get the methods information of this variable using $str|gm

If you want to check the methods only use the below code

$str |gm -membertype method

If you want to see the method definitions, you can use the

Code like this

$str.StartsWith

OverloadDefinitions

Check Account permissions Existence across multiple file shares


#Check file share permissions using multiple accounts

$Fileshares = "C:\Chaitanya\work","C:\Chaitanya\Work2"

$Accounts = "NT AUTHORITY\Authenticated Users","chaitanya"

$AccessArr = @();

foreach ( $account in $accounts)

{

foreach ($share in $Fileshares)

{

$accessObj = Get-ACL $share | Select-Object `

@{n=’Path’;e={ (Get-Item $_.PSPath).FullName }}, Owner `

-Expand Access|?{$_.IdentityReference -contains $account}

if (-not($accessObj))

{

$AccessArr += [pscustomobject]@{Share=$share;Account=$account}

}

else

{

}

}

}

$AccessArr|Out-GridView -Title "MissingAccounts"

Regards,

Chaitanya

Check Disk availability for Storage pool


If you want to check the any disks available to add in the storage pool for servers, you can use the below command.

Get-PhysicalDisk -CanPool $True

Below is the information regarding the storage pool.

The storage pool is a set of disks on which the Data Protection Manager (DPM) server stores replicas, shadow copies, and transfer logs. Before you can start protecting data, you must add at least one disk to the storage pool. Disks added to the storage pool should be empty.

Regards,

Chaitanya

Create folders if not exists


To Create file share folders if does not exists, below is the PowerShell code.

Test-path is PowerShell command let checks the existence of folder paths and using new-item command let you can create folders.

Code:

$sharearray ="fileshare1","fileshare2"

foreach ( $share in $sharearray)

{

if (-not (Test-Path -Path $share))

{

Write-host "$share not exists ,Creating it"

new-item -Path $share -ItemType Directory -Force

}

}

Regards,

Chaitanya

Check Command Execution History


Want to check the history of your executed commands in PowerShell session.

Use get-history command let.

You will get the ID from the result. If you want to execute the command based on the ID, you can use the invoke-history id

Regards,

Chaitanya

Importing BizTalk Application bindings


Hi All,

 

This is the  continuation for the below blog post.

 

https://sqlblogging.com/2016/11/19/export-application-bindings-from-the-any-biztalk-server-by-providing-the-application-names/

 

once you exported the bindings , you can copy the entire folder and try to run the below script.

In the same script folder.

 

If any error occurs , it halts the processing.

 

 

#region WriteLog function

 

function WriteLog($LogMessage, $LogDateTime, $LogType)

{

 

write-host

“$LogType, [“+ $LogDateTime +”]: “+ $LogMessage | Add-Content -Path $MainLogFilepath

}

 

 

$BiztalkSrvInfo = @{

‘MgmtDbname’=Get-CimInstance MSBTS_GroupSetting -namespace root\MicrosoftBizTalkServer|select MgmtDbName

‘MgmtDbServerName’=Get-CimInstance MSBTS_GroupSetting -namespace root\MicrosoftBizTalkServer|select MgmtDbServerName

}

 

$Obj = New-Object -TypeName PSObject -Property $BiztalkSrvInfo

 

 

$MgmtDbServerName = $Obj.MgmtDbServerName.MgmtDbServerName

$MgmtDbname = $Obj.MgmtDbname.MgmtDbName

 

 

$scriptpath = $MyInvocation.MyCommand.Path

$dir = Split-Path $scriptpath

 

 

$inputFiles = “$dir\Bindings\”

 

$LogFilepath = “$Dir\Logs\”

 

if(!(Test-Path $LogFilepath))

{

New-Item -ItemType directory -Path $LogFilepath

}

 

$LogFile = “$LogFilepath\ImportLogfile.txt”

 

TRY

{

 

Get-ChildItem -path $inputFiles -Filter *.xml -Recurse |ForEach-Object -Process{

 

$Actfilepath = $_.FullName

$filename = $_.BaseName

 

$LogDateTime = get-date

 

Write-host “***Starting  Importing of Bindings for Application : $filename in” + $inputFiles “folder” -ForegroundColor Cyan

 

$run = “BTSTask.exe ImportBindings /Source:$Actfilepath /ApplicationName:$filename /Server:$MgmtDbServerName /Database:$MgmtDbname”

 

Invoke-Expression $run  | Add-Content $LogFile

 

if ($LASTEXITCODE -eq 1)

 

{

$LogMessage = throw $_.Exception.Message

 

}

 

$LogDateTime = get-date

 

Write-host “Finished Extracting of Bindings for Application : $filename in ” + $inputFiles “folder” -ForegroundColor green

 

 

}

 

}

 

CATCH

{

 

$_.Exception.Message|Add-Content $LogFile

 

}

 

Let  me know if you have any questions.

 

Regards,

Chaitanya

 

%d bloggers like this: