Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Loops ForEach and For speed difference and results difference Questions

$
0
0

Hey all, 

Working with PowerShell and Outlook for a folder that's getting rather unruly. 

 

I created a script that used a foreach loop to delete all emails in a folder, When ever i run it though it only deletes half of the emails in the folder. but does so in a semi quick manner. 

when i change it to a for loop it deletes every email but does it a snails pace.. 

So my questions are: 

Why is the FOREACH only looping through half of the results (never seen do that before, is it a bug with outlook coms?). 

and

Why is the FOR loop sooo very slow

 

CODE: 

 

#Outlook Connection

$Outlook = New-Object -ComObject Outlook.Application

# Outlook folder to clean up and load into SQL

$EmailsInFolder = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Folders.Item("__ SCOM Alerts").Items

## FOR Loop

FOR ( $i=($EmailsInFolder.count-1) ; $i -ge 0 ; $i-- )

    {

        $($EmailsInFolder)[$i].Delete()

        #write-host $i

    }

 

 

CODE@ FOREACH

 

#Outlook Connection

$Outlook = New-Object -ComObject Outlook.Application

# Outlook folder to clean up and load into SQL

$EmailsInFolder = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Folders.Item("__ SCOM Alerts").Items

## FOREACH

FOREACH ($Email in $EmailsInFolder)

{

$Email.Delete()

}

 


Print line

$
0
0

Hello!

When I search a string in several .txt datas I get the output of the files the string was found. Let's say I find 10 files with the string I was looking for.
Now I want to use the output files (only the output files, not all files!) and print the first line of all the output files.
Is there a way to do this? The search works fine but I can't figure out how to use the output automatically without typing all the output names manually in.

Thanks 

MVP top tips: Columns in Remote Access Management, SCOM 2012 Health Script, PowerShell V5, Associations in SharePoint and Office 365, Sharing Images Phone 8.1 apps

$
0
0

MVP top tips: Columns in Remote Access Management, SCOM 2012 Health Script, PowerShell V5, Associations in SharePoint and Office 365, Sharing Images Phone 8.1 apps

Read More

More New Stuff in PowerShell V5: A NEW Way to Construct Things

$
0
0

Usually we can build out a new instance of a .Net object we have to use New-Object and pass the required parameters to accomplish this. Or at least that is the most common approach to the subject. We can also use [activator] type as well to build out the same instance with a little bit better performance. Both of these are compatible since at least V2 (I don’t deal with V1, so someone who still has this running can verify in the comments). And even sometimes you can use a hash table with a .Net type to build out the instance as well (works well with WPF and WinForms).

Read More

Local User Accounts

$
0
0

Hello Everyone,

I am very new to Powershell or even scripting for that matter. We are trying to change the password for a local user account that is disabled for 2000 computers on our domain. When the script starts running it will stop if the computer is offline or network path is not found. I was hoping someone might help me with something along the lines of " If network path not found then skip to next computer on text file"

Here is the script I have so far using Powershell V2.0:

$computers = Get-Content -path C:\users\walter.barrios\desktop\computers2.txt |  where {$_ -match "\w+"

} | foreach {$_.trim()}

$username = "XADMINISTRATOR"

$password = "P@ssw0rd12345!"

Foreach($computer in $computers)

{

  $user = [adsi]"WinNT://$computer/$username,user" 

  $user 

   $user.SetPassword($Password)

   $user.SetInfo()

}

 

Arrays and stings and foreach, trying to understand?

$
0
0

It took me over two hours to get this foreach loop to work because there was something about the array that I was over looking. I am not even sure exactly what I did, or more importantly why I had to do it. 

I was using PowerCLi to get the folder id of two folders named the same.  It would not run through the foreach loop and give me the results I wanted because it changed the object when I started to pull items out of the variable.  

 

This is what worked:

$vm = "vmname"

$folders = Get-Folder "Windows Servers"

#$folders.id

#there will be two folders Id's if there is more than one Folder

#!!!you will need the name of a VM in one of the folders to determine which is which!!!

$fsum = New-Object System.Collections.ArrayList

$fsum.add("$f1")

$fsum.add("$f2")

$f1 = $folders[0].id 

$f2 = $folders[1].id

 

foreach ( $fs in $fsum ) { $test = Get-Folder -id $fs | Get-VM $vm -erroraction 'silentlycontinue' 

        if ( $test ) { "This is the correct folder: $fs" }}

What I don't understand is why this type of thing did not work:

$fsum = $f1

$fsum = $fsum + $f2

$fsum

It would give me something like the string concatenated:

FolderFolder

I tried this too:

$fsum = @()

$fsum += $f1

$fsum += $f2

Lastly, why does this add give the output 0 and 1?

$fsum.add("$f1")

$fsum.add("$f2")

 

Search Files efficiently

$
0
0

Hi,

I am trying to write a powershell script to search and find if the files exist in a given directory or Drive. and then find the fullpath of the file location.

In the Filestoscan.txt I have some 700 file names (only the file names, without the full path) which can be present anywhere in the C:\Program Files (x86).

I am doing a search in C:\Program Files (x86) to find these file names. The search is taking very long time to complete. I am doing a foreach loop on every filename and executing get-childitem on the whole C:\Program Files (x86). .

then iterate through next file...... search the whole C:\Program Files (x86).

It takes about 30 minutes to finish the search. I am afraid, If i need to search one level up, C:\ or search for more files,  it is going to take infinite amount of time.

Is it the foreach loop i am not using properly causing the slowness or does the powershell takes this long for search normally.

Please advice if there is any better/efficient method to search the files.

CODE:

$var=(Get-Content $DirPath\Filestoscan.txt)

foreach ($filename in $var) {

[string]$filename=$filename.Trim();

Get-ChildItem -Recurse -Force "C:\Program Files (x86)" -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*$filename*") } | Select-Object FullName,Directory >> "$DirPath\fileResultOutput.txt"

}

 

 

delete


question about New-WebServiceProxy over https in powershell 3.x

$
0
0

Good Day!

Can someone please help me find an answer on 'How to get the response from the Remedy ARS webservice over https in powershell 3.x' ?

One of the ways I've tried is to have the webservice object created with the below step and I see the below errror.

New-WebServiceProxy : The HTML document does not contain Web service discovery information.

At line:2 char:9

+ $myitsm=New-WebServiceProxy -Uri $uri -Namespace ITSM

............

............

 

What is happenning is that the Remedy ARS system is feeding/responding with a Logon Page and the new-webservice cmdlet doesn't find any WSDL in there. So fails to proceed.

Here is how I tried which works for http(Dev) but not for https(Prod).

 $ARSuri=https://coreweb.itsm.env.srv.yourcompany.com.au/arsys/WSDL/protected/coreapp.itsm.env.srv.yourcompany.com.au/HPD_IncidentInterface_WS'

 $myitsm=New-WebServiceProxy -Uri$ARSuri-NamespaceITSM

 

What's the best way ? 

Let me know if I need to provide any further info.

Thanks in advance.

Updating AD users information from a CSV file.

$
0
0

Hi,

 

I have this Excel file with a list of telephones, names, departments and titles which is distributed and updated by the HR department. 

I want to use import-csv to update the Telephone, Department and Title in AD, however I am kind of new with PS. I know how to do it when the columns are named exactly like the field names in AD, but they can't be named like that by the HR.

Please help :)

 

Unable to create self assigned certificate for powershell file

$
0
0

I am trying to make a self assigned certificate for my powershell script.

 

Getting below Error:

Export-certificate : The term 'Export-certificate' is not recognized as the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
+ Export-certificate -FilePath $filelocation -Cert cert:\localmachine\My\$thumbpri ...
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Export-certificate:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I am having Powershell 3.0

PS C:\Windows\system32> Get-Host


Name             : ConsoleHost
Version          : 3.0
InstanceId       : ec667d49-8d10-437f-8235-75c155af8527
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

=======================================

##Certificate command below

# SelfSignedCertificate.ps1
# Written By EISHKKA
#
$certfilepath = "c:\"     #Where do you want to export the file to?  Include trailing backslash
$certfilename = "EISHKKA_"  #what name would you like for the cert (used for Certificate Name and Exported Filename) [no extension]
$certfilename += hostname    # Append the host name to the cert name

$name = new-object -com "X509Enrollment.CX500DistinguishedName.1"
$name.Encode("CN=" + $certfilename , 0)

$key = new-object -com "X509Enrollment.CX509PrivateKey.1"
$key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
$key.KeySpec = 1
$key.Length = 2048
$key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
$key.MachineContext = 1
$key.Create()

$serverauthoid = new-object -com "X509Enrollment.CObjectId.1"
$serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.2")
$ekuoids = new-object -com "X509Enrollment.CObjectIds.1"
$ekuoids.add($serverauthoid)
$ekuext = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
$ekuext.InitializeEncode($ekuoids)

$cert = new-object -com "X509Enrollment.CX509CertificateRequestCertificate.1"
$cert.InitializeFromPrivateKey(2, $key, "")
$cert.Subject = $name
$cert.Issuer = $cert.Subject
$cert.NotBefore = get-date
$cert.NotAfter = $cert.NotBefore.AddDays(900)
$cert.X509Extensions.Add($ekuext)
$cert.Encode()

$enrollment = new-object -com "X509Enrollment.CX509Enrollment.1"
$enrollment.InitializeFromRequest($cert)
$certdata = $enrollment.CreateRequest(0)
$enrollment.InstallResponse(2, $certdata, 0, "")

# Let user know the certificate is now installed
Write "The following <$certfilename> certs are now installed..."
dir -recurse cert:\localmachine\My | Where-Object { $_.Subject -eq ("CN=" + $certfilename)} | Format-Table subject, thumbprint, notbefore -AutoSize

# Get the thumbprint from the last created certificate of the name we just created - so we can export it to a file
$thumbprint=(dir cert:\localmachine\My -recurse | where {$_.Subject -match "CN=" + $certfilename} | Select-Object -Last 1).thumbprint
Write  "Exporting cert:\LocalMachine\My\$thumbprint to $certfilepath$certfilename.cer ... "
dir cert:\localmachine\My -recurse | where {$_.thumbprint -match $thumbprint} # Display the certificate we will be exporting

# Do the export
$filelocation = $certfilepath ; $filelocation += $certfilename; $filelocation +=(".cer") # Concatinate the destination filename and path

Export-certificate -FilePath $filelocation -Cert cert:\localmachine\My\$thumbprint
Write "The certificate that was just installed/exported is: cert:\LocalMachine\My\$thumbprint $filelocation"

Copying and inserting text from one file into another into a specific place within that text file

$
0
0

Hi All,

I am trying to copy the contents of a file and then paste this content into a specific location within another file. 

I can copy the contents no problem using get-content and then paste the content using the set-content (which i know is not correct as this is overwriting the file) i need to just paste it into the other file after the last <location/> tag.

However, i cannot find anywhere how best to do this?

 

Any help with this is greatly appreciated.

 

Cheers 

Grizzly

.log file to richtextbox

$
0
0

Hello,

i'm searching for the best way to show a microsoft .log file to a richtextbox. if u just do a get-content, i have somthing like that in richtextbox :

 

<![LOG[Raised Program Started Event for Ad:K24532, Package:K002555, Program: InstallationQuiet]LOG]!><time="16:46:29.976-120" date="07-29-2014" component="execmgr" context="" type="1" thread="3576" file="executioncontext.cpp:459">

 

first think is to use a regex to get all groups and show them without <![Log ..

but do you think there is a better way ? faster ? ..

my goal is to show something similar to SMS Trace.

 

thx for the help

Chris

 

Incorrect Total Folder Size Calculation - Please assist

$
0
0

Guys,

I use the below script to calculate a folder size and size of immidiate child folders.My output will be like below.

Folder Sizes for "C:\temp"

Run on 09/09/2014 12:02:01 PM

Folder NameOwnerCreated onLast UpdatedSize
C:\temp**************8/11/2014 3:54:12 PM9/9/2014 12:01:19 PM303.66 MB
C:\temp\professional**************9/8/2014 11:43:14 AM9/8/2014 1:15:35 PM303.64 MB
C:\temp\Sample*************9/8/2014 12:38:55 PM9/8/2014 12:39:03 PM0.01 MB

Total Space Used In "C:\temp": 607.31 MB

Error in my script is calculating the total space used ---> It is calulating the C:\temp whole folder size along with internal folder size also,

The corrent output has to be "Total Space Used In "C:\temp": 303.66 MB"

Where is the logic missed in the script, please help.

Script below:

Param (
 [string]$Path = "C:\temp",
 [string]$ReportPath = "C:\temp\Sample"
)

Function AddObject {
 Param (
  $FileObject
 )
 $Size = [double]($FSO.GetFolder($FileObject.FullName).Size)
 $Script:TotSize += $Size
 If ($Size)
 { $NiceSize = CalculateSize $Size
 }
 Else
 { $NiceSize = "0.00 MB"
        $Size = 0
 }
 $Script:Report += New-Object PSObject -Property @{
  'Folder Name' = $FileObject.FullName
  'Created on' = $FileObject.CreationTime
  'Last Updated' = $FileObject.LastWriteTime
  Size = $NiceSize
        RawSize = $Size
  Owner = (Get-Acl $FileObject.FullName).Owner
 }
}

Function CalculateSize {
 Param (
  [double]$Size
 )
 If ($Size -gt 1000000000)
 { $ReturnSize = "{0:N2} GB" -f ($Size / 1GB)
 }
 Else
 { $ReturnSize = "{0:N2} MB" -f ($Size / 1MB)
 }
 Return $ReturnSize
}

cls
$Report = @()
$TotSize = 0
$FSO = New-Object -ComObject Scripting.FileSystemObject

#First get the properties of the starting path
$Root = Get-Item -Path $Path
AddObject $Root

#Now loop through all the subfolders
ForEach ($Folder in (Get-ChildItem -Path $Path | Where { $_.PSisContainer }))
{ AddObject $Folder
}

#Create the HTML for our report
$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
</style>
<Title>
Folder Sizes for "$Path"
</Title>
"@

$TotSize = CalculateSize $TotSize

$Pre = "<h1>Folder Sizes for ""$Path""</h1><h2>Run on $(Get-Date -f 'MM/dd/yyyy hh:mm:ss tt')</h2>"
$Post = "<h2>Total Space Used In ""$($Path)"":  $TotSize</h2>"

#Create the report and save it to a file
$Report | Sort RawSize -Descending | Select 'Folder Name',Owner,'Created On','Last Updated',Size | ConvertTo-Html -

PreContent $Pre -PostContent $Post -Head $Header | Out-File $ReportPath\FolderSizes.html

#Display the report in your default browser
& $ReportPath\FolderSizes.html

Writing a whois for multipel ips

$
0
0

 

Hi I have started to write some small thingy to run whois with some proxy parameters.

Try to use the webservicex.net and the whois function.

param([String]$domain)
if ($domain -eq "") { $domain = Read-Host "Please Enter Domain" }
if ($domain -eq "") { Write-Host "No domain was entered, quitting.." }
else {
 
$wc = New-Object System.Net.WebClient
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$wc.GetWhoIs($domain)
}

and that work, but when i got to do this on mutlipel ips from a source file with ip.

$servers = Get-Content C:\Scripts\hostlist.txt
 
foreach ($_ in $servers) {
 
$wc = New-Object System.Net.WebClient
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$wc.GetWhoIs($_) | Out-File -FilePath C:\Scripts\output.txt -Append -Force
}

it does not work, any ideas of the script or just a other great function to use.

 

 


PowerShell Web Access eliminates location restrictions

$
0
0

IT professionals no longer need to be glued to their laptop to manage their virtual environments. PowerShell Web Access allows professionals to handle anything from a phone or a tablet.

Read More

Chef Brings DevOps Platform and Practices to Windows and Microsoft Azure

$
0
0

Chef, the leader in web-scale IT automation, today announced new integration with Windows PowerShell Desired State Configuration (DSC), enabling developers and operations teams to best implement DevOps practices on the journey to web speed and scale. Chef also today announced its next-generation IT automation platform, Chef 12 (see separate release), with a new comprehensive suite of enterprise features for high availability (HA), replication, and analytics. 

Read More

Book: Announcing Windows PowerShell Desired State Configuration Revealed

$
0
0

If you have followed my posts here and/or heard me speaking in the last 6 to 8 months, I have been mostly focusing on Desired State Configuration. At the same time, I was busy writing a book for Apress on DSC. I am very happy to announce that this book is available for pre-order now. As I write this post, the content of the book is final and ready if you are a part of the Alpha program.

This will be my first published book and I am excited. This book will be available through Amazon and various other sales channels and will be available in all book formats. I must thank the PowerShell team members (Abhik, Nana, Hemant, Travis, and everyone on the team) and the community. Especially, I have learned a lot about DSC from my friend and fellow MVP Steven Murawski.

Powershell Script - change folder owner based on username from a csv file

$
0
0

Hi

I've got a Powershell script which allows me to change the owner of a users home drive from it's current owner (administrators) to the user, but it only allows me to do one user at a time.
I've exported a list of users whose owner is set to administrators and put the information into a csv file. What I want to do is modify my existing script to import the csv file, and change the owner of these users home folders from administrators to the user.

Please note the folder name of the users home folder, matches the ad account name. And the csv file has the following headings: 
Share: (lists the users home folder path = \\servername\$share\userfolders\userhomefolder1, 2, 3 etc
Name: (Ad acccount name)
Owner: Builtin\Administrators

Here is my existing script which works on a per user basis:

function pathPrompt {

$tempPath = $null
$tempPath = Read-Host "\\servername\$share\userfolders\userfolder"
return $tempPath
}

$username=$Username
$domain=”domain”
$ID = new-object System.Security.Principal.NTAccount($domain, $username)

$path = "\\servername\$share\userfolders\userfolder"

write-host $path

$acl = get-acl $path
$acl.SetOwner($ID)
set-acl -path $path -aclObject $acl

Any help would be most appreciative. I've got about 1000 of these to do :)

 

Cheers Ben

Win32_printer and cross check with csv file and delete printer Zero clients

$
0
0

I am getting the mac address of the zero client and then importing a csv. from there i filter out all records from the printers list that don't match with the mac address. After the printers are found I match it to the WMI win32_printer query. Then i want to delete the printers that matched but i cannot get it to work right.

#Get the client MAC ADDRESS and assign it to a variable

$NIC = Get-ItemProperty 'HKCU:\Volatile Environment' | Select-Object -ExpandProperty ViewClient_MAC_Address

 

#import the list of computers/printers from the CSV file. Assign it to a variable

$printers = Import-CSV \\vpc275\c$\MyScripts\Printers.csv

 #filter out all records from the printers list that don't match with the MAC

$p = $printers | Where-Object {$_.'MAC' -eq $NIC}

#Delete printers found

$WMI = Get-WMIObject Win32_Printer | where {$_.Name -eq $p.'Printer location'} | foreach{$_.delete()}

I am new to powershell sorry if i do not make sense. Also do yall know any easy way to have error handling, like if the mac address is not found the write to log file what happend or if it cannot remove the printer due to printer in use or something along those lines.

csv headers 

MAC        Printer name     Printer location             DefaultPrinter

 

Viewing all 6937 articles
Browse latest View live