Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Using invoke with get-process and Select-object

$
0
0
All,

I am needing some help with running get-process on remote machines. 

I am wanting to get specific objects such as Name, ID , HandleCount, fileversioninfo and each time I run the command against the remote machine i get the following:

PS C:\> invoke-command -computername server01 {get-process  -name Excel | select-object name,id
>>

My question is why does it go to the prompt >>?
I can 

PS C:\Load_Stuff\MonitoringScripts\PowerShell> get-process -name excel | form

I would like to pull this specific  objects in the script as seen below....

PS C:\Load_Stuff\MonitoringScripts\PowerShell> get-process -name excel |format-list *


__NounName                 : Process
Name                       : EXCEL
Handles                    : 208
VM                         : 330530816
WS                         : 35110912
PM                         : 18128896
NPM                        : 31504
Path                       : C:\PROGRA~1\MICROS~1\Office14\EXCEL.EXE
Company                    : Microsoft Corporation
CPU                        : 6.0996391
FileVersion                : 14.0.6126.5003
ProductVersion             : 14.0.6126.5003
Description                : Microsoft Excel
Product                    : Microsoft Office 2010
Id                         : 328
PriorityClass              : Normal
HandleCount                : 208
WorkingSet                 : 35110912
PagedMemorySize            : 18128896
PrivateMemorySize          : 18128896
VirtualMemorySize          : 330530816
TotalProcessorTime         : 00:00:06.0996391
BasePriority               : 8
ExitCode                   :
HasExited                  : False
ExitTime                   :
Handle                     : 2180
MachineName                : .
MainWindowHandle           : 1521690
MainWindowTitle            : Microsoft Excel - Book1

Script to Change DNS Servers on Remote Server

$
0
0

I am new to powershell and I am trying to construct a script to change the DNS servers settings on a whole list of machines remotely. I have the list of machines that I want to change in a txt file. I have read several posts on this and tried several different methods but I cannot seem to get it to work. Here is my code, any help is much appreciated.

$servers = Get-Content C:\PathToFile\computers.txt

foreach($server in $servers)

{

    Write-Host "Connect to $server..."

    $nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE"}

    $newDNS = "10.1.1.1","10.2.2.2"

    foreach($nic in $nics)

    {

        Write-Host "`tExisting DNS Servers " $nic.DNSServerSearchOrder

        $x = $nic.SetDNSServerSearchOrder($newDNS)

        if($x.ReturnValue -eq 0)

        {

            Write-Host "`tSuccessfully Changed DNS Servers on " $server

        }

        else

        {

            Write-Host "`tFailed to Change DNS Servers on " $server

        }

    }

}

Compare-object between 2 txt files that have security updates

$
0
0

Hello,

I have 2 text files that have the following report of the installed patches on 2 different systems.each file for each system:

description                                              hotfixid                                                 InstalledOn                                           
-----------                                              --------                                                 -----------                                           
Update                                                   KB982861                                                   12/3/2012 12:00:00 AM                                  
Update                                                   KB958830                                                 12/4/2012 12:00:00 AM                                  
Update                                                   KB971033                                                 12/4/2012 12:00:00 AM                                  
Update                                                   KB2506143                                                1/14/2013 12:00:00 AM   

I would like to compare between the systems of what is missing between them and compare.

How can I accomplish that with a PowerShell script?

Thank you,

Morris

File size

$
0
0
How to get files sizes from folder 

How would I spit results from this script to csv or txt

$
0
0

How would I spit results from this script to csv or txt I have tried putting an export-csv and it wont work.

Param($ScriptFile = $(Read-Host "Enter the script file"),
    $ComputerList = $(Read-Host "Enter the Location of the computerlist"),
    $MaxThreads = 20,
    $SleepTimer = 500,
    $MaxWaitAtEnd = 600,
    $OutputType = "Text")
   
$Computers = Get-Content $ComputerList


"Killing existing jobs . . ."
Get-Job | Remove-Job -Force
"Done."

$i = 0

ForEach ($Computer in $Computers){
    While ($(Get-Job -state running).count -ge $MaxThreads){
        Write-Progress  -Activity "Creating Server List" -Status "Waiting for threads to close" -CurrentOperation "$i threads created - $($(Get-Job -state running).count) threads open" -PercentComplete ($i / $Computers.count * 100)
        Start-Sleep -Milliseconds $SleepTimer
    }

    #"Starting job - $Computer"
    $i++
    Start-Job -FilePath $ScriptFile -ArgumentList $Computer -Name $Computer | Out-Null
    Write-Progress  -Activity "Creating Server List" -Status "Starting Threads" -CurrentOperation "$i threads created - $($(Get-Job -state running).count) threads open" -PercentComplete ($i / $Computers.count * 100)
   
}

$Complete = Get-date

While ($(Get-Job -State Running).count -gt 0){
    $ComputersStillRunning = ""
    ForEach ($System  in $(Get-Job -state running)){$ComputersStillRunning += ", $($System.name)"}
    $ComputersStillRunning = $ComputersStillRunning.Substring(2)
    Write-Progress  -Activity "Creating Server List" -Status "$($(Get-Job -State Running).count) threads remaining" -CurrentOperation "$ComputersStillRunning" -PercentComplete ($(Get-Job -State Completed).count / $(Get-Job).count * 100)
    If ($(New-TimeSpan $Complete $(Get-Date)).totalseconds -ge $MaxWaitAtEnd){"Killing all jobs still running . . .";Get-Job -State Running | Remove-Job -Force}
    Start-Sleep -Milliseconds $SleepTimer
}

"Reading all jobs"

If ($OutputType -eq "Text"){
    ForEach($Job in Get-Job){
        "$($Job.Name)"
        "****************************************"
        Receive-Job $Job
        " "
    }
}
ElseIf($OutputType -eq "GridView"){
    Get-Job | Receive-Job | Select-Object * -ExcludeProperty RunspaceId | out-gridview
   
}

Enter-PSSession: WinRM cannot process the request, Kerberos authentication error 0x80090322

$
0
0

Hi!

I've configured PowerShell Remoting on the server using Enable-PSRemoting commandlet.

But when I'm trying to connect to the server I'm constantly getting the following error:

PS C:\Users\sergeyp> Enter-PSSession SERVERNAME.DOMAINNAME.com
Enter-PSSession : Connecting to remote server SERVERNAME.DOMAINNAME.com failed with the following error message : WinRM cannot process the request. The following error
with errorcode 0x80090322 occurred while using Kerberos authentication: An unknown security error occurred.
 Possible causes are:
  -The user name or password specified are invalid.
  -Kerberos is used when no authentication method and no user name are specified.
  -Kerberos accepts domain user names, but not local user names.
  -The Service Principal Name (SPN) for the remote computer name and port does not exist.
  -The client and remote computers are in different domains and there is no trust between the two domains.
 After checking for the above issues, try the following:
  -Check the Event Viewer for events related to authentication.
  -Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
 Note that computers in the TrustedHosts list might not be authenticated.
   -For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1+ Enter-PSSession SERVERNAME.DOMAINNAME.com+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (SERVERNAME.DOMAINNAME.com:String) [Enter-PSSession], PSRemotingTransportException+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Also, in the System event log on a client computer I see the Security-Kerberos error described here:
http://technet.microsoft.com/en-us/library/52ddf7d9-a0e7-4c9d-be3c-3c35219f2d69.aspx

Error details:

Log Name: System Source: Microsoft-Windows-Security-Kerberos Date: 2/22/2013 1:42:39 PM Event ID: 4 Task Category: None Level: Error Keywords: Classic User: N/A Computer: ... Description:

The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server
SERVERNAME$. The target name used was HTTP/SERVERNAME.DOMAINNAME.com.
This indicates that the target server failed to decrypt the ticket
provided by the client. This can occur when the target server principal
name (SPN) is registered on an account other than the account the target
service is using. Please ensure that the target SPN is registered on,
and only registered on, the account used by the server. This error can
also happen when the target service is using a different password for
the target service account than what the Kerberos Key Distribution
Center (KDC) has for the target service account. Please ensure that the
service on the server and the KDC are both updated to use the current
password. If the server name is not fully qualified, and the target
domain (DOMAINNAME.COM) is different from the client domain
(DOMAINNAME.COM), check if there are identically named server accounts
in these two domains, or use the fully-qualified name to identify the
server.
...

And... I have identical WinRM configuration on the other server, and it works fine.

I'm using Windows Server 2008 Standard SP2 and PowerShell 3.0.

I'm logging in as a domain user.

Both client and server are in the same domain.

The SPN HTTP/SERVERNAME.DOMAINNAME.com doesn't exist, but the corresponding SPN also doesn't exist for the computer on which PS Remoting works fine!

Could somebody help me with identification of this error source, please?


Powershell script to set the Computer Description field in AD to the display name - office number of the last person to login to a computer

$
0
0

I would like to create a Powershell script to set the Computer Description field in AD to the display name - office number of the last person to login to a computer. I've taken a couple posted ps scripts and have put this script together, but rather than using the username I would like to use the user's display name + office number:

Get-QADComputer -OSName "Windows 7*" | foreach{

    $name = $_.name

# would like to use display name + office number instead of username

    ((Get-WmiObject Win32_ComputerSystem -ComputerName $name -EA Stop).UserName)
    Set-QADComputer $name -Description

}

Listing assigned virtual desktops

$
0
0
We have a Windows 7 VDI environment running on Hyper-V 2008 R2. Users are all assigned personal virtual desktops either by using the Remote Desktop Services MMC or straight in ADUC. I've been trying to find a way to list a set of users along with the personal virtual desktop which has been assigned to each one. The Get-ADUser powershell cmdlet doesn't return any information about the personal virtual desktop. Does anyone have a way of doing this?

Export Email Header Information via PowerShell

$
0
0

I was hoping someone could help me achieve the following via Powershell. I'm trying to figure out if we can do this via theMicrosoft Online Services Module for Windows PowerShell (Office 365); or if any other way.

I am trying to write a script that will let me input an email and get a list of output (header information), as below:

INPUT:
- Sender Email 

OUTPUT:
- SentDate
- Sender
- Recipient(s)
- Subject Line

So basically I’m trying to figure out if there’s any built in cmdlet in the module for powershell. Or if I need to get something else installed to connect to the email headers to get the information I want?

Thanks...

Fuad

array is showing as one continous string in email body - how to insert carriage return?

$
0
0

$CHANGES = Compare-Object ($BEFORE | ConvertTo-CSV) ($AFTER | ConvertTo-CSV)
$REPORT = ForEach ($CHANGE in $CHANGES) {$CHANGE.InputObject | where {$CHANGE.SideIndicator -eq "=>"}}

$Message = new-object Net.Mail.MailMessage

$Message.Body = $REPORT -replace ("False","Disabled") -replace ("True","Enabled") -replace ("`"","")

$REPORT looks like this:

Doe, John, Disabled

Doe, Jane, Enabled

Running this from the console shows each array item on single line: $REPORT -replace ("False","Disabled") -replace ("True","Enabled") -replace ("`"","")

But when it is included as the message body of a .NET email it wraps: Doe, John, Disabled Doe, Jane, Enabled.  How can I get the message body to include a carriage return after each array item?

access denied for wsman:\localhost

$
0
0

I've looked around at the other threads and concluded I must be missing something pretty obvious.  This is windows XP

Firewall is off.

I'm actually on the localhost, not VPN'ing in or anything.

I'm the built-in administrator.

Host file is default.


PS C:\Documents and Settings\Administrator> dir wsman:\localhost
Get-ChildItem : Access is denied.
At line:1 char:4
+ dir <<<<  wsman:\localhost
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetChildItemCommand

edit to rule more things out: 

admin account I'm using has a password

winrm starts automatically on startup


Graceful way to create an alphabet array

$
0
0
Just curious if there is a graceway to create an array

$alphabet = @("A","B", etc...) without having to type it all in from A-Z.

Thanks,
John

Try Catch continue foreach

$
0
0

Hi

This is properly so simple. But I am trying to make a script where I would like to catch an error within an foreach, but when I set the error action it stops the whole script:

    try {
        $colItems = Get-ChildItem $folder.FullName -Recurse -ErrorAction STOP | Measure-Object -property length -sum -ErrorAction SilentlyContinue
        $size = "{0:N2}" -f ($colItems.sum / 1MB) + " MB"
    } catch {
        Write-Warning "Access Denied to $folder.Name"
        $size = "N/A"
    }
is there somehow to only stop the single foreach?

Import-Csv to update Set-ADUser but skip fields that are null?

$
0
0

I'm trying to import a CSV file from our HR department to go through and update employee titles, phone numbers, etc. Everything works fine for rows that contain all of the fields, but when there is a row where a field is null that row gets skipped. Is there anyway to continue to import that row, but skip importing the null fields in the Set-ADUser command?

Here is an example of my CSV file:

sAMAccountName,department,title,telephoneNumber,mobile
User1,Dept1,Title1,,9999999991
User2,Dept2,Title2,9999999992,1111111112
User3,Dept1,Title3,9999999993,
User4,Dept2,Title4,9999999994,1111111114

Here is the script I'm using, which works perfectly fine for User2 and User4, but completely skips User1 and User3 because they contain null fields.

$udata = Import-Csv .\test_users.csv
foreach ($User in $udata){
Set-ADUser $User.sAMAccountName -Replace @{Department = $User.department; Title= $User.title; telephoneNumber = $User.telephoneNumber; mobile = $User.mobile}
}

I've tried something like the following and get an error, "Missing '=' operator after key in hash literal. At line:4 char:12"

$udata = Import-Csv .\test_users.csv
foreach($user in $udata)
{
	Set-ADUser $user.sAMAccountName -Replace @{
		if(!($user.department -eq $null)){Department = $user.department;}
		if(!($user.title -eq $null)){Title = $user.title;}
		if(!($user.telephoneNumber -eq $null)){telephoneNumber = $user.telephoneNumber;}
		if(!($user.department -eq $null)){mobile = $user.mobile}
	}
}

Thank you for any help you might be able to offer!

get-computer -credential parameter

$
0
0

I am using the add-computer cmdlet to join a remote machine to the domain from another machine on the same LAN that is already on our domain with a command similar to the one below.  I understand that to join the machine to our domain, I need to pass local credentials that have admin rights on the workgroup machine, as well as domain credentials that have authority to join the machine on our domain.  

Looking at http://technet.microsoft.com/en-us/library/hh849798.aspx there is a -localcredential, and -credential parameter that can be used to do the above. It says that the default value for the -credential parameter is current user. Since the remote machine I am running the command from is already joined to the domain, and I am logged into it with a domain account that has permission to join machine to our domain, I would like to know if its possible to omit the -credential parameter or have it use the credentials I'm currently logged in with to join the remote machine to our domain.

Example of what currently works, but prompts for two sets of credentials:Add-Computer -DomainName test.com -ComputerName testcomputer       -credential domain\domainuser  -LocalCredential testcomputer\localuser -force -restart

Example of what I am trying to get to work: (passes current logged in domain user from where script is started)
Add-Computer -DomainName test.com -ComputerName testcomputer  -LocalCredential testcomputer\localuser -force -restart 


The Future of Operating Systems.

$
0
0
What will be the features that would give base to Operating systems to live in the era, where every where we will be having roboot in our materialistic life?

Negative file size mnemonic not binding to parameter

$
0
0

I'm writing a script where the sign of certain parameters determines the functionality.  In particular, positive filesize finds all files larger than X, negative filesize fines all files smaller than X.

To test this issue, create this function (or equivalent script):

function foo {
param([Int]$Size)
$Size
}

To test:

> foo 1kb
1024> foo -1kb
foo : Cannot process argument transformation on parameter 'Size'. Cannot convert value "-1kb" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:4+ foo <<<<  -1kb+ CategoryInfo          : InvalidData: (:) [foo], ParameterBindin...mationException+ FullyQualifiedErrorId : ParameterArgumentTransformationError,foo

My guess is the Powershell engine first converts the mnemonic 1kb to the equivalent number 1024, then the value is bound to the [int] parameter.  

But, why doesn't it also first convert -1kb to -1024, then bind that to the parameter?

This works; are there any better workarounds???

> foo -size (-1kb)
-1024

Thanks,

Scott

get-content

$
0
0

How can I tell get-content to only output lines that (as of the moment) are being added to the text file?

my code

get-content locationOfTheFile.txt -wait

seems to load the entire file.I am looking at a log file which are updated very frequently.

Help with cleaning up this script to use nslookup on our various subnets

$
0
0

Hello,

I'm hoping the community can assist with helping me cleanup the following script.  The script works great in that it does an nslookup on all IP's we have available to us but currently it reports the results in my powershell window only.  I would like to write this out to a CSV file instead.  My thought is to assign each line to a variable and then use the Export-Csv command to write out the results.  Here is my script:

84..111 + 113..124 + 129..150 + 159..161 + 163..167 + 171..240 |%{$h="10.10.14.$_";if($n=(nslookup $h 2>$null) -match "Name:"-replace"Name:\s{2,}"){"$h,$n"}else{"$h"}}
11..21 + 23..37 + 39..51 + 53..66 + 78..85 + 87..128 + 131..151 + 153..190 + 192..202 |%{$h="10.10.15.$_";if($n=(nslookup $h 2>$null) -match "Name:"-replace"Name:\s{2,}"){"$h,$n"}else{"$h"}}
12..254 |%{$h="10.10.16.$_";if($n=(nslookup $h 2>$null) -match "Name:"-replace"Name:\s{2,}"){"$h,$n"}else{"$h"}}
31..254 |%{$h="10.10.17.$_";if($n=(nslookup $h 2>$null) -match "Name:"-replace"Name:\s{2,}"){"$h,$n"}else{"$h"}}

It's not pretty, but we have a lot of IP's we can't use when building our VM's so with the help of this community this script was born to help us track which IP's in each VLAN is available and which aren't.

Any help you can provide would be appreciated.

Thank you,

Outlook Signature Output issue

$
0
0

Cannot get DisplayName, sn, givenName, and streetAddress to be in lowercase as desired in the output of this script. This script creates an Outlook Signature based on AD Attributes.

Any help is greatly appreciated.

###########################################################################” 
# 
# NAME: ogsig.ps1 
# 
# AUTHOR: Dustin Barna 
# 
###########################################################################” 
 
#Custom variables 
$CompanyName = ‘og’ 
$DomainName = ‘newstarfresh.com’ 
 
$SigSource = “\\$DomainName\netlogon\Signatures\$CompanyName” 
$ForceSignatureNew = ’1' #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force 
$ForceSignatureReplyForward = ’0' #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force 
 
#Environment variables 
$AppData=(Get-Item env:appdata).value 
$SigPath = ‘\Microsoft\Signatures’ 
$LocalSignaturePath = $AppData+$SigPath 
$RemoteSignaturePathFull = $SigSource+’\'+$CompanyName+’.docx’ 
 
#Get Active Directory information for current user 
$UserName = $env:username 
$Filter = “(&(objectCategory=User)(samAccountName=$UserName))” 
$Searcher = New-Object System.DirectoryServices.DirectorySearcher 
$Searcher.Filter = $Filter 
$ADUserPath = $Searcher.FindOne() 
$ADUser = $ADUserPath.GetDirectoryEntry() 
$ADDisplayName = $ADUser.DisplayName
$ADgivenName = $ADUser.FirstName
$ADsn = $ADUser.LastName 
$ADEmailAddress = $ADUser.mail 
$ADTitle = $ADUser.title 
$ADTelePhoneNumber = $ADUser.TelephoneNumber 
$ADFax = $ADUser.facsimiletelephonenumber
$ADMobile = $ADUser.mobile
$ADstreetAddress = $ADUser.streetAddress

#Setting registry information for the current user 
$CompanyRegPath = “HKCU:\Software\”+$CompanyName 
if (Test-Path $CompanyRegPath) 
{} 
else 
{New-Item -path “HKCU:\Software” -name $CompanyName} 
 
if (Test-Path $CompanyRegPath’\Outlook Signature Settings’) 
{} 
else 
{New-Item -path $CompanyRegPath -name “Outlook Signature Settings”} 
 
$SigVersion = (gci $RemoteSignaturePathFull).LastWriteTime #When was the last time the signature was written 
$ForcedSignatureNew = (Get-ItemProperty $CompanyRegPath’\Outlook Signature Settings’).ForcedSignatureNew 
$ForcedSignatureReplyForward = (Get-ItemProperty $CompanyRegPath’\Outlook Signature Settings’).ForcedSignatureReplyForward 
$SignatureVersion = (Get-ItemProperty $CompanyRegPath’\Outlook Signature Settings’).SignatureVersion 
Set-ItemProperty $CompanyRegPath’\Outlook Signature Settings’ -name SignatureSourceFiles -Value $SigSource 
$SignatureSourceFiles = (Get-ItemProperty $CompanyRegPath’\Outlook Signature Settings’).SignatureSourceFiles 
 
#Forcing signature for new messages if enabled 
if ($ForcedSignatureNew -eq ’1') 
{ 
#Set company signature as default for New messages 
$MSWord = New-Object -com word.application 
$EmailOptions = $MSWord.EmailOptions 
$EmailSignature = $EmailOptions.EmailSignature 
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries 
$EmailSignature.NewMessageSignature=$CompanyName 
$MSWord.Quit() 
} 
 
#Forcing signature for reply/forward messages if enabled 
if ($ForcedSignatureReplyForward -eq ’1') 
{ 
#Set company signature as default for Reply/Forward messages 
$MSWord = New-Object -com word.application 
$EmailOptions = $MSWord.EmailOptions 
$EmailSignature = $EmailOptions.EmailSignature 
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries 
$EmailSignature.ReplyMessageSignature=$CompanyName 
$MSWord.Quit() 
} 
 
#Copying signature sourcefiles and creating signature if signature-version are different from local version 
if ($SignatureVersion -eq $SigVersion){} 
else 
{ 
#Copy signature templates from domain to local Signature-folder 
Copy-Item “$SignatureSourceFiles\*” $LocalSignaturePath -Recurse -Force 
 
$ReplaceAll = 2 
$FindContinue = 1 
$MatchCase = $False 
$MatchWholeWord = $True 
$MatchWildcards = $False 
$MatchSoundsLike = $False 
$MatchAllWordForms = $False 
$Forward = $True 
$Wrap = $FindContinue 
$Format = $False 
 
#Insert variables from Active Directory to rtf signature-file 
$MSWord = New-Object -com word.application 
$fullPath = $LocalSignaturePath+’\'+$CompanyName+’.docx’ 
$MSWord.Documents.Open($fullPath) 
 
$FindText = “givenName” 
$ReplaceText = $ADgivenName.ToString().ToLower()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    ) 

$FindText = “sn” 
$ReplaceText = $ADsn.ToString().ToLower()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    ) 
 
$FindText = “Title” 
$ReplaceText = $ADTitle.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    ) 

$FindText = “TelephoneNumber” 
$ReplaceText = $ADTelePhoneNumber.ToString() 
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    )  

$FindText = “FacsimileNumber” 
$ReplaceText = $ADFax.ToString() 
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    )

$FindText = “streetAddress” 
$ReplaceText = $ADstreetAddress.ToString().ToLower()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    )

$FindText = “CellNumber” 
$ReplaceText = $ADMobile.ToString() 
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,    $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,    $Format, $ReplaceText, $ReplaceAll    )

$MSWord.Selection.Find.Execute(“Email”) 
 
$MSWord.ActiveDocument.Hyperlinks.Add($MSWord.Selection.Range, “mailto:”+$ADEmailAddress.ToString(), $missing, $missing, $ADEmailAddress.ToString()) 
$MSWord.ActiveDocument.Save() 
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatHTML”); 
[ref]$BrowserLevel = “microsoft.office.interop.word.WdBrowserLevel” -as [type] 
 
$MSWord.ActiveDocument.WebOptions.OrganizeInFolder = $true 
$MSWord.ActiveDocument.WebOptions.UseLongFileNames = $true 
$MSWord.ActiveDocument.WebOptions.BrowserLevel = $BrowserLevel::wdBrowserLevelMicrosoftInternetExplorer6 
$path = $LocalSignaturePath+’\'+$CompanyName+”.htm” 
$MSWord.ActiveDocument.saveas([ref]$path, [ref]$saveFormat) 
 
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatRTF”); 
$path = $LocalSignaturePath+’\'+$CompanyName+”.rtf” 
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat) 
 
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatText”); 
$path = $LocalSignaturePath+’\'+$CompanyName+”.rtf” 
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat) 
 
$path = $LocalSignaturePath+’\'+$CompanyName+”.txt” 
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$SaveFormat::wdFormatText) 
$MSWord.ActiveDocument.Close() 
 
$MSWord.Quit() 
 
} 
 
#Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the “Custom variables”-section. 
if ($ForcedSignatureNew -eq $ForceSignatureNew){} 
else 
{Set-ItemProperty $CompanyRegPath’\Outlook Signature Settings’ -name ForcedSignatureNew -Value $ForceSignatureNew} 
 
if ($ForcedSignatureReplyForward -eq $ForceSignatureReplyForward){} 
else 
{Set-ItemProperty $CompanyRegPath’\Outlook Signature Settings’ -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward} 
 
if ($SignatureVersion -eq $SigVersion){} 
else 
{Set-ItemProperty $CompanyRegPath’\Outlook Signature Settings’ -name SignatureVersion -Value $SigVersion}

Viewing all 2562 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>