0

WordPress Split Description\Tagline into Multiple Lines

Posted by paris on Feb 8, 2017 in Code

Add the Following Code to your Functions.php theme file ( under Appearance ) 

/*
 * Split Description\TagLine
 */
    function get_split_description() {
        $title = get_bloginfo( 'description', 'display' );;
        $lines = explode(' – ', $title);
        $output = false;
        $count = 0;
 
        foreach( $lines as $line ) {
            $count++;
            $output .= '<span class="line-'.$count.'">'.$line.'</span><br> ';
        }
 
        return $output;
    }

 

 

Change in your header.php file to use the following :

<p class="site-description"><?php echo get_split_description(); ?></p>
					<?php endif; ?

 

 

Then change your Tagline to line 1 – line 2 ( with a slash and space in between ) 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

VMware PowerCLi Powershell Script to get VMWare Tools out of Date and Virtual Machine Hardware Versions

Posted by paris on Jan 5, 2016 in Code
New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine -ValueFromExtensionProperty 'Config.tools.ToolsVersion' -Force
 
New-VIProperty -Name ToolsVersionStatus -ObjectType VirtualMachine -ValueFromExtensionProperty 'Guest.ToolsVersionStatus' -Force
 
Get-VM | Select Name, Version, ToolsVersion, ToolsVersionStatus | Export-Csv -NoTypeInformation -UseCulture -Path C:\VMHWandToolsInfo.csv
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

New User Powershell Script

Posted by paris on Sep 28, 2015 in Code

To copy 

################################## Import ActiveDirectory ##############################################
 
Import-Module ActiveDirectory
 
################################## Import Exchange snap-in #############################################
 
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
 
########################################################################################################
 
#Clear-host
 
# Gets all of the users info to be copied to the new account
#Checking the user to copy if it exist
	do {
$nameds = Read-Host "Copy From Username"
if (dsquery user -samid $nameds){"AD User Found"
}
 
elseif ($nameds = "null") {"AD User not Found"}
}
while ($nameds -eq "null")
 
#Checking if the new user exist
 
do {
 
$NewUserds = Read-Host "New Username"
 
While ( $NewUserds -eq "" ) { $NewUserds = Read-Host "New Username"}
$NewUser = $Newuserds
 
#check if AD user exist	
if (dsquery user -samid $NewUserds){"Ad User Exist"}
 
#check imanage user exist
$SQLServer = "imanagesqlserver" #use Server\Instance for named SQL instances! 
$SqlQuery = "SELECT sum(A+B) FROM (select COUNT(1) as A FROM [imanagedatabase].[MHGROUP].DOCUSERS where [USERID]='$NewUserds') a
CROSS JOIN (select COUNT(1) as B FROM [imanagedatabase2].[MHGROUP].DOCUSERS where [USERID]='$NewUserds') b"
 
 
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Integrated Security = True"
 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
 
$DataSet = New-Object System.Data.DataSet
[void]$SqlAdapter.Fill($DataSet)
 
$SqlConnection.Close()
 
$UserExist = $DataSet.Tables[0]| select -expand Column1
 
if ($UserExist -gt 0) {
$NewUserds -eq ""
"iManage User Found"
}
 
elseif ($NewUserds = "no") {"Validation OK"}
}
 
while ($Newuserds -ne "no")
 
 
# Gets all of the users info to be copied to the new account
 
$name = Get-AdUser -Identity $nameds -Properties *
 
$DN = $name.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
$NewUser = Read-Host "New Username"
$firstname = Read-Host "First Name"
$Lastname = Read-Host "Last Name"
$Extention = Read-Host "Users Extension"
$Password = Read-Host "New Password"
$SecurePassword = ConvertTo-SecureString $Password –asplaintext –force
$NewName = "$firstname $lastname"
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 
$newuserfinitial = $firstname.substring(0,1)
$pager = $name.Pager
$newusernumber= $pager.Substring(0,$pager.Length-3)+$Extention
$OldNotes = $name.info
 
#Remove Spaces for Make Email Alias Correct
$Lastnamens = $Lastname -replace '\s',''
 
# Creates the user from the copied properties
 
New-ADUser -SamAccountName $NewUser -Name $NewName -GivenName $firstname -Surname $lastname -EmailAddress $newuserfinitial$Lastnamens@domain.com  -Instance $DN -Path "$OUDN" -AccountPassword $SecurePassword –userPrincipalName $NewUser@$domain -Company $name.Company -Department $name.Department -Manager $name.Manager -title $name.Title -Description $name.Description -HomePage $name.HomePage  -Office $name.Office -City $name.city -PostalCode $name.postalcode -Country $name.country -OfficePhone $newusernumber -Fax $name.fax -State $name.State -StreetAddress $name.StreetAddress  -homedrive "H" -homedirectory "\\domain.local\dfs\home\$NewUser" -Enabled $true
 
#Copy Signature
Set-ADUser $NewUser -Replace @{info="$OldNotes"}
Set-ADUser $NewUser -Replace @{pager="$newusernumber"}
 
# Set Profile Location
$NewUserAdDetails = Get-AdUser -Identity $NewUser -Properties *
$DN = $NewUserAdDetails.distinguishedName
$NewUserLdap = [ADSI]"LDAP://$DN"
$NewUserLdap.psbase.invokeset(“terminalservicesprofilepath”,”\\domain.local\dfs\profiles\$NewUser)
$NewUserLdap.setinfo()
 
 
# gets groups from the Copied user and populates the new user in them
 
write-host "Copying Group Membership"
 
$groups = (GET-ADUSER –Identity $name –Properties MemberOf).MemberOf
foreach ($group in $groups) { 
 
Add-ADGroupMember -Identity $group -Members $NewUser
}
 
$count = $groups.count
 
#Check to see if new user is member of group and do things - Use Windows 2000 Name
$newusergroups = (GET-ADUSER –Identity $NewUser –Properties MemberOf).MemberOf
if ($newusergroups -match '#ADGROUP') { 
 
$currentuser = [Environment]::UserName
 
#Give the user who is running the script full permissions to the user Mailbox but don't add to Outlook
Add-MailboxPermission -Identity $NewUser -User $currentuser  -AccessRights FullAccess -Automapping $false
 
#Create the Folders
C:\scripts\Folders.ps1 $NewUser
 
#Remove Permissions
Remove-MailboxPermission -Identity $NewUser -User $currentuser -AccessRights FullAccess
 
}
 
# List of Mailbox DB
 
$databases = Get-MailboxDatabase
$Count = 0
 
Foreach ($database in $databases){
 
    Write-Host $Count "." $database.Name
    $Count ++
 
}
 
$Choice = Read-Host "Please choose a Database to list databases from"
 
$db = $databases[$Choice].Name
 
# After some testing it seems that sometimes ad don't have time to process everything and while trying to access the user for exchange it gave error.
 
write-host "Waiting time for Ad to process earliers operations"
 
Start-Sleep -s 30
 
#Clear-host
 
# Creates the New users mailbox 
 
Enable-Mailbox -Identity $NewUser@$domain -alias "$NewUser" -ManagedFolderMailboxPolicyAllowed -Database "$db"
 
# Sets secondary smtp adress while specifying the Primary smtp adress(1st address with the SMTP is the primary one).
 
Start-Sleep -s 15
 
Set-Mailbox "$NewUser" -EmailAddressPolicyEnabled $false -EmailAddresses SMTP:"$newuserfinitial$Lastnamens@domain.com"
 
#Does the user have a value for custom attribute e.g. Partner? if so copy to new user
 
if(Get-Mailbox -Identity $user | Select -Expand CustomAttribute1) { Set-Mailbox -Identity $newuser -CustomAttribute1 (Get-Mailbox -Identity $user | Select -Expand CustomAttribute1) }
 
#clear-host
 
# Creates the New user Profile Folder
New-item \\domain.local\dfs\profiles\"$newuser" -type directory
$acl = Get-Acl \\domain.local\dfs\profiles\"$NewUser"
$acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount])
$acl.SetAccessRuleProtection($true, $true)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule "domain\$NewUser","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"
$acl.addAccessRule($rule)
Set-Acl \\domain.local\dfs\profiles\"$NewUser" $acl
 
# Creates the New user Home Folder
New-item \\domain.local\dfs\home\"$newuser" -type directory
$acl = Get-Acl \\domain.local\dfs\home\"$NewUser"
$inheritanceFlags = ([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit) 
$propagationFlags = [Security.AccessControl.PropagationFlags]::None 
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule "domain\$NewUser","FullControl",$inheritanceFlags, $propagationFlags,"Allow"
$acl.addAccessRule($rule)
Set-Acl \\domain.local\dfs\home\"$NewUser" $acl
 
Set-AdUser -Identity $NewUser -Replace @{HomeDirectory="\\domain.local\dfs\home\$NewUser"}
 
$homedrivereadded = Read-Host "Now can you reset the homedrive as the script doesn't do a very good job"
 
#Logging in as user to create redirected
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$Process = New-Object System.Diagnostics.Process
 
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
$ProcessInfo.Arguments = "/generic:TERMSRV/TERMINALSERVERNAME /user:$NewUser /pass:$Password"
$Process.StartInfo = $ProcessInfo
$Process.Start()
 
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
$ProcessInfo.Arguments = "$MstscArguments /v $Computer"
$Process.StartInfo = $ProcessInfo
$Process.Start()

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , ,

 
0

Send a Robocopy Job notification via Powershell

Posted by paris on Sep 10, 2015 in Code
# Change these values
$Logfile = “C:\Scripts\Logs\AffSql_” + (Get-Date).tostring(“yyyyMMdd”) + “.log”
 
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue
 
# Copy Folder with Robocopy
$command = 'Robocopy.exe "\\unc\path\" "E:\localpath" /S /MIR /R:10 /W:5 /LOG+:$Logfile /NP /TS /FP /COPY:DAT'
iex $command
 
# Send E-mail message with log file attachment
$smtpServer = "smtpserver"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "from@domain.com"
$msg.To.Add("to@domain.com")
$msg.Subject = "SQL Backup"
$msg.Body = get-content $Logfile | out-string
$smtp.Send($msg)
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

Search for folder in iManage

Posted by paris on Sep 9, 2015 in Code

It seems the iManage Inbox has difficulties filing items in a folder with a Custom24 Attribute attached to it. Here’s how to search imanage folders and list Workspaces/Folders with this attribute to remove where required.

SELECT PF.PRJ_NAME AS 'Folder Name', PWS.PRJ_NAME AS 'Workspace Name', PN.VALUE AS 'Cust 24 Value'
FROM MHGROUP.PROJECTS PF
JOIN MHGROUP.PROJECT_NVPS PN ON PF.PRJ_ID = PN.PRJ_ID
JOIN MHGROUP.PROJECTS PWS ON PF.TREE_ID = PWS.PRJ_ID AND PWS.PRJ_ID <> PF.PRJ_ID 
JOIN MHGROUP.DOCMASTER DWS ON DWS.DOCNUM = PWS.DOCNUM
WHERE PN.NAME = 'iMan___48'
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

Worksite iManage History SQL Search Query

Posted by paris on Jul 24, 2015 in Code

Worksite/Imanage Monitor can export a document list based on History using the History search but it’s limited in the way it can display comments as well as duplicate Document Numbers. Below is SQL of how to get this direct in SSSM

Change the WorksiteDB to your DB and APPName to your application

SELECT DISTINCT [WORKSITEDB].[MHGROUP].[DOCHISTORY].[DOCNUM]
     ,[WORKSITEDB].[MHGROUP].[DOCHISTORY].[VERSION]
	 ,[WORKSITEDB].[MHGROUP].[DOCMASTER].DOCNAME
	 ,[WORKSITEDB].[MHGROUP].[DOCMASTER].T_ALIAS
      ,[ACTIVITY]
      ,[ACTIVITY_CODE]
      ,[ACTIVITY_DATETIME]
      ,[DURATION]
      ,[DOCUSER]
      ,[APPNAME]
      ,[LOCATION]
	  , CAST([WORKSITEDB].[MHGROUP].[DOCHISTORY].[COMMENTS] AS NVARCHAR(MAX))
  FROM [WORKSITEDB].[MHGROUP].[DOCHISTORY] JOIN [WORKSITEDB].[MHGROUP].[DOCMASTER] ON [WORKSITEDB].[MHGROUP].[DOCHISTORY].[DOCNUM]=[WORKSITEDB].[MHGROUP].[DOCMASTER].[DOCNUM] WHERE (APPNAME = 'APPLICATIONNAME') AND (ACTIVITY = 'Checkin')
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , ,

 
8

How to Upload and Insert Quick Copy ( Quick Step Settings) Into Exchange

Posted by paris on Jul 16, 2015 in Code

Per my backup script before , this restores

You will need to go through and change the values in %

 

$mailbox = Get-Mailbox %mailbox%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$s.AutodiscoverUrl($mailAddress);
 
 
$cred = New-Object System.Net.NetworkCredential("%username%","%password%")
 
 
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$s.Credentials = $cred
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
 
$file = [System.IO.File]::ReadAllBytes("c:\%folder%\%binaryfile%")
$data = [System.Convert]::ToBase64String($file)
 
#change folder where needed
$folderobject = GetFolder($MailboxRoot, "\Quick Step Settings\");
$folderid = $folderobject.id.uniqueid
$folderchangekey = $folderobject.id.ChangeKey
 
$expRequest = @"
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
      xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2010_SP1" />
  </soap:Header>
  <soap:Body>
  <m:UploadItems>
      <m:Items>
        <t:Item CreateAction="CreateNew" IsAssociated="true">
          <t:ParentFolderId  Id="$folderid" ChangeKey="$folderchangekey"/>
          <t:Data>$data</t:Data>
        </t:Item>
      </m:Items>
    </m:UploadItems>
  </soap:Body>
</soap:Envelope>
"@
 
$mbMailboxFolderURI = New-Object System.Uri($s.url)
$wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)
$wrWebRequest.KeepAlive = $false;
$wrWebRequest.Headers.Set("Pragma", "no-cache");
$wrWebRequest.Headers.Set("Translate", "f");
$wrWebRequest.Headers.Set("Depth", "0");
$wrWebRequest.ContentType = "text/xml";
$wrWebRequest.ContentLength = $expRequest.Length;
$wrWebRequest.Timeout = 60000;
$wrWebRequest.Method = "POST";
$wrWebRequest.Credentials = $cred
$bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($expRequest);
$wrWebRequest.ContentLength = $bqByteQuery.Length;
$rsRequestStream = $wrWebRequest.GetRequestStream();
$rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);
$rsRequestStream.Close();
$wrWebResponse = $wrWebRequest.GetResponse();
$rsResponseStream = $wrWebResponse.GetResponseStream()
$sr = new-object System.IO.StreamReader($rsResponseStream);
$rdResponseDocument = New-Object System.Xml.XmlDocument
$rdResponseDocument.LoadXml($sr.ReadToEnd());
$Datanodes = @($rdResponseDocument.getElementsByTagName("m:ResponseCode"))
$Datanodes
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , , ,

 
0

Use Exchange EWS/Powershell to Copy Outlook Quick Copy AKA Quick Step Settings

Posted by paris on Jul 16, 2015 in Code

Wow , possible my biggest EWS Powershell script, Big thanks go to Glen for the missing piece of the jigsaw. The project started as a way to copy Quick Copy settings between users when needed.

Outlook doesn’t provide much functionality to do this itself, you can use the famous redemtion.dll for this task  http://www.dimastr.com/redemption/rdoquicksteps.htm , but I’m more of a server side guy than a client side, Our Outlook Enviroment has too many macros already!

I knew how to get more Inbox items , but have never dived into the “Associated Contents Table”. Using the free MFCMAPI.exe tool , I explored the mailbox to find the folder I need as well as the table and after hours or tinkering and borrowing code we are good!

You will need to go through and change the values in %

This is the download script , I will paste the SOAP upload script in another post

$mailbox = Get-Mailbox %mailbox%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$s.AutodiscoverUrl($mailAddress);
 
#needed for XML Soap
$cred = New-Object System.Net.NetworkCredential("%username%","%password%")
 
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$s.Credentials = $cred
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
#choose the folder name you want to download the Configuration items from
$folderobject = GetFolder($MailboxRoot, "\Quick Step Settings\");
$sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Microsoft.CustomAction")
$Itemview = new-object Microsoft.Exchange.WebServices.Data.ItemView(20)
$ItemView.PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$ItemView.Traversal = [Microsoft.Exchange.Webservices.Data.ItemTraversal]::Associated
#$folderid = new-object  Microsoft.Exchange.WebServices.Data.Folderid([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$mailAddress)
$folderid = $folderobject.Id
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
$pspropset = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
$mails  = $inboxFolder.finditems($sfSearchFilter,$Itemview)
 
#loop to go through all the items in the folder
$count=0
foreach($Item in $mails.Items)
{ 
 
#gets the id for the SOAP XML Request
$itemid = $mails.Items[$count].Id.Uniqueid
 
$expRequest = @"
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
      xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2010_SP1" />
  </soap:Header>
  <soap:Body>
    <m:ExportItems>
      <m:ItemIds>
        <t:ItemId Id="$itemid"/>
      </m:ItemIds>
    </m:ExportItems>
  </soap:Body>
</soap:Envelope>
"@
$mbMailboxFolderURI = New-Object System.Uri($s.url)
$wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)
$wrWebRequest.KeepAlive = $false;
$wrWebRequest.Headers.Set("Pragma", "no-cache");
$wrWebRequest.Headers.Set("Translate", "f");
$wrWebRequest.Headers.Set("Depth", "0");
$wrWebRequest.ContentType = "text/xml";
$wrWebRequest.ContentLength = $expRequest.Length;
$wrWebRequest.Timeout = 60000;
$wrWebRequest.Method = "POST";
$wrWebRequest.Credentials = $cred
$bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($expRequest);
$wrWebRequest.ContentLength = $bqByteQuery.Length;
$rsRequestStream = $wrWebRequest.GetRequestStream();
$rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);
$rsRequestStream.Close();
$wrWebResponse = $wrWebRequest.GetResponse();
$rsResponseStream = $wrWebResponse.GetResponseStream()
$sr = new-object System.IO.StreamReader($rsResponseStream);
$rdResponseDocument = New-Object System.Xml.XmlDocument
$rdResponseDocument.LoadXml($sr.ReadToEnd());
$Datanodes = @($rdResponseDocument.getElementsByTagName("m:Data"))
$Datanodes
if ($Datanodes.length -ne 0){
	$Data = [System.Convert]::FromBase64String($Datanodes[0].'#text')
#file location
	$fsFileStream = new-object system.io.filestream C:\%folder%\quickcopy$count, ([io.filemode]::create), ([io.fileaccess]::write), ([io.fileshare]::none)
	$fsFileStream.Write($Data, 0, $Data.Length);
    $fsFileStream.Close();
}
$count= $count+1 
 
	}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , , , , , , ,

 
0

Search for File Across Multiple Servers or Roaming Profiles with Powershell

Posted by paris on Jul 15, 2015 in Code

PowerShell logoRecently we need to search a load of servers locally for files that existed ( lingered ) on peoples local user proflile

Get-ChildItem -Recurse -Force \\servername\c$\Users\*\AppData\Local\Temp | Where-Object {$_.Name -like "Z@*.tmp"} | Export-CSV C:\TempFiles.csv -Append

We then needed to search roaming directories mapped on a file server , I tried to use the above for this command replacing the directory location with a roaming file server location replace * with Users again, however I was getting “Get-ChildItem : Access is denied” with UnauthorizedAccessException , probably because query is too generic! To limit this down, I used the following pipe to query the list of users and then check each folder after

Get-ChildItem "\\domain.local\dfs\location\*" | ForEach-Object {
 
Get-ChildItem -Recurse -Force $_"\AppData\Roaming\Software"   | Where-Object {$_.Name -like "Z@*.tmp"}} | Export-CSV C:\Files.csv -Append

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , , ,

 
0

EWS Exchange Error – the underlying connection was closed an unexpected error occurred on a send

Posted by paris on Jul 8, 2015 in Code
On trying to run a EWS Script the follow error came up

The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

The addition to of the following line above to silenced the problem but did not fix the communication. Instead brought up an new error

“The request failed. The underlying connection was closed: An unexpected error occurred on a send.”

First you can add this line after each of the errors to give you the full error
$error[0] | fl -force

The full error displayed :

System.Management.Automation.PSInvalidOperationException: There is no Runspace available t  scripts in this thread. self sign certificate

The below code needs to be added instead to properly ignore the self signed certificate issues:

## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
 
$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
 
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
 
## end code from http://poshcode.org/624
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , ,

Copyright © 2017 Welcome to Pariswells.com All rights reserved. Theme by Laptop Geek. Privacy Policy