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

Finding odd and even numbers

$
0
0

I have created a script that will put a collection into a html table and send it in an eamil. I would like to add an alternating color for each table row in the html table. I am building the table and each row by looping through a collection and have added $LoopCount++ count each time the loop is started. I want to use the $LoopCount++ to generate a number and based on the number being odd or even i will update the <tr "bgcolor='7FA96F'"> tag. I am not married to this method but it was the only way i could think of to get alternating colors. I am missing the logic to find out if the loopcount is an odd or even number. Any ideas would help...

FOREACH($Item in $SortedMBXProps)
 { 
  $LoopCount ++
  ## Change to color 1
  IF($LoopCount -eq "True")
   {
   $list += "<tr bgcolor='7FA96F'>"
   }
   ## Change to color 2
    ELSE
    {
    $list += "<tr bgcolor='FFFFFF'>"
    }
  $list += "<td>" + $Item.DisplayName + "</td>"
  $list += "<td>" + $Item."IssueWarningQuota(MB)" + "</td>"
  $list += "<td>" + $Item."TotalItemSize(MB)" + "</td>"
  $list += "<td>" + $Item."ProhibitSendQuota(MB)" + "</td>"
  $list += "<td>" + $Item.StorageLimitStatus + "</td>"
  $list += "<td>" + $Item.ServerName + "</td>"
  $list += "</tr>"
 }
$list += "</table></font>"

PowerShell Workflow Issue?

$
0
0

Hello,

I am having an issue passing a variable from one workflow to another. If I use a hard-coded variable, it seems to work without issue. Basically, I have two workflows: one that grabs information about the user from Active Directory, and the other that updates a SharePoint list based on that returned data. Below are my scripts:

Workflow Get-User {

    param(
        [string]$SamAccountName
    )

    $DomainController = Get-AutomationVariable -Name "Domain Controller"
    $Credentials = Get-AutomationPSCredential -Name "Administrator"

    $User = InlineScript {
        Get-ADUser -Filter { SamAccountName -eq $Using:SamAccountName }
    } -PSComputerName $DomainController -PSCredential $Credentials

    $ObjectGUID = $User.ObjectGUID

    Update-Employee -ObjectGUID $ObjectGUID -TelephoneNumber "+12312345678"

}


workflow Update-Employee {
    param(
        [string]$ObjectGUID,
        [string]$TelephoneNumber
    )

    $SharePoint = Get-AutomationVariable -Name "SharePoint"
    $Credentials = Get-AutomationPSCredential -Name "SharePoint Farm"

    inlinescript {
        Add-PSSnapin Microsoft.SharePoint.PowerShell

        $Web = Get-SPWeb -Site http://sharepoint
        $List = $Web.Lists["List"]
        $Item = $List.Items | Where-Object {$_['Object_x0020_GUID'] -eq $Using:ObjectGUID}
        $Item["Work_x0020_Phone"] = $Using:TelephoneNumber
        $Item.Update()
        $Web.Dispose()

    } -PSComputerName $SharePoint -PSCredential $Credentials -PSAuthentication CredSSP
}

When I run...

Get-User -SamAccountName jdoe

I receive the following error:

"Cannot index into a null array"

Any help?

Windows Update PowerShell Script

$
0
0

Hi All 

I have this Windows update Powershell script below which works pretty much fine. I would like to add a csv file that will contain multiple Serves and do the updates on them. The issue is getting the script to get the machines name from the CSV file and and update it based on the CSV file. Can anyone assist on this matter.

$UpdateSession = New-Object -Com Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
 
Write-Host("Searching for applicable updates...") -Fore Green
 
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")
 
Write-Host("")
Write-Host("List of applicable items on the machine:") -Fore Green
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    Write-Host( ($X + 1).ToString() + "&gt; " + $Update.Title)
}
 
If ($SearchResult.Updates.Count -eq 0) {
    Write-Host("There are no applicable updates.")
    Exit
}
 
#Write-Host("")
#Write-Host("Creating collection of updates to download:") -Fore Green
 
$UpdatesToDownload = New-Object -Com Microsoft.Update.UpdateColl
 
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    #Write-Host( ($X + 1).ToString() + "&gt; Adding: " + $Update.Title)
    $Null = $UpdatesToDownload.Add($Update)
}
 
Write-Host("")
Write-Host("Downloading Updates...")  -Fore Green
 
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Null = $Downloader.Download()
 
#Write-Host("")
#Write-Host("List of Downloaded Updates...") -Fore Green
 
$UpdatesToInstall = New-Object -Com Microsoft.Update.UpdateColl
 
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    If ($Update.IsDownloaded) {
        #Write-Host( ($X + 1).ToString() + "&gt; " + $Update.Title)
        $Null = $UpdatesToInstall.Add($Update)        
    }
}
 
$Install = [System.String]$Args[0]
$Reboot  = [System.String]$Args[1]
 
If (!$Install){
    $Install = Read-Host("Would you like to install these updates now? (Y/N)")
}
 
If ($Install.ToUpper() -eq "Y" -or $Install.ToUpper() -eq "YES"){
    Write-Host("")
    Write-Host("Installing Updates...") -Fore Green
 
    $Installer = $UpdateSession.CreateUpdateInstaller()
    $Installer.Updates = $UpdatesToInstall
 
    $InstallationResult = $Installer.Install()
 
    Write-Host("")
    Write-Host("List of Updates Installed with Results:") -Fore Green
 
    For ($X = 0; $X -lt $UpdatesToInstall.Count; $X++){
        Write-Host($UpdatesToInstall.Item($X).Title + ": " + $InstallationResult.GetUpdateResult($X).ResultCode)
    }
 
    Write-Host("")
    Write-Host("Installation Result: " + $InstallationResult.ResultCode)
    Write-Host("    Reboot Required: " + $InstallationResult.RebootRequired)
 
    If ($InstallationResult.RebootRequire -eq $True){
        If (!$Reboot){
            $Reboot = Read-Host("Would you like to install these updates now? (Y/N)")
        }
 
        If ($Reboot.ToUpper() -eq "Y" -or $Reboot.ToUpper() -eq "YES"){
            Write-Host("")
            Write-Host("Rebooting...") -Fore Green
            (Get-WMIObject -Class Win32_OperatingSystem).Reboot()
        }
    }
}

get-process commonparameters

$
0
0

Windows 7

The cmdlet get-process has the option [<commonparameters>] 

How do I determine what those options are?

get-help get-process -commonparameters is not valid.  A google search tell me many things I am not looking for but not the ones I need.  A tutorial I found does not address this.


~jag77 We need to know what a dragon is before we study its anatomy. (Bryan Kelly, 2010)

Issue in looping through drives and servers

$
0
0

I'm trying to write a script which scan through all the drives and find old files with specific extension on the list of servers which I pass in servers.txt. Please find below the errors and the script which I executed. Can anyone suggest 1) why it is checking in my local desktop drive rather than server listed in servers.txt.2) How to pass a value to a variable :$diskname="\\$strComputer$\$disk$"

Error Message 

starting
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At C:\Documents\oldfiles_new.ps1:29 char:25
+    $time = ((Get-Date) - <<<<  $file.CreationTime).Days 
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

\\.$\\\local_host\root\cimv2:Win32_LogicalDisk.DeviceID="D:"$
Compiling list, this could take a while.
Get-ChildItem : Illegal characters in path.
At C:\Documents\oldfiles_new.ps1:25 char:23
+ $files = get-childitem <<<<  $diskname -Include *.trn,*.bak -recurse  
    + CategoryInfo          : InvalidArgument: (\\.$\\\ACWIN-MG....DeviceID="D:"$:String) [Get-ChildItem], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand

------------------------------------------------

Script which I executed:

function oldfiles {

Param( 
    [alias("f")] 
    $outfile, 
    [alias("a")] 
    $maxage, 
    [alias("d")] 
    [string] $strComputer) 
 
#If a parameter was not specified, set a defualt 
if (!($strComputer)) {$strComputer = "."} 
if (!($outfile)) {$outfile = "C:\Documents\oldfiles.csv"} 
if (!($maxage)) {$maxage = 10} 
#param( [string] $strComputer) 

    # Get the Disks for this computer
    $colDisks = get-wmiobject Win32_LogicalDisk -computername $strComputer -Filter "DriveType = 3"
    
foreach ($disk in $colDisks) {
$diskname="\\$strComputer$\$disk$"
$diskname
Write-host "Compiling list, this could take a while." 
$files = get-childitem $diskname -Include *.trn,*.bak -recurse  
"File Name `t Age in Days " | out-file $outfile 
write-host "starting" 
foreach ($file in $files) { 
   $time = ((Get-Date) - $file.CreationTime).Days 
#$totalSize = {($file).Length -gt 5kb }
   if ($time -gt $maxage -and $file.PSiSContainer -ne $True) {"$($file.FullName) `t $time `t" | out-file -Append $outfile}  
   } 
}
}
foreach ($computer in cat C:\Documents\servers.txt) {oldfiles $strcomputer}

Any help would be appreciated

Thanks

Run Powershell script from Scheduled Task as "NT Authority \ SYSTEM"

$
0
0

Hello, dear Colleagues.

Cannot make Powershell script from Scheduled Task as "NT Authority \ System"

Action: Start a program - 

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "C:\script.ps1"

The matter is that script is working, moreover if to run Task with Domain Account it works too.

Checked Run with highest privileges, changed "Configure for" field, tried different arguments (-noprofile, -noexit, -executionpolicy bypass, -command, -file,") - no luck.

Didn't you try to make it work with SYSTEM account?

Thanks.

Sum Columns using Powershell

$
0
0

I have written the following PowerShell script for getting disk space information for servers in our environment.

$servers = Get-Content E:\POC.txt
$array = @()
foreach($server in $servers){
    $sysinfo =  Get-WmiObject Win32_Volume -ComputerName $server
    for($i = 0;$i -lt $sysinfo.Count; $i++){
        $sname =  $sysinfo[$i].SystemName
        $servername = $server
        $label = $sysinfo[$i].Label
        if(($label) -and (!($label.Contains("FILLER")))){
            write-host "Processing $label from $server"
            $name = $sysinfo[$i].Name
            $capacity = [math]::round(($sysinfo[$i].Capacity/1GB),2)
            $fspace = [math]::round(($sysinfo[$i].FreeSpace/1GB),2)
            $sused = [math]::round((($sysinfo[$i].Capacity - $sysinfo[$i].FreeSpace)/1GB),2)
            $fspacepercent =  [math]::Round((($sysinfo[$i].FreeSpace*100)/$sysinfo[$i].Capacity),2)
            $obj = New-Object PSObject
            $obj | Add-Member -MemberType NoteProperty -Name "SystemName" -Value $sname
            $obj | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $server
            $obj | Add-Member -MemberType NoteProperty -Name "Label" -Value $label
            $obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $name
            $obj | Add-Member -MemberType NoteProperty -Name "Capacity(GB)" -Value $capacity
            $obj | Add-Member -MemberType NoteProperty -Name "FreeSpace(GB)" -Value $fspace
            $obj | Add-Member -MemberType NoteProperty -Name "Used(GB)" -Value $sused
            $obj | Add-Member -MemberType NoteProperty -Name "FreeSpace%" -Value $fspacepercent
            $array += $obj
        }
    }
    $array += write-output " "
    $totalSize = ($array | Measure-Object 'Capacity(GB)' -Sum).Sum
    $array += $totalsize
    $array += write-output " "
}
$filename = "E:\VolumeReport.csv"
$array |  Export-CSV $filename -NoTypeInformation
One additional requirement here is to get the sum of the columns for Capacity, Size and Freespace for each server. I tried using Measure-Object but no success. No values are getting outputted here. Just blank. Please look into this and kindly assist. Only Sum output is coming blank, rest everything is fine.

Remoting and localized output from executables

$
0
0

Hello all, I am in need of a bit of assistance.

We have client computers which have non-English Windows 7, and thus any executable that produce output produce non-English output. This is not a problem when using PowerShell locally, all localized output is displayed properly.

Problems arise when using PowerShell remoting, where output does not display non-English characters correctly. Examples of native executables which produce incorrect output: ipconfig, ping, wingmmt.

Host's output encoding:
IsSingleByte      : True
BodyName          : ibm850
EncodingName      : Western European (DOS)
HeaderName        : ibm850
WebName           : ibm850
WindowsCodePage   : 1252
IsBrowserDisplay  : False
IsBrowserSave     : False
IsMailNewsDisplay : False
IsMailNewsSave    : False
EncoderFallback   : System.Text.InternalEncoderBestFitFallback
DecoderFallback   : System.Text.InternalDecoderBestFitFallback
IsReadOnly        : True
CodePage          : 850

Remoting output encoding:
IsSingleByte      : True
BodyName          : iso-8859-1
EncodingName      : Western European (Windows)
HeaderName        : Windows-1252
WebName           : Windows-1252
WindowsCodePage   : 1252
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
EncoderFallback   : System.Text.InternalEncoderBestFitFallback
DecoderFallback   : System.Text.InternalDecoderBestFitFallback
IsReadOnly        : True
CodePage          : 1252

Following command can be run to change console output encoding to UTF8:
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

However, running this on remote session will result in "Exception setting "OutputEncoding": "The handle is invalid." Running this on host works, but has no effect on remote session.

Apparently $OutputEncoding only works for input, not output. But I tried to set it to UTF8 anyway, with no effect.

This problem does not affect PowerShell cmdlets, as Write-Host and Write-Output produce correct output even in remote session.

Previously host had PowerShell 3 and client had PowerShell 2, now both have PowerShell 4 and problem still persists.

Anyone know how I can receive correct output from localized native executables? Thanks in advance.



List processes in a Loop

$
0
0

Hello,

I'm looking for a way to list the processes on my client with a delay of 2 seconds for each process. This is the reason why I cannot use Get-Process. Maybe as a do oder foreach loop.

Greetings
Uemit

Learn how to use Powershell with AD, Exchange and Excel

$
0
0

Hi.

I want to learn how to script in Powershell to make my life easier at work.

Now, I'm creating Distribution Lists with cmdlets, and other simple moves, but I'd like understand and use scripts with Excel to make it easier in AD and Exchange.

Can anyone help me find out where I can learn Powershell with those tools? I've searched google and youtube, and bought books, but I'd like to learn especially about AD and Exchange through Excel.

I also have another question, I'm trying to collect the telephonenumbers in one OU in AD, and found this cmdlet:

Get-AdUser -Filter * -Properties OfficePhone | FT OfficePhone,UserPrincipalName

I lined ut the OU path before -Filter, and used * -Properties Telephones Mobile to find the phonenumber in Properties-Telephones-Mobile in Active Directory. But I'm obviously doing something wrong.

Could anyone please help me? 

 

Using Powershell to update AD Users staring from a CSV

$
0
0

Hi!

i need to update a list of AD Users and change for all of them the same attribute with the same value.

i have a csv containing just the list of users cn, ho can i make the query on this attribute?

I start to build the command and i've something like that:

$USERS = Import-CSV C:\Users\Users2.csv

$USERS | Foreach{Get-ADUser-filter {cn-eq $_.name} |Set-ADUser -replace @{info=""}

but i got the following error for every entry in the csv:

Get-ADUser : Property: 'name' not found in object of type:
'System.Management.Automation.PSCustomObject'.
At line:1 char:18
+ $USERS | Foreach{Get-ADUser -filter {cn -eq $_.name}}
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentExcep
   tion
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,M
   icrosoft.ActiveDirectory.Management.Commands.GetADUser

something wrong for the filter in the command, someone can help?

Thanks!

Schedule IISreset at specific time on powershell

$
0
0
How to Schedule IISreset at specific time on powershell without manual intervention?

Change property type for an existing object

$
0
0

Hello,

is there a way to change the property type for an existing object ?

for example, i have this object:

[pscustomobject]$Object = @{
    Name = 'Marius'
    Age = 34
    Cars = 'Ford','BMW'
}

"Cars" property type is Array - can i change it to string ? or any other type ?

Thanks,
Marius


Exchange PS to get info with Variable

$
0
0

I am trying to pull some information for an O365 migration.

This command works fine:
get-mailbox -Filter {windowsemailaddress -eq "saorders@domain.com"} | fl windowsemailaddress, primarysmtpaddress

and returns the expected result.  I am going to use a CSV to make a variable for several email addresses.  For right now I hard coded a variable for simplicity:

$UPN = "saorders@domain.com"

If I plug that in:
get-mailbox -Filter {windowsemailaddress -eq "$UPN"} | fl windowsemailaddress, primarysmtpaddress

I get the following error:

Invoke-Command : Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "The value "$upn" could not
be converted to type Microsoft.Exchange.Data.SmtpAddress."
At C:\Users\a_mscott\AppData\Roaming\Microsoft\Exchange\RemotePowerShell\usp306.domain.com\usp306.domain.com.psm1:13613 char:
29
+             $scriptCmd = { & <<<<  $script:InvokeCommand `
    + CategoryInfo          : WriteError: (:) [Get-Mailbox], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetMailbox

What syntax do I need to use in this case to use a variable there?


Mark


Executing powershell scripts via Task Scheduler

$
0
0

Hi,

I have a powershell script that I wrote that when executed from the shell works fine but when executed from task scheduler does not work.

In my script, an email is sent out based on the results of the execution.  When I run this from the shell, email goes out, when scheduled, no email and there is no indication of errors having occurred anywhere in the system.

Has anyone run into a similar issue?

I did change my powershell execution policy to be unrestricted (both in the x86 and x64 consoles).  I am running Windows 2008 R2.

Thanks - Greg.


How to exclude results in a XML event viewer filter.

$
0
0

Hello, Im trying to create a custom filter to return only files that are deleted. Problem is I do not care about .tmp files created and removed by MS Office. How can I exclude any result that has an "ObjectName" which contains ".tmp"?

My Filter looks like this right now. Can someome help me? This returns all deleted items including the .tmp ones.

<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
    *[EventData[Data[@Name='AccessMask'] and (Data='0x10000')]] and
    *[EventData[Data[@Name='ObjectName'] and (Data!='.tmp')]]
    </Select>
  </Query>
</QueryList>

Grant change(write) permissions to an already existing bulk shares folder

$
0
0

Hello,

We had a server crash (Windows 2003) and I had to bring it up on new VM.  I have used net share to create my shares, however after doing so, the share permissions for "Everyone" are only set to read.  What I need to do is modify the current folders so "Everyone" has read/write access. 

net share    SHARENAME$=''\\servername\d$\folder_path\folder_path\FOLDERtoSHARE''   

Above is the command I used. How would I grant "Everyone" read/write permissions.  I guess now the question is how do I grant CHANGE (write) permissions to "Everyone" since they can all view their folders, but cannot add to or edit them.

Currently I have to go to the properties of each folder, click Sharing, the Permissions and edit "Everyone" permissions to read/change.  I have a lot of folders and this could take awhile doing it manually.  I know I'm close, just cant find the right syntax.

Please help!

Thanks

Cheston

Waiting on job status

$
0
0

Hey guys!  I am writing a script that will back up our Hyper-V machines.  I want to do them at the same time but then wait for them all to be done...I'll need to move the files when they are finished. 

My question is, will this work?  I haven't tested it but I think it should show you the general idea of what I want.  I need to store the jobs in an array...then loop through the array waiting for them all to be finished or failed, anything but running.  Does the following code look ok?

Remove-Item "C:\Backup\*" -Recurse

$jobs[0] = Export-VM -Name COMPANYWEB -Path "C:\Backup" -AsJob
$jobs[1] = Export-VM -Name TFSDeploy -Path "C:\Backup" -AsJob
$jobs[2] = Export-VM -Name OldVSS -Path "C:\Backup" -AsJob
$jobs[3] = Export-VM -Name MattBuild -Path "C:\Backup" -AsJob
$jobs[4] = Export-VM -Name PSR -Path "C:\Backup" -AsJob
$jobs[5] = Export-VM -Name XPPortal -Path "C:\Backup" -AsJob

$done = true
do
{
    for ($i = 0; $i -le 6; $i++)
    {
        if ($jobs[$i].status -eq "Running")
	    $done = false
    }
} while ($done -eq false)



Where-Object error.

$
0
0

I am querying AD and want to add some conditions.   I have been playing with several conditions that work for me but this one I can't figure out.

Can anyone tell me why this does not work?

Where-Object { $_.DisplayName -contains '$' }

And this does work.

Where-Object { $_.DisplayName -contains '_' }

I have tried various methods to escape the $ with no good result.  I have researched the "gotcha's but nothing is working.  Backslash, back tick, double quotes, single quotes.  

Error:  You cannot call a method on a null-valued expression.

Using compare-object to check ACLs on two sets of folders

$
0
0

In preparation of moving away from Win 2003, I've been asked to compare ACLs on two servers with identical directory structures. I came up with the following:

function Compare-ACLs {
    Param(
        [string]$Path1 = "Path1",
        [string]$Path2 = "Path2"
        )

        $folders_path1 = gci -Directory $Path1 -Force | get-acl
        $folders_path2 = gci -Directory $Path2 -force | get-acl
        compare-object $folders_path1 $folders_path2 -IncludeEqual
                    }

However, when I run it I get an output that is giving me the object type:

InputObject                                                                                          SideIndicator
-----------                                                                                          -------------
System.Security.AccessControl.DirectorySecurity                                                      ==
System.Security.AccessControl.DirectorySecurity                                                      ==
System.Security.AccessControl.DirectorySecurity                                                      ==
System.Security.AccessControl.DirectorySecurity                                                      ==
System.Security.AccessControl.DirectorySecurity                                                      ==
System.Security.AccessControl.DirectorySecurity                                                      ==                      

Is there a way for me to show the folder of the InputObject, or is that impossible given get-ACLs limitations?

Thank you.


zarberg@gmail.com

Viewing all 21975 articles
Browse latest View live


Latest Images

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