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

How to empty recycle bin on remote computers

$
0
0

Hi Team,

I'm trying empty the recycle bin on remote computers. I'm using the following code, it works fine on local machine but not on remote machine. Could somebody help me out?

$Shell = New-Object -ComObject Shell.Application 
$RecBin = $Shell.Namespace(0xA) 
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false



Event Viewer Logs errors from multiple servers

$
0
0

I want to get the event viewer logs from multiple servers .

Here is my code,using this code i want to loop to get the event viewer logs from multiple servers.currently i am geting for only one server while running this script on power shell.

I know how to get the all server's using 

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

foreach($allservers in $computers)

{

}

how i can loop multiple servers with event viewer log messages,where i have to place the logic to run successfully. 

$eventEntries = Get-EventLog Application 

$rows = ""

foreach ($eventEntry in $eventEntries){

if($eventEntry.EntryType.value__ -eq 0 -or $eventEntry.EntryType -eq "Error")
{

If ((New-TimeSpan $eventEntry.TimeGenerated (Get-Date)).TotalMinutes -le 60 )
{

    $rows += @"

    <tr>
        <td style="text-align: center; padding: 5px;">$($eventEntry.TimeGenerated)</td>
        <td style="text-align: center; padding: 5px;">$($eventEntry.EntryType)</td>
        <td style="padding: 5px;">$($eventEntry.Message)</td>
    </tr>
"@
}
}
}

Regards,

Phani.


How to Install Powershell 3.0 in Windows Server 2007

$
0
0

Hi,

Could you please let me know the steps to install Powershell 3.0 in

Windows Server 2007 Ent.

Regards,

How to get/set Share permissions with PowerShell

$
0
0

I have a file server with a bunch of Shares and need to get/set Share perms and inventory stuff.  I've looked at other threads on this forum but there seems to be more than one way to do it.

What I'm trying to do is export to .csv all share names and perms so they can be viewed/edited in Excel, and then use the edited .csv file as input to another script to modify Share perms.

Here's what I've got so far:

$root = "F:\RootDir"
$fldr = Get-ChildItem "$root\*" | Where-Object { $_.PSIsContainer } | Sort $_.PSIsContainer.Name
foreach ($f in $fldr) {
    $acl = get-acl $f.FullName | foreach { $_.Access }
    # do stuff with ACLs
}

The above code seems to enumerate the Shares okay, but what about this:

    $shares = @()
    Get-WmiObject win32_share |
        ForEach-Object { $shares += $_.name.tostring() }
    $shares | Out-String

Are these two blocks of code equivalent?  Why would I use one over the other to enumerate Shares?

And then there's this code from the Hey Scripting Guy Blog

 PROCESS { 
   $input 
   $query = "Associators of {win32_LogicalShareSecuritySetting='$share'}  
   Where resultclass = win32_sid" 
   Get-WmiObject -query $query @RemoteParam |   
   Select-Object -Property @{LABEL="User";EXPRESSION= 
    {"{0}\{1}" -f $_.ReferencedDomainName, $_.AccountName}}, SID  
   } 

which I can't get to work... the script will NOT be run remotely, but rather on the File Server with admin rights.  What does this WMI query do and how can I get it to work locally?

As for *setting* Share perms, AFAIK, I will need to call Icacls.exe from PowerShell. Something like this:

Icacls.exe /G john.smith:F

Or sometimes Everyone would have full perms to the share and NTFS perms would be set on certain subfolders in the Share.  Only the first level of subfolders within the share would be used this way.

What is the best way to get an inventory of Share/subdirectory perms into a .csv that can also be used for input to modify Share/subdirectory perms?

Need help simplifying get-date

$
0
0

I have a script that returns all users from AD who logged in from the last 30 days, but I need to adjust it to make it for the current calendar month. I've got the following code but I could do with some help simplifying it.

$month = (Get-Date -format "MM")
$year = (Get-Date -format "yyyy")

switch ($month)		#if month has less than 31 days
#start switch statement 
{

04 { $myvar = '30' }
06 { $myvar = '30' }
09 { $myvar = '30' }
11 { $myvar = '30' }
02 { if ([datetime]::IsLeapYear($year)){	#if current year is a leap year
	$myvar = '29'
}
	else {
	$myvar = '28'}
	}
}#end switch statement

So $myvar is the variable it uses to query AD users and say Where-Object {$_.LastLogon -le $myvar}. I haven't implemented this code yet but the script works fine at the moment with a variable set to 30 so let's put Active Directory to one side, because this is adapted from the first PS script I ever wrote and is very sloppy. Can anyone help in simplifying it at all?

Thanks in advance

Script against outlook mail box is selecting old data

$
0
0

Hi there,

I am into this project wherein emails pushed into a folder has to be cross checked whether it arrives.

So, to meet this end, I used a powershell script to connect to the mail folder and collect the data.

Add-Type $class -ReferencedAssemblies Microsoft.Office.Interop.Outlook
$class = @"
using Microsoft.Office.Interop.Outlook;public class MyOL
{
    public MAPIFolder GetInbox(string userName)
    {
        Application oOutlook = new Application();
        NameSpace oNs = oOutlook.GetNamespace("MAPI");
        Recipient oRep = oNs.CreateRecipient(userName);
        MAPIFolder inbox = oNs.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderInbox);
        return inbox;
    }
}
"@
Add-Type $class -ReferencedAssemblies Microsoft.Office.Interop.Outlook

$MyOL = New-Object MyOL
$olInbox = $MyOL.GetInbox("mailbox")

$olInbox.items | Select-Object -Property Subject, ReceivedTime, Importance, SenderName

but this code is collecting only a week old data! I did try a bit of looking around and found that this can be related to the indexes in the mailbox. So, I have tried disabling that as well but in vain.

Please can someone help me on this.

Powershell Command lastlogon has "Null"

$
0
0

Hi All,

We had a requirement to find out the users, who are created but never logged on to any machines. Such users we need to disabled

I have tried the below command, but it didn't work. Also i tried to configure the below command via scheduled task, gaves an error.

Request you to please help me in correcting the commands and for configuring the scheduled task.

Search-ADAccount-AccountInactive-TimeSpan([timespan]10d)-UsersOnly|Set-ADUser-Enabled $false -WhatIf


Thanks HA

Bug Powershell/PSExec - Missing Information outside ISE

$
0
0
I´m affected of this Bug in Powershell/PSExec

http://stackoverflow.com/questions/22593651/powershell-psexec-job

Executing powershell script and execute for example ping/tracert/iperf
via psexec on remote-hosts is working very well. 

In ISE I see all the Information I expect. But I´m the interesting information is missing outside ISE.

For example in ISE:

#####################################
PS C:\Scripts> .\tracert.ps1 -ComputerName REMOTEHOST -target TARGETHOST
PsExec v2.1 - Execute processes remotely
Copyright (C) 2001-2013 Mark Russinovich
Sysinternals - www.sysinternals.com

Starting tracert.exe on REMOTEHOST...REMOTEHOST...
tracert.exe exited on REMOTEHOST with error code 0.
From REMOTEHOST to TARGETHOST <br>
Routenverfolgung zu TARGETHOST [200.100.100.1]  über maximal 30 Abschnitte:
  1    74 ms    <1 ms    <1 ms  100.100.100.5
  2    <1 ms    <1 ms    <1 ms  Router1 [120.12.245.101]
  3     1 ms    <1 ms    <1 ms  Router2 [130.12.246.101]
  4     1 ms    <1 ms    <1 ms  Router3 [150.12.247.101]
  5     1 ms    <1 ms    <1 ms  TARGETHOST  [200.100.100.1]
Ablaufverfolgung beendet.
#####################################


Fine? NO!!!

Write to File, Print,execute the Script via IIS/PHP everything fails!
Only this Information outside ISE:

#####################################
C:\scripts\tracert.ps1 -ComputerName REMOTEHOST  -target TARGETHOST
From REMOTEHOST  to TARGETHOST 

Routenverfolgung zu TARGETHOST [200.100.100.1]  über maximal 30 Abschnitte:

#####################################

PLS HELP!!!
Invoke-Command cannot be used here


BUG - Powershell/PSExec - Missing Information outside ISE

$
0
0
I´m affected of this Bug in Powershell/PSExec

http://stackoverflow.com/questions/22593651/powershell-psexec-job

Executing powershell script and execute for example ping/tracert/iperf
via psexec on remote-hosts is working very well. 

In ISE I see all the Information I expect. But I´m the interesting information is missing outside ISE.

For example in ISE:

#####################################
PS C:\Scripts> .\tracert.ps1 -ComputerName REMOTEHOST -target TARGETHOST
PsExec v2.1 - Execute processes remotely
Copyright (C) 2001-2013 Mark Russinovich
Sysinternals - www.sysinternals.com

Starting tracert.exe on REMOTEHOST...REMOTEHOST...
tracert.exe exited on REMOTEHOST with error code 0.
From REMOTEHOST to TARGETHOST <br>
Routenverfolgung zu TARGETHOST [200.100.100.1]  über maximal 30 Abschnitte:
  1    74 ms    <1 ms    <1 ms  100.100.100.5
  2    <1 ms    <1 ms    <1 ms  Router1 [120.12.245.101]
  3     1 ms    <1 ms    <1 ms  Router2 [130.12.246.101]
  4     1 ms    <1 ms    <1 ms  Router3 [150.12.247.101]
  5     1 ms    <1 ms    <1 ms  TARGETHOST  [200.100.100.1]
Ablaufverfolgung beendet.
#####################################


Fine? NO!!!

Write to File, Print,execute the Script via IIS/PHP everything fails!
Only this Information outside ISE:

#####################################
C:\scripts\tracert.ps1 -ComputerName REMOTEHOST  -target TARGETHOST
From REMOTEHOST  to TARGETHOST

Routenverfolgung zu TARGETHOST [200.100.100.1]  über maximal 30 Abschnitte:

#####################################

PLS HELP!!!
Invoke-Command cannot be used here

cpu utilization command in powershell

$
0
0

Hi All,

I want to get the CPU Utilization Percentage from my system.

 when i am using this command

  $DateTime =Get-Date-Format G
        $ProcessorPercentage =(Get-WmiObjectWin32_PerfFormattedData_PerfOS_Processor-ComputerName $Server -filter "Name='_Total'").PercentProcessorTimeWrite-Output"$Server $DateTime`: $ProcessorPercentage"

using this script i am  getting some value,But it is not the exact value  same as in  Task Manager Performance Tab.

Can any one help on this..

Regards,

Phani Kumar R.

Starting / Stoping an FTP site using PowerShell... IIS 7.5 on 2008R2

$
0
0

Hi, so I want to automate / build functions with PowerShell to interact with IIS 7.5! I done some reading and come to the conclusion (if I am not mistaken) that I should be able to administer / script the FTP server with the cmdlets that are contained in the WebAdministration module. So, for example if I want to stop() an already existing FTP site <MyCustomFtpSite> I run the following code:

Stop-WebSite -Name MyCustomFtpSite

Generates error: (Stop-Website : The object identifier does not represent a valid object) and I can ensure that the site is there....

If I do another way of binding to the site, as below:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration") | Out-Null
$iis = New-Object Microsoft.Web.Administration.ServerManager
$iisTargetSite = $iis.sites["MyCustomFtpSite"]
$iisTargetSite.Stop()

Generates the following error:
Exception calling "Stop" with "0" argument(s): "The object identifier does not represent a valid object. (Exception fro
m HRESULT: 0x800710D8)"

And finally, should be able to do it the following way as well (according to me, but hey, who knows...):

$objDesiredWebSite = Get-WebSite | Where {$_.Name -eq "MyCustomFtpSite"}
$objDesiredWebSite.Stop()

Generates error: The object identifier does not represent a valid object. (Exception from HRESULT: 0x800710D8)

To be honest, what am I missing? I dont understand... previously I got an error saying that the "WAS" service could not be detected. So I installed additional components of the IIS server which lead me to the next error msg shown above... I dont get it! I know I am slow, but altering configuration with PowerShell is normally a lot easier than this....

I would be much happier if anyone could point in the right direction on what I am missing or what I need to add! I sure hope it is something silly....


br4tt3

Read the content of a properties file

$
0
0

I have a properties file(.properties), which has contents in this format:-

[1]TYPE=4
[1]ENABLED=TRUE
[1]Caption = "Kozos"
[1]URL=https://kozos.com/access

I want to display the value of url for kozos and when i try below code, i get an error :- 

ConvertFrom-StringData : Data line 'D:\kozos.properties' is not in 'name=value' format. 

Clear-host
$FileName = "D:\kozos.properties"
$file_content = $FileName -join [Environment]::NewLine
$configuration = ConvertFrom-StringData($file_content)
$environment = $configuration.'kozos'
Write-host "Environment is $environment"


Find folders with an extension older than 2 weeks

$
0
0

The helpdesk where I'm at likes to take the nuclear option of troubleshooting and as a first step wipe out a user's profile. They've been reprimanded enough times that they're not actually deleting a profile, but they're renaming it to the original name+ their initials as an extension.

At this point in time we have enough folders named "jones.JQS" or "smith.GNM" that they're taking up a lot of space and I need to delete them, and would like to start deleting them automatically. Here's what I'd like to do:

1) find all folders that have an extension. Doesn't matter what it is, just has to be a folder and an extension has to exist

2) of those folders, find ones older than 2 weeks

I'm drawing a blank on how to list all folders that have an extension. "gci | select-object extension | ... ?"

Thanks


zarberg@gmail.com

Calling a Function Within a For-Each in Powershell

$
0
0

Error:

Unexpected token 'in' in expression or statement.
At :line:1 char:22
+ ForEach-Object ($i in  <<<< $fs_size_info) { $i.Name.Name, GetGB($i.Sum)  }


Code:

foreach ($i in $fs_size_info) { $i.Name.Name GetGB($i.Sum) }

If I omit the function from inside this foreach, it works perfectly, and I can access $i.Sum within the foreach as well. The problem arises when I try to call a function from inside the foreach. GetGB simply returns a more readable format e.g. GetGB(1024) will return "1 K" etc...

I don't understand what I'm doing wrong, unless you cannot call a function inside a foreach statement.... am I missing something?

Thanks

Windows 2008 R2 Print Server DRP

$
0
0

Hi all, I have two servers Windows 2008 R2 with the print server rol on different sites.

One of the server is productive and has around 600 printers and the second one should be the DRP server on another data center.

I need a way to synchronize the changes from the productive server (add, remove or queues and drivers changes) to the DRP server.

I tried to make a backup and do a restore on the DRP server but it's a very large file to transfe from one data center to another, is posible to create a script to keep the changes up to date on the DRP server or do I use any application to do that?

Thanks in advance

Fer


PS: Set-ADAccountPassword - Complexity Exception

$
0
0

I've got problems with setting new passwords via Powershell on Server 2012 R2:

Set-ADAccountPassword -Identity testuser48 
-OldPassword (ConvertTo-SecureString -AsPlainText "HelloPassword123#" -Force)
-NewPassword (ConvertTo-SecureString -AsPlainText "April456#@123" -Force)

I tried many different passwords but there's always an ADPasswordComplexityException.

FullyQualifiedErrorId : ActiveDirectoryServer:1325,Microsoft.ActiveDirectory.Management.Commands.SetADAccountPasword


Are there any other things I could try? All password complexity rules (incl. length, ...) are disabled.


replace character to spaces in different position

$
0
0

Hello, i have a lot of txt files with this content:

ER-MD122-20150           001001/    0A0126070320120228I01A4
ER-MD129-20151           001001/    0A0126070320120228I01A4
ER-MD129-20152           001001/    0A0126070320120228I01A4
ER-MD129-20153           001001/    0A0126070320120228I01A4
ER-MD129-20154           001001/    0A0126070320120228I01A4

the three block are separate by multiple spaces.

I need to parse every lines in txt and remove the non numeric characters  at the beginning of line(in this case 5 character ER-MD). The number of non-numeric character may vary in other files.
Then i need to insert between first and second block a number of spaces equivalent to the characters removed earlier.

The file shouls appears:

129-20150                001001/    0A0126070320120228I01A4
129-20151                001001/    0A0126070320120228I01A4
129-20152                001001/    0A0126070320120228I01A4
129-20153                001001/    0A0126070320120228I01A4
129-20154                001001/    0A0126070320120228I01A4

between first (129-20150) and second block (001001/) five whitespaces are been added.

It is possible in powershell?

Thank you in advance



DFSN Module Update

$
0
0

I'm running DFS Servers on Server 2012 and would like to take advantage of some of the new cmdlets provided by DFSN 2012 R2 Under Powershell 4.0. I am unable to upgrade to 2012 R2 at this time, apart from installing Powershell 4.0, is there a clean way to upgrade the DFSN module for powershell and remain at 2012? 

Particularly, I'd like to be able to modify DFS Replication Group membership with commands such as Add-DFSrMember

Thanks for any help.

Create IIS AppPool with Powershell?

$
0
0

Using Powershell 4 and IIS 7.5.  Would like to do the following:

1. Create AppPool XYZ if does not exist

2. Create Web App ABC using AppPool XYZ if ABC does not exist

How do you check if IIS AppPool / Web App exists in Powershell 4?

thanks


Start Up Paths in Windows Powershell

$
0
0

Hello,

I have a novice question. I have three environments(dev,qa,prod) and would like to manage paths so that hard-coding is minimal. The directory structure for the three environments is identical. I have paths to manage like:

\\domain\somecompany\PRD\XXX

\\domain\somecompany\QA\XXX

\\domain\somecompany\DEV\XXX

I thought I might put the environment path in one file globals.ps1 that was dot sourced from the current directory. Thus this file might for DEV set a variable holding the path 

\\Domain\somecompany\DEV

Then I thought I could control the current directory by putting an entry in the profile for the user. In all subsequent scripts I would only need to dot source 

As a first test on my local machine I tried something like this:

1. Set the Powershell startup directory to a starting script directory by adding the following to $profile. 

Set-Location "C:\my script directory"

2. In "c:\my script directory" I have a script Globals.ps1 that (in theory would hold all the other paths but at present) sets one variable holding a path

$RootPath = "C:\some\other\path"

3. Also in "c:\my script directory" I have a script called GlobalsTest.ps1 that contains:

.\Globals.ps1 
Write-Host $MyPath\test.txt

Instead of getting  the output "c:\some\other\path\test.txt" I get "\test.txt". If I take the quotes off in the defintion of $MyPath I get an error. What am I missing?

Thanks in advance


Viewing all 21975 articles
Browse latest View live


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