# Connecting to Azure Parameters
$tenantID = "mytenantid"
$ClientId = "myapplicationid"
$ClientSecret = "myclientsecret"
# Create a hashtable for the body, the data needed for the token request
# The variables used are explained above
$Body = @{
'tenant' = $TenantId
'client_id' = $ClientId
'scope' = 'https://graph.microsoft.com/.default'
'client_secret' = $ClientSecret
'grant_type' = 'client_credentials'
}
# Assemble a hashtable for splatting parameters, for readability
# The tenant id is used in the uri of the request as well as the body
$Params = @{
'Uri' = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
'Method' = 'Post'
'Body' = $Body
'ContentType' = 'application/x-www-form-urlencoded'
}
$AuthResponse = Invoke-RestMethod @Params
$Headers = @{
'Authorization' = "Bearer $($AuthResponse.access_token)"
}
#$url = "https://graph.microsoft.com/v1.0/users/?$select=displayName,givenName,postalCode,UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName"
$url = 'https://graph.microsoft.com/v1.0/users/?$select=UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName'
$userPurpose = @()
$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $url
$nexturl = $UserData.'@odata.nextLink'
$userPurpose+= $UserData
$count = 0
while($nexturl -ne "")
{
$nexturl = $UserData.'@odata.nextLink'
Write-host $nexturl -ForegroundColor Yellow
if(!$nexturl) {break;}
$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $nexturl
$userPurpose+= $UserData
$count++
}
Write-host "Count of url: $count" -ForegroundColor Yellow
$userPurpose.count
$Users = @()
Foreach($userdata in $userPurpose)
{
$Users+=$userdata.value
}
$users | Export-csv -Path c:\temp\Azureusers1.csv -NoClobber -NoTypeInformation -Append
Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts
Tuesday, September 6, 2022
Powershellscript to get details of Azure users who have synced to Azure with diferent upn
Thursday, December 2, 2021
Resize Azure VMs using Az powershell.
Script to resize Azure VM's from any subscription. If a VM is stopped it will resize it. If it is running it will stop the VM and resize it.
#$NewSize = "Standard_D8s_v3"
$NewSize = "Standard_E4s_v3"
#$NewSize = "Standard_DS1_v2"
Function Out($message) {
$message = $(Get-Date -Format "MM/dd/yyyyTHH:mm:ss") + ":" + $message
Write-Output $message}
Out "Vm resize script starting...."
function Connect($tenantid)
{
$username = "username@contoso.com"
$password = ConvertTo-SecureString -AsPlainText -Force "password"
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential($username, $password)
Connect-AzAccount -Credential $pscredential -Tenant $tenantId -EnvironmentName AzureUSGovernment
}
Function Resize-VM($VM)
{
Out "Resizing $($vm.name) in $($vm.ResourceGroupName) from $($VM.HardwareProfile.VmSize) to $NewSize" ## Change here
$VM.HardwareProfile.VmSize = $NewSize
Update-AzVM -ResourceGroupName $vm.ResourceGroupName -VM $VM
}
Function CheckVM($VM)
{
if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM running")
{
Out "$($VM.Name) is resized and Started"
}
else {
Out "$($VM.Name) is resized and not started"
}
}
Connect "put your tenant id here"
$VMList = @("VM1","VM2" ## comma separated list of VM's
)
$Allsubs = Get-AzSubscription
foreach($sub in $Allsubs)
{
Select-AzSubscription -SubscriptionId $sub.SubscriptionId | Out-Null
$VMS = Get-AzVM -Status
foreach($vm in $VMS)
{
foreach($v in $VMList)
{
if($v -eq $Vm.name)
{
if($vm.PowerState -notmatch "VM running") ## If the VM is switched off.We resize but dont start it.
{
#Resize the vm
Out "VM $($VM.Name) is already powered off.Resizing...."
Resize-VM $VM
}
Else # If the VM is turned on. Turn it off, resize and start it.
{
Out "VM is powered on. So Stopping $($VM.Name)"
Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
Start-Sleep -Seconds 120
#Get VM Status
if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM deallocated")
{
Out "$($VM.Name) is now off. Resizing...."
Resize-VM $VM
Start-AzVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName
Start-Sleep -Seconds 300
CheckVM $VM
}
}
}
}
}
}
Monday, January 4, 2021
Get SCOMGroup members using powershell.
SCOM group members using powershell
Get-SCOMGroup | ?{$_.displayname -match "advisor"} | Get-SCOMmonitoringobject
Tuesday, February 4, 2020
URL Certificate expiration check using powershell
Using powershell to check for certificate expiration for a url.
Create a folder called C:\URLCertexpiry
add a text file in it named URLsToCheckforCertExpiry.txt. Add the url's you want to check for certificate expiration in this text file.
$ErrorActionPreference = "Stop"
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject "Starting Script at $(get-date)" -Append
try {Remove-Item -path C:\URLCertExpiry\URLCERTExpiryReport.txt -Force -ErrorAction Continue} catch {$_.exception}
$UrlList = @()
$Data = @()
$ExpiringCollection = @()
$ExpiredCollection = @()
$username = "username"
$password = "Password" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
$UrlList = GC "C:\URLCertExpiry\URLsToCheckforCertExpiry.txt"
$TLS12urls = ("https://www.google.com",
"https://www.bing.com"
)
foreach ($url in $UrlList )
{
try{
$message = "Working on $url"
Write-host $message -ForegroundColor Yellow
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
$minimumCertAgeDays = 30
$timeoutMilliseconds = 20000
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
if($TLS12urls -contains $url)
{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}
else
{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
}
Write-Host Checking $url -f Green
$req = [Net.WebRequest]::Create($url)
$req.Credentials = $cred
$req.Timeout = $timeoutMilliseconds
try {
$response = $req.GetResponse()
$response.Close()
[datetime]$expiration = $req.ServicePoint.Certificate.GetExpirationDateString()
[int]$certExpiresIn = ($expiration - $(get-date)).Days
if($certExpiresIn -gt $minimumCertAgeDays)
{
$expirationState = "NotExpiring"
}
elseif($certExpiresIn -lt $minimumCertAgeDays -and $certExpiresIn -gt 0)
{
$expirationState = "Expiring"
$ExpiringCerts= $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
$ExpiringCollection+=$ExpiringCerts
}
elseif($certExpiresIn -lt $minimumCertAgeDays -and $certExpiresIn -lt 0)
{
$expirationState = "Expired"
$ExpiredCerts= $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
$ExpiredCollection+=$ExpiredCerts
}
$Data1 = $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
Write-Host $data1 -ForegroundColor Yellow
$Data+=$Data1
}
catch {
$message = "Exception while checking URL $url`: $_ "
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
continue
}
}
catch {
$Message = $_.exception.Message
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $(get-date) -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
Continue
}
}
Write-Host $data -ForegroundColor Yellow
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $Data -Append
$Data
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject "Email Data" -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiringCollection -Append
$ExpiringCollection
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiredCollection -Append
$ExpiredCollection
$ExpiringCollectionArray=$null
$ExpiredCollectionArray=$null
$ExpiringCollection | %{$ExpiringCollectionArray+=$_}
$ExpiredCollection | %{$ExpiredCollectionArray+=$_}
$ExpiringCollection | Select @{label='Expiring Certificates:';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Expiring Certificates:' -As List | % { $_ -replace '<td>Expiring Certificates::</td>', ''} | % { $_ -replace '<tr><td><hr></td></tr>', '' } | Out-File C:\URLCertExpiry\report.html -append
$ExpiredCollection | Select @{label='Expired Certificates:';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Expired Certificates:' -As List| % { $_ -replace '<td>Expired Certificates::</td>', '' } | % { $_ -replace '<tr><td><hr></td></tr>', '' } | Out-File C:\URLCertExpiry\report.html -append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject "Collection Values" -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiredCollectionArray -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiringCollectionArray -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject "Ending Script at $(get-date)" -Append
$Data
$ExpiringCollectionArray
$ExpiredCollectionArray
Create a folder called C:\URLCertexpiry
add a text file in it named URLsToCheckforCertExpiry.txt. Add the url's you want to check for certificate expiration in this text file.
$ErrorActionPreference = "Stop"
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject "Starting Script at $(get-date)" -Append
try {Remove-Item -path C:\URLCertExpiry\URLCERTExpiryReport.txt -Force -ErrorAction Continue} catch {$_.exception}
$UrlList = @()
$Data = @()
$ExpiringCollection = @()
$ExpiredCollection = @()
$username = "username"
$password = "Password" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
$UrlList = GC "C:\URLCertExpiry\URLsToCheckforCertExpiry.txt"
$TLS12urls = ("https://www.google.com",
"https://www.bing.com"
)
foreach ($url in $UrlList )
{
try{
$message = "Working on $url"
Write-host $message -ForegroundColor Yellow
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
$minimumCertAgeDays = 30
$timeoutMilliseconds = 20000
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
if($TLS12urls -contains $url)
{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}
else
{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
}
Write-Host Checking $url -f Green
$req = [Net.WebRequest]::Create($url)
$req.Credentials = $cred
$req.Timeout = $timeoutMilliseconds
try {
$response = $req.GetResponse()
$response.Close()
[datetime]$expiration = $req.ServicePoint.Certificate.GetExpirationDateString()
[int]$certExpiresIn = ($expiration - $(get-date)).Days
if($certExpiresIn -gt $minimumCertAgeDays)
{
$expirationState = "NotExpiring"
}
elseif($certExpiresIn -lt $minimumCertAgeDays -and $certExpiresIn -gt 0)
{
$expirationState = "Expiring"
$ExpiringCerts= $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
$ExpiringCollection+=$ExpiringCerts
}
elseif($certExpiresIn -lt $minimumCertAgeDays -and $certExpiresIn -lt 0)
{
$expirationState = "Expired"
$ExpiredCerts= $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
$ExpiredCollection+=$ExpiredCerts
}
$Data1 = $url + " " + $expirationState + " Validity "+ $certExpiresIn +" " + "days"
Write-Host $data1 -ForegroundColor Yellow
$Data+=$Data1
}
catch {
$message = "Exception while checking URL $url`: $_ "
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
continue
}
}
catch {
$Message = $_.exception.Message
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $(get-date) -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject $message -Append
Continue
}
}
Write-Host $data -ForegroundColor Yellow
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $Data -Append
$Data
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject "Email Data" -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiringCollection -Append
$ExpiringCollection
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiredCollection -Append
$ExpiredCollection
$ExpiringCollectionArray=$null
$ExpiredCollectionArray=$null
$ExpiringCollection | %{$ExpiringCollectionArray+=$_}
$ExpiredCollection | %{$ExpiredCollectionArray+=$_}
$ExpiringCollection | Select @{label='Expiring Certificates:';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Expiring Certificates:' -As List | % { $_ -replace '<td>Expiring Certificates::</td>', ''} | % { $_ -replace '<tr><td><hr></td></tr>', '' } | Out-File C:\URLCertExpiry\report.html -append
$ExpiredCollection | Select @{label='Expired Certificates:';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Expired Certificates:' -As List| % { $_ -replace '<td>Expired Certificates::</td>', '' } | % { $_ -replace '<tr><td><hr></td></tr>', '' } | Out-File C:\URLCertExpiry\report.html -append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject "Collection Values" -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiredCollectionArray -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryReport.txt -InputObject $ExpiringCollectionArray -Append
Out-file -FilePath C:\URLCertExpiry\URLCERTExpiryLog.txt -InputObject "Ending Script at $(get-date)" -Append
$Data
$ExpiringCollectionArray
$ExpiredCollectionArray
Labels:
certificate,
certificate expiry,
expiration,
expires,
Powershell,
url,
url certificate
Wednesday, January 16, 2019
Adding a disk to Azure vm using powershell
Powershell Script to add a disk to Azure RM virtual machine.
$Credentials = Get-Credential
param([string] $VirtualMachineName,$DiskSize)
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials
$Managed_Prod_Sub = Get-AzureRMSubscription -SubscriptionId "Your subscription id"
Select-AzureRMSubscription -SubscriptionId $Managed_Prod_Sub.SubscriptionId ##
$Managed_ProdVMS = Get-AzureRMVM
if($VM.name -eq $VirtualMachineName)
{
Write-host "Working on $($VM.name)" -ForegroundColor Yellow
$rgName = $VM.ResourceGroupName
$vmName = $VM.Name
$location = $VM.location
$storageType = 'Premium_LRS'
$dataDiskName = $vmName + '_datadisk1'
$diskConfig = New-AzureRmDiskConfig -AccountType PremiumLRS -Location $location -CreateOption Empty -DiskSizeGB $DiskSize -OsType Windows
$dataDisk1 = New-AzureRmDisk -DiskName $dataDiskName -Disk $diskConfig -ResourceGroupName $rgName
$vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
$vm = Add-AzureRmVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk1.Id -Lun 1
Update-AzureRmVM -VM $vm -ResourceGroupName $rgName
}
$Credentials = Get-Credential
param([string] $VirtualMachineName,$DiskSize)
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials
$Managed_Prod_Sub = Get-AzureRMSubscription -SubscriptionId "Your subscription id"
Select-AzureRMSubscription -SubscriptionId $Managed_Prod_Sub.SubscriptionId ##
$Managed_ProdVMS = Get-AzureRMVM
if($VM.name -eq $VirtualMachineName)
{
Write-host "Working on $($VM.name)" -ForegroundColor Yellow
$rgName = $VM.ResourceGroupName
$vmName = $VM.Name
$location = $VM.location
$storageType = 'Premium_LRS'
$dataDiskName = $vmName + '_datadisk1'
$diskConfig = New-AzureRmDiskConfig -AccountType PremiumLRS -Location $location -CreateOption Empty -DiskSizeGB $DiskSize -OsType Windows
$dataDisk1 = New-AzureRmDisk -DiskName $dataDiskName -Disk $diskConfig -ResourceGroupName $rgName
$vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
$vm = Add-AzureRmVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk1.Id -Lun 1
Update-AzureRmVM -VM $vm -ResourceGroupName $rgName
}
Wednesday, January 9, 2019
Good trick for using Try Catch in Powershell
try{
Something......
}
Catch{
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
Out-File -FilePath 'C:\Temp\error.txt' -inputobject ($formatstring -f $fields) -Append
}
Something......
}
Catch{
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
Out-File -FilePath 'C:\Temp\error.txt' -inputobject ($formatstring -f $fields) -Append
}
Tuesday, December 11, 2018
Get Azure VM status and ip address
Powershell script to get the list of virtual machines in Azure Gov with ip address.
$username = "parag.waghmare@contoso.com"
$Password = "Password"
$Credentials = New-Object System.Management.Automation.PSCredential ($username, $password)
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials
$subs = Get-AzureRmSubscription
foreach ($Sub in $Subs) {
$SelectSub = Select-AzureRmSubscription -SubscriptionName $Sub.Name
$nics = get-azurermnetworkinterface | where VirtualMachine -NE $null #skip Nics with no VM
$VMs = Get-AzureRMVM -Status
foreach($nic in $nics)
{
$vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
$prv = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
$alloc = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
$data = $Sub.Name + "`t "+ $vm.Name + "`t "+ $prv + "`t "+ $alloc + "`t " + $Vm.powerstate
Write-Host $data
}
}
Friday, October 27, 2017
Powershell script to ping multiple servers at the same time.
Powershell script to ping multiple servers at the same time.
Warning: This script is resource intensive as it starts a powershell instance for each of the jobs. If you have multiple servers then it will take all up all the memory until it finishes all the jobs.
$scriptDir = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$serverlist = GC "$scriptdir\list.txt"
$outputpath = "$scriptdir\pingcheck.txt"
foreach($server in $serverlist)
{
Start-job -scriptblock {
param([string]$computer,$outputpath)
$out = Test-NetConnection -ComputerName $computer
if($out.pingsucceeded -eq "True")
{
$output = "$computer" + "`t" + $out.remoteaddress + "`t" + " is pinging"
}
Else
{
$output = "$computer" + "`t" + $out.remoteaddress + "`t" + " is not pinging"
Out-File -InputObject $output -FilePath $outputpath -Append
}
Sleep -Seconds 10
return $output
} -ArgumentList @($server,$outputpath)
}
$A = Get-Job | Wait-Job | Receive-Job
Write-host "Writing A" -ForegroundColor Yellow
$A
Out-File -InputObject $A -FilePath $outputpath -Append
Get-job | Remove-Job
Warning: This script is resource intensive as it starts a powershell instance for each of the jobs. If you have multiple servers then it will take all up all the memory until it finishes all the jobs.
$scriptDir = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$serverlist = GC "$scriptdir\list.txt"
$outputpath = "$scriptdir\pingcheck.txt"
foreach($server in $serverlist)
{
Start-job -scriptblock {
param([string]$computer,$outputpath)
$out = Test-NetConnection -ComputerName $computer
if($out.pingsucceeded -eq "True")
{
$output = "$computer" + "`t" + $out.remoteaddress + "`t" + " is pinging"
}
Else
{
$output = "$computer" + "`t" + $out.remoteaddress + "`t" + " is not pinging"
Out-File -InputObject $output -FilePath $outputpath -Append
}
Sleep -Seconds 10
return $output
} -ArgumentList @($server,$outputpath)
}
$A = Get-Job | Wait-Job | Receive-Job
Write-host "Writing A" -ForegroundColor Yellow
$A
Out-File -InputObject $A -FilePath $outputpath -Append
Get-job | Remove-Job
Labels:
job,
multiple,
ping,
Powershell,
same time,
script,
server,
start-job,
Test-NetConnection
Thursday, August 3, 2017
Regular expression checker powershell
Simple powershell script to check your regular expression strings.
The reference for creating a regular expression is here
http://www.regular-expressions.info/quickstart.html
PS C:\WINDOWS\system32> $String = 'This is my string'
$expression = [regex]"my"
$expression.Match($String)
Groups : {my}
Success : True
Captures : {my}
Index : 8
Length : 2
Value : my
PS C:\WINDOWS\system32> $String = 'this is my string'
$expression = [regex]"[A-Za-z]"
$expression.Match($String)
Groups : {t}
Success : True
Captures : {t}
Index : 0
Length : 1
Value : t
PS C:\WINDOWS\system32> $String = 'this is my string'
$expression = [regex]"[A-Z]"
$expression.Match($String)
Groups : {}
Success : False
Captures : {}
Index : 0
Length : 0
Value :
The reference for creating a regular expression is here
http://www.regular-expressions.info/quickstart.html
PS C:\WINDOWS\system32> $String = 'This is my string'
$expression = [regex]"my"
$expression.Match($String)
Groups : {my}
Success : True
Captures : {my}
Index : 8
Length : 2
Value : my
PS C:\WINDOWS\system32> $String = 'this is my string'
$expression = [regex]"[A-Za-z]"
$expression.Match($String)
Groups : {t}
Success : True
Captures : {t}
Index : 0
Length : 1
Value : t
PS C:\WINDOWS\system32> $String = 'this is my string'
$expression = [regex]"[A-Z]"
$expression.Match($String)
Groups : {}
Success : False
Captures : {}
Index : 0
Length : 0
Value :
Wednesday, June 7, 2017
How to make a parameter mandatory in powershell.
How to make a parameter mandatory in powershell.
Enter this at the start of your script.
param(
[Parameter(Mandatory=$true)]
[string]$Server
)
A very good explanation and additional ways to do it is here.
https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/22/use-powershell-to-make-mandatory-parameters/
Enter this at the start of your script.
param(
[Parameter(Mandatory=$true)]
[string]$Server
)
A very good explanation and additional ways to do it is here.
https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/22/use-powershell-to-make-mandatory-parameters/
powershell powergui download link
Powergui is a very good powershell editor. I particularly like the speed of execution compared to windows powershell ise.
Please refer to this link for powergui and additinal downloads.
https://dmitrysotnikov.wordpress.com/2015/01/30/download-links-for-powergui-and-qad-cmdlets/
In case the page does not open the direct download link is posted below.
http://community-downloads.quest.com/powergui/Release/3.8/PowerGUI.3.8.0.129.msi
Please refer to this link for powergui and additinal downloads.
https://dmitrysotnikov.wordpress.com/2015/01/30/download-links-for-powergui-and-qad-cmdlets/
In case the page does not open the direct download link is posted below.
http://community-downloads.quest.com/powergui/Release/3.8/PowerGUI.3.8.0.129.msi
Thursday, April 27, 2017
Putting a SCOM agent (non clustered) in maintenance mode using powershell
## Putting scom agent in maintenance mode. This does not yet put agents which are part ## of a cluster in maintenance mode.
$rootMS = "rootms"
$agentName = "agentname"
$minutes= 10
$comment= "Planned Reboot"
$reason="PlannedOther"
$startTime = [System.DateTime]::Now
$endTime = $startTime.AddMinutes($minutes)
Add-PSSnapin "Microsoft.EnterpriseManagement.OperationsManager.Client" -ErrorVariable errSnapin;
New-ManagementGroupConnection -ConnectionString:$rootMS
set-location "OperationsManagerMonitoring::";
$agent = Get-Agent | ?{$_.computername -match $agentName}
$agent
New-MaintenanceWindow -StartTime $startTime -EndTime $endTime -MonitoringObject $agent.HostComputer -Reason PlannedOther -Comment $Comment
$rootMS = "rootms"
$agentName = "agentname"
$minutes= 10
$comment= "Planned Reboot"
$reason="PlannedOther"
$startTime = [System.DateTime]::Now
$endTime = $startTime.AddMinutes($minutes)
Add-PSSnapin "Microsoft.EnterpriseManagement.OperationsManager.Client" -ErrorVariable errSnapin;
New-ManagementGroupConnection -ConnectionString:$rootMS
set-location "OperationsManagerMonitoring::";
$agent = Get-Agent | ?{$_.computername -match $agentName}
$agent
New-MaintenanceWindow -StartTime $startTime -EndTime $endTime -MonitoringObject $agent.HostComputer -Reason PlannedOther -Comment $Comment
Labels:
2012 R2,
agent,
Agents,
Maintenance mode,
MaintenanceMode,
Powershell
Tuesday, April 25, 2017
How to test if a port is open using powershell
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.connect('servername or ip address', portnumber)
Or you can use this single line of code
(New-Object System.Net.Sockets.TcpClient).Connect('servername or ip address', portnumber)
There is also an in built powershell cmdlet that lets you test a port connection which only works with powershell 4.0
Test-NetConnection -Port portnumber -Computername 'Servername or ip address'
The first commands are much faster compared to the second one but does not give you any output.
The powershell cmdlet does give you a good output that you can use in another script but is much slower.
Wednesday, April 19, 2017
Adding a powershell script in SCOM as a recovery task.
Adding a powershell script in SCOM as a recovery task.
Open the properties of the monitor.
Add the recovery task
Export the management pack and open it in any text editor. You have to change the write action to powershell write action. Locate the enrty for write action and replace it with a powershell write action ID.
Replace
TypeID="Windows!Microsoft.Windows.ScriptWriteAction"
with
TypeID="Windows!Microsoft.Windows.PowerShellWriteAction"
Remove the <Arguments /> section.
Increment the version and import the management pack.
Open the properties of the monitor.
Add the recovery task
Export the management pack and open it in any text editor. You have to change the write action to powershell write action. Locate the enrty for write action and replace it with a powershell write action ID.
Replace
TypeID="Windows!Microsoft.Windows.ScriptWriteAction"
with
TypeID="Windows!Microsoft.Windows.PowerShellWriteAction"
Remove the <Arguments /> section.
Increment the version and import the management pack.
Subscribe to:
Posts (Atom)