Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Simplest things dont even work..

$
0
0

This is beyond simple. I have spent now 10 times longer than doing this manually would have taken. Simple script saved as ps1 and trying to run the variable keeps not updating...

$test1 = Read-Host -Prompt "Input user"

get-mailbox -identity $test1

add-mailboxfolderpermission -identity ($test1.alias+':\calendar') -User Manager -AccessRights Reviewer

When I run this it prompts as expected, I enter the username to update, the "get-mailbox" shows the user I have entered, but then it fails to update saying the Manager user already has permissions.

At this point when the script fails if I do a "get-mailbox -identity $test1" it tells me a previous user I have attempted this with.

For example I run it and put in "john.smith", it runs, the "get-mailbox" line of the script returns john.smith, but then the add-permission line fails and if I do a manual get-mailbox it tells me the variable is instead "jane.smith" or some other user I have previously ran this manually with.

I just can't possibly work out what I am doing wrong... The variable reads as one user on one line, then another on another?? I'm at the point of a heart attack pulling my hair out stressing over this stupdi shit.



Active Directory Powershell command error for some users

$
0
0

Hello,

I use following command to get a user DL membership using active directory module for PowerShell

Get-ADPrincipalGroupMembership username |select name,group* | ft  -autosize . This command in return gives me output for all the DL membership of the user that I have rqueried. How ever for some of my users when I run this command, I get below error:

PS C:\Users\adm> Get-ADPrincipalGroupMembership userabc |select name,group*
| ft  -autosize
Get-ADPrincipalGroupMembership : The server was unable to process the request d
ue to an internal error.  For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from th
e <serviceDebug> configuration behavior) on the server in order to send the exc
eption information back to the client, or turn on tracing as per the Microsoft
.NET Framework 3.0 SDK documentation and inspect the server trace logs.
At line:1 char:31
+ Get-ADPrincipalGroupMembership <<<<  userabc |select name,group* | ft  -autos
ize
    + CategoryInfo          : NotSpecified: (userabc:ADPrincipal) [Get-ADPrinc
   ipalGroupMembership], ADException
    + FullyQualifiedErrorId : The server was unable to process the request due
    to an internal error.  For more information about the error, either turn
  on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or
  from the <serviceDebug> configuration behavior) on the server in order to
 send the exception information back to the client, or turn on tracing as     p
er the Microsoft .NET Framework 3.0 SDK documentation and inspect the ser    ve
r trace logs.,Microsoft.ActiveDirectory.Management.Commands.GetADPrincip    alG
roupMembership

***********************

I get the above error output only for some users!!!


bws

faster new-pssession

$
0
0

I tried using invoke command by its self and it wasn't working. Maybe in need a profile? So i went with method 2 and used new-pssession but its starts so slow(i am opening about 600).

Is there a better way to handle this?

$session = 600COMPUTERS

write-host Opening PSSession $session = New-PSSession -credential $cred -ComputerName $Clients -ErrorAction SilentlyContinue


Show Servers without Win32_Product

$
0
0

Hello,

I'd like to look for software on servers and have all servers display even if the software isn't installed. I'm running the script below and if .Net isn't installed on a server, that server won't even be in the output. Can I make all servers display and if .Net's not installed, the name column will just be blank for that server?

Get-WmiObjectwin32_product-computername(get-content"c:\temp\servers.txt")|where{$_.name-like"*.Net*"}|select__server,Name

Thanks,

Scott

Powershell script to send e-mail only once if a condition is satisfied and not everytime it is scheduled to run

$
0
0

I have a powershell script that is scheduled to run every 15 minutes. It connects to a printer and checks the ink levels. If the ink level falls to 5%, it sends a mail to the admin group. When the ink level is 4% it resets the ink levels to 100%. What I am trying to do is send the mail only once when the ink level falls to 5% and not send repeated mails every time it is scheduled. It takes about a few hours for the ink levels to change from 5% to 4%. I want to get just one mail when the ink level hits 5%.

Thanks in advance for any pointers.

Thanks.

Win32_quickfixengineering vs get-hotfix

$
0
0

Hi,

I am looking a way to extract hotfixlist from a computer. So I have 2 choices: Get-hotfix or with WMI win32_quickfixengineering. We are running Vista and Windows 7 32 bits.

1. I found running get-hotfix is returning InstalledOn hour to 00:00:00. Any idea why?

Get-Hotfix | Select HotfixID, Description, Caption, InstalledOn | Sort-Object InstalledOn
2. With win32_quickfixengineering, installedOn is returning the correct value. But I would like the caption just returning the ID instead the long URL path. Any Idea?
Get-WmiObject -Class "win32_quickfixengineering" | Select-Object -Property "HotfixID", "Status", "Description", `
    @{Name="Caption"; $_.caption.split("=")}, `"InstalledData", "InstalledBy",`
   	 @{Name="InstalledOn"; Expression={([DateTime]($_.InstalledOn)).ToLocalTime()}} |Sort-Object -Property InstalledOn -descending |Format-Table -autosize

3.  Is it possible getting the full name as in Add remove program?


Active Directory Daily Logon

$
0
0

Hi,

Can somebody help me to query our AD Users who logon within 24 hours but will not include users who did not login or disabled?

Thanks


Anthony JD Luistro



powershell 4 and exchange 2010 issues

$
0
0
Hello All,
My company is a powershell 2.0 shop that was looking to upgrade to powershell 4.0 due to some attractive features. Based on the spec sheet on(i cannot post the link) it states that exchange 2010 with rollout 5 update is supported. we decided to start testing it. the link states that we need Microsoft Exchange Server 2010 SP3 with update rollout 5 which we have. On my machine I am testing WMF 4.0. I have exchange management console installed on my machine with sp3 and update rollup 5. now for the problem:

      • if i run any exchange command such as "get-mailboxdatabase" "enable-mailbox" etc, i get:
    The type initializer for 'Microsoft.Exchange.Diagnostics.ExTraceConfiguration' threw an exception.
        + CategoryInfo          : OperationStopped: (corpmail1.corp.lan.aleks.com:String) [], PSRemotingTransportException
        + FullyQualifiedErrorId : JobFailure

    followed by a popup indicating that powershell has crashed. 

    how should i resolve this?

Help with removing items.

$
0
0

Hello, I'm trying to create a script that takes 3 *. xlsx files looks for "id" matches and updates or adds items as needed.

I'm hung up with the process i have in place to remove the items that have already been updated so that the second part of the script doesn't add any duplicate values or overwrites anything. I've tried a few variations of this however its results have been inconsistent. the bulk of the script works fine its removing the items in $remove that equal items in $UpdateList that seems to be very problematic. 

So this isnt the whole thing but the basic is load 3 .xlsx documents loop through the values in $updatelist that -eq those in $master and update the fields. then i save those updated id's in the $remove array and then loop through that "trying" to remove equal items in the update list. here is the failure if remove and updatelist are exactly the same a error is generated i think it needs a break if updatelist = 0 somewhere. Sometimes in the 2nd half it removes items it shouldnt that are ne.. not entirely sure how that happens but it does. I've confirmed that in the error log with bogus data in the updatefile array.

Maybe there is a better and cleaner way to accomplish this I dont know, any help is appreciated.

$remove = @() ForEach ($u in $UpdateList) { ForEach ($r in $($Master | ? { $_.TemplateKey -eq ($u.Key) })) { $t = $r.Template $t2 = $u.'T#' $c = $r.Comments $r.Template = ($u.'T#') $r.TemplateName = ($u.Resolution) $r.Comments = ("$c`n updated $t to $t2 via -script $date") $item = New-Object PSObject $item | Add-Member -type NoteProperty -Name 'Key' -Value ($u.Key) $remove += $item } } ###remove items that were updated from updatelist foreach ($i in $remove) { if ($i.key -eq $UpdateList.Key) { $rm = $UpdateList.key.indexof($i.key) } $UpdateList.RemoveAt($rm) } $remove = @() ForEach ($u in $UpdateList) { ForEach ($e in $($EAR | ? { $_.TempKey -eq ($u.Key) } | Sort-Object -Property TempKey -Unique)) { ##DO $item = New-Object PSObject $item | Add-Member -type NoteProperty -Name 'ProcessLevel' -Value ($e.Company) $item | Add-Member -type NoteProperty -Name 'CompanyDescription' -Value ($e.CompanyDescr) $item | Add-Member -type NoteProperty -Name 'DeptID' -Value ($e.DeptID) $item | Add-Member -type NoteProperty -Name 'DeptName' -Value ($e.DeptName) $item | Add-Member -type NoteProperty -Name 'JobCode' -Value ($e.JobCode) $item | Add-Member -type NoteProperty -Name 'JobTitle' -Value ($e.JobTitle) $item | Add-Member -type NoteProperty -Name 'Template' -Value ($u.'T#') $item | Add-Member -type NoteProperty -Name 'TemplateName' -Value ($u.Resolution) $item | Add-Member -type NoteProperty -Name 'TemplateKey' -Value ($e.TempKey) $item | Add-Member -type NoteProperty -Name 'Comments' -Value "added per template validations $date -script" $Master += $item $remove += $item.TemplateKey } }

###Remove items that were updated from Updatelist foreach ($i in $remove) { if ($i.key -eq $UpdateList.Key) { $rm = $UpdateList.key.indexof($i.key) } $UpdateList.RemoveAt($rm) } ###Anything left was not found or updated and is error if ($UpdateList.count -gt 0){$UpdateList | Export-Csv -Path $PathUpdate\Errorlog.csv -NoTypeInformation; Write-Host "contains errors see errorlog in $pathupdate\Errorlog.csv"} ###Saves new master document $Master | Export-Excel -Path $PathMaster\"Master."$Date.xlsx


WUA Complex selection...

$
0
0

Using This:.

$msWUASession = New-Object -ComObject "Microsoft.Update.Session"
$msWUASessionSearch = $msWUASession.CreateUpdateSearcher()
$msWUASessionResults = $msWUASessionSearch.Search("IsInstalled=1")
$msWUASessionResults.Updates | Select-Object @{Name="KB";Expression={$_.KBArticleIDs }},@{Name="RevNumber";Expression={$_.Identity.RevisionNumber}},@{Name="UpdateID";Expression={$_.Identity.UpdateID}} | export-csv blablabla...

How do I add (relate) the Updates.Categories found TO EACH UPDATE LISTED in the command before:.

$msWUASessionResults.updates.item(0).Categories | gm
$msWUASessionResults.updates.item(0).Categories | select *

For Identity, in the first command I was able to use the Expression={$_.Identity.UpdateID} but for Categories this doesn`t work, and I also can`t do: .

.

Expression={$_.Categories.Name} #There are 2 of these (how to deal with that Expression={$_.Categories.CategoryID} #There are 2 of these (how to deal with that Expression={$_.Categories.Children} #There are 2 of these (how to deal with that Expression={$_.Categories.Description} #There are 2 of these (how to deal with that Expression={$_.Categories.Type} Expression={$_.Categories.Parent} Expression={$_.Categories.Updates} #There are 2 of these they both return back to the parent using

$msWUASessionResults.Updates.item(0).Categories.Item(0).Updates

Ideas :)




Unable to delete subfolders with PowerShell

$
0
0

We are running PowerShell v 2.0 on Windows 2008 R2 SP1

We have successfully run a command to delete temporary internet files on a file server several times; the command is shown below:

get-childitem -path '\users\*\tempif\local settings\temporary internet files\content.ie5' -recurse -force | where {$_.mode -eq 'd--hs'} | remove-item -recurse

We run the command as administrator with an account that is a member of the local admins group from the root of the drive where the folders are located.  The above command was successfully run at least eight times in the last month but now we get an error saying there is insufficient permissions to remove item or the item cannot be removed because it is not empty.  I can still manually delete the folders in Windows Explorer so it is not a real permissions issue.  The rest of the command runs fine; I can get a list of all the folders and a count of how many of them there are, I simply can no longer delete them in PowerShell.  I can get the Remove-Item command to autofill so it appears I still have access to it.

The security team claims nothing was changed on the servers since we last ran the command five days ago.  Any ideas where I can start looking for what is blocking the delete? 


TBrennan

Script to clean up AD user certificates

$
0
0

We currently have a situation where a large selection of users are receiving multiple certificates from the same source. All the certificates are not expired. We have a legacy script that searches the AD and removes these excess certificates. 

Whilst we diagnose the underlying problem is it possible to have a powershell script that will search the AD user accounts and delete all duplicate user cerificates or deleted all certificates if the certificate count is over a certain number.

If there is any information that can be added to why this may be happening this would also be helpful. 

Thankyou




Netsh command to delete firewall rules

$
0
0

Hi All,

I am looking for powershell script to delete all firewall inbound rules where rule name starts with 'MySql'

e.g. "MySql"

"MySql-5050"

TIA

 


Bulk printer scripts hangs after 1 - 2 printers

$
0
0

Hi all,

I have a bulk printer script, which is performing as expected, however... it hangs after creating 1 or 2 printers

I can wait for minutes, but it won't go on.
If I stop the script, and re-run it, it will jump over the already created ones and will hang after 1 or 2 new ones.

Anyone have any advice ?

Get property of previous command after piping other command

$
0
0

Good morning,

Hopefully there is a simple answer for my question.
When using:

$mailbox = Get-Mailbox | Get-MailboxStatistics

I can only use the properties of Get-MailboxStatistics.
Is there a way to get the properties from Get-Mailbox also in this vaiable?

$mailbox.Name for example?

I know it can be solved with a loop through every mailbox. But I was hoping for a better solution.


ShowUI to Input Text and Output Results

$
0
0

Has anyone worked with ShowUI? I'd like to create a Stackpanel that takes in text that someone would manually input, runs it through the script below after clicking an 'OK' button and outputs the results at the bottom of the stackpanel. Basically plugging in a NetBios name and getting an FQDN. I'm struggling with ShowUI to get this to work.


    {
    $IP = [system.net.dns]::GetHostByName($server).AddressList.IpAddressToString
    $hostname = (nslookup $IP)[3].substring(9)
    $hostname2 = (nslookup $IP)[3].substring(9)
    $hostname2


    }

I'm trying something like this, but I know it's way off. At least, I can't get the output to the bottom of the StackPanel.

New-StackPanel -ControlName 'Servers' {
    New-textbox -Name 'Servers' -AcceptsReturn -AcceptsTab
    New-Button "OK" -On_Click {
    $IP = [system.net.dns]::GetHostByName($server).AddressList.IpAddressToString
    $hostname = (nslookup $IP)[3].substring(9)
    $hostname2 = (nslookup $IP)[3].substring(9)
    $hostname2
    }

    } -Show

Thanks,

Scott

How to filter csv file if heading contains dot

$
0
0

How to filter csv file if heading contains dot, Here is the example for a csv file

Test  test.test

1        A

2        B

3        C

so If I need a line by doing filtering in second column, usually we do like below but it does not work with heading that contains dot

import-csv test.csv | where {$_.test.test -eq 'B'}

I get blank output.


Thanks, Samer

Testing a UNC Path with an ManagedService Account

$
0
0

Hi folks,

Iam using a managed Service Account for starting a Script on one of my Server. Inside the script I use Test-Path (UNC Path on a fileserver).

Always getting back the path don't esxist. For checking purposes I already added the Account in the DomainAdmin group but nothing changed.

Do I need a Manages ServiceGroup account? did't seems logic to me cause the scripts runs on the server and not on the fileserver. I have created the account with the "-RestrictedToSingleComputer" parameter.

With a "normal" user the script runs fine.

Any hints?


Best regards
Andreas Ernst
MCITP:EA, MCP, MCTS


Powershell for a beginner

$
0
0

Help!!!!!!

and hello.

I have a small assignment that I need to complete and have never used powershell.

My teacher has given us a few weeks to complete but has not provided any resources (notes, books, etc) to assist in completion.

So I am left to scour the web for my solution and when i search for powershell help on a beginner level I am finding answers that are way advanced compared to my needs.

I need to find some type of guidance on how to complete this project.

This is the project below.  Any pointers or advice is much appreciated.  

Please don't take this as me asking someone to do it.  I just need some way to start and want to to do this in as simple a way as possible.

Create a Powershell script that will list ONLY the name, size and CreationTime of files in a given directory.  The user should have the option to provide a directory as a command line argument; however, if it is not provided, default the directory to the C:. 

To receive a better grade, the script should add the file sizes for all files from the previous task and print out the total number of bytes.  It should ONLY include files, not directories.

To receive the best grade, format the output so that name, size and creationtime of each file is not truncated or cut off. [ Example: C:\file\file.txt does not show C:\file\f.. ]  The output should be table-like with headers to describe each column of data.  Each column does not have to be the same width as long as each field is readable.  The last line of the output should be the file size summary.

 

Thanks 

iterate XML elements in Powershell

$
0
0

Hello,

I am a newbie in Powershell, so please bear with me on this basic one.

I am working on an XML content and wanted to iterate through each element and map the key - values pairs in each section. For example, I wanted to iterate the value of the Student element and corresponding value of Gender, and then finally check if the student name is Susan, print the Gender as Female.

However when I try using below script, 

The output i get here is :

Susan is Male

Susan is Male

Susan is Female

What could be wrong here? Could someone help me here please?


<?xml version="1.0"?><Objects><ObjectType="System.Management.Automation.CustomObject"><PropertyName="Gender"Type="Application.String">Male</Property><PropertyName="Student"Type="Microsoft.Application.Service">John</Property></Object><ObjectType="System.Management.Automation.CustomObject"><PropertyName="Gender"Type="Application.String">Male</Property><PropertyName="Student"Type="Microsoft.Application.Service">Charles</Property></Object><ObjectType="System.Management.Automation.CustomObject">
<PropertyName="Gender"Type="Application.String">Female</Property><PropertyName="Student"Type="Microsoft.Application.Service">Susan</Property></Object>
</Objects>

Here is the code I am using:

[xml]$file =Get-Content C:\xml-report.xml

foreach($obj in $file.Objects.Object.Property){if('Student'-contains $obj.Name){ $name = $obj.'#text'

}

if('Gender' -contains $obj.Name) {

$gend = $obj.'#text'

}

if ($name = "Susan") {

Write-Host $name "is" $gend

}

}


Viewing all 21975 articles
Browse latest View live


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