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

Custom stuff... in a Table

$
0
0

Hi All,

I created a powershell script to check every 60 seconds the counts of Move requests on O365... It works exactly how I want it to... but it's in a list based format...

So output would show:

Autosuspended: 1
Completed: 2
Failed:3

And so on... and every 60 seconds it would just post it again.  Now this works, but I would rather want my output in a table format.  Like this: (Ok so the website screws this up, but it's a table format)

Run Date: AutoSuspended: Completed:Failed:
================================================

10/06/2014 10:00:00 1 2 3

10/06/2014 10:01:00 2 2 1

and so forth... so every time it runs, it just adds a new row...

Could anyone help me with that sort of formatting?

This is the script:

param($Work)

# restart PowerShell with -noexit, the same script, and 1
if (!$Work) {
    powershell -noexit -file $MyInvocation.MyCommand.Path 1
    return
}



#PARAMETERS:
    Write-Host
    echo 'ENTER USERNAME: (Exchange Online tenant administrator):'
    $username = read-host

    echo 'ENTER PASSWORD: '
    $password = read-host -assecurestring

#CONNECT TO O365
    $UserCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
    Write-Host "CONNECTING..." -Foregroundcolor Yellow
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
    Import-PSSession $Session

#HEADER
    $Host.UI.RawUI.WindowTitle = "Exchange Online: Get-Move-Queue-Counts"
    Write-Host "=========================================================================================================" -ForegroundColor Yellow
    Write-Host "NAME:           Exchange Online: Get-Move-Queue-Counts" -Foregroundcolor Yellow
    Write-Host "REFRESH RATE:   60s"
    Write-Host "=========================================================================================================" -ForegroundColor Yellow

        
    function GetStats
    {
    Write-Host $RunDate "> Running " Get-Date -ForegroundColor Cyan
    [Int] $intAutoSuspended = $intCompleted = $intCompletedWithWarning = $intCompletionInProgress = $intFailed = $InProgress = $intNone = $intQueued = $intSuspended = 0

    Get-MoveRequest | Where {$_.status -eq "AutoSuspended"} | ForEach { $intAutoSuspended++ }
    if ($intNone -eq 5000) { Write-Host "AutoSuspended: > 5000" } ELSE  {Write-Host "AutoSuspended: " $intAutoSuspended}

    Get-MoveRequest | Where {$_.status -eq "Completed"} | ForEach { $intCompleted++ }
    if ($intFailed -eq 5000) { Write-Host "Completed: > 5000" } ELSE  {Write-Host "Completed: " $intCompleted}

    Get-MoveRequest | Where {$_.status -eq "CompletedWithWarning"} | ForEach { $intCompletedWithWarning++ }
    if ($intPending -eq 5000) { Write-Host "CompletedWithWarning: > 5000" } ELSE  {Write-Host "CompletedWithWarning: " $intCompletedWithWarning}

    Get-MoveRequest | Where {$_.status -eq "CompletionInProgress"} | ForEach { $intCompletionInProgress++ }
    if ($intDelivered -eq 5000) { Write-Host "CompletionInProgress: > 5000" } ELSE  {Write-Host "CompletionInProgress: " $intCompletionInProgress}

    Get-MoveRequest | Where {$_.status -eq "Failed"} | ForEach { $intFailed++ }
    if ($intExpanded -eq 5000) { Write-Host "Failed: > 5000" } ELSE  {Write-Host "Failed: " $intFailed}

    Get-MoveRequest | Where {$_.status -eq "InProgress"} | ForEach { $InProgress++ }
    if ($intExpanded -eq 5000) { Write-Host "InProgress: > 5000" } ELSE  {Write-Host "InProgress: " $InProgress}

    Get-MoveRequest | Where {$_.status -eq "None"} | ForEach { $intNone++ }
    if ($intExpanded -eq 5000) { Write-Host "None: > 5000" } ELSE  {Write-Host "None: " $intNone}

    Get-MoveRequest | Where {$_.status -eq "Queued"} | ForEach { $intQueued++ }
    if ($intExpanded -eq 5000) { Write-Host "Queued: > 5000" } ELSE  {Write-Host "Queued: " $intQueued}

    Get-MoveRequest | Where {$_.status -eq "Suspended"} | ForEach { $intSuspended++ }
    if ($intExpanded -eq 5000) { Write-Host "Suspended: > 5000" } ELSE  {Write-Host "Suspended: " $intSuspended}

    }




while(1)
{
    GetStats
    start-sleep -seconds 60
}
 


\\Tjopsta// http://www.tjopsta.net




Save unsaved files

$
0
0

I need to save all open Excel, Word, and PowerPoint documents to a temp directory(C:\temp\), regardless if they have ever been saved or not.  The saved file will be the "CurrentDocumentTitle + Timestamp".Extension.  I can use WASP to pull all open workbooks/documents in Excel, Word, and PowerPoint.  I can get A file to save, but it contains no content (at least unreadable).  I cannot seem to get this to work correctly, and I'm really hoping that this can be accomplished using PowerShell.  The intent of this is to be able to run an Acrobat uninstaller across multiple systems in my domain using SCCM.  I'm asking the users to save their work and close their applications so the uninstaller can run, unfortunately, they are not acting accordingly.  Any help would greatly be appreciated.

Set-ExecutionPolicy unrestricted -force
import-module C:\temp\WASP\WASP.dll -force #location of WASP

Function logstamp {
    $now=get-Date
    $yr = $now.Year.ToString()
    $mo = $now.Month.ToString()
    $dy = $now.Day.ToString()
    $hr = $now.Hour.ToString()
    $mi = $now.Minute.ToString()
    $se = $now.Second.ToString()
    if ($mo.length -lt 2) {
        $mo = "0" + $mo
    }
    if ($dy.length -lt 2) {
        $dy = "0" + $dy
    }
    if ($hr.length -lt 2) {
        $hr = "0" + $hr
    }
    if ($mi.length -lt 2) {
        $mi = "0" + $mi
    }
    if ($se.length -lt 2) {
        $se = "0" + $se
    }
    write-output $yr$mo$dy$hr$mi$se
}
$logstamp = logstamp

$filepath = "C:\temp\"
$objects = Select-Window | Where-Object {$_.Title -like "*Excel" -or $_.Title -like "*Word" -or $_.Title -like "*PowerPoint"} #SEARCHES FOR ALL OPEN WINDOWS OF LISTED TYPES (SAVED OR UNSAVED)
foreach($file in $objects){
    If ($file.Title -like "*Excel"){ #Set extension for Excel
        $ext = ".xlsx"
        #$a = New-Object -comobject Excel.Application
        #$a.Visible = $true
        #$book = $a.Workbooks.open($file)
        #$book.Save($filepath + $file.Title + $logstamp + $ext)
        #$a.Quit()
    }
    Elseif ($file.Title -like "*Word"){ #Set extension for Word
        $ext = ".docx"
    }
    Elseif ($file.Title -like "*PowerPoint"){ #Set extension for PowerPoint
        $ext = ".pptx"
    }
    $ofile = out-file ($filepath + $file.Title + $logstamp + $ext)
}
$ofile

New Version of the Azure Active Directory Module and PowerShell 2.0

$
0
0

Since the last upgrade of the Azure Active Directory Module for Windows PowerShell (64-bit version), we are no longer able to load it in an application targeting .NET Framework 3.5 SP1. The error message that we receive is:

Could not load file or assembly 'file:///C:\Windows\system32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Our application loads and uses the Azure AD PowerShell Module for Azure AD management. The previous version of the module available until September worked well, however, we cannot use the new version because it is built using the .NET Framework 4.0 runtime, and our application targets .NET Framework 3.5 SP1.

The link for the old version of the module was removed, and since the EULA for the module restricts us from making the old version available on our web site, we need a solution that would enable us to load the module in our application because we cannot retarget the application to a newer Framework version. In particular,we need a link that our customers can use to download the old version of the module.Is there a URL to the old version of the Azure Active Directory Module that we can download the old version from? Can someone help?

Run ps1 in ps1

$
0
0
I have C:\TestThis.ps1 $ip in a ps1 file and running ok. After changing the file name to C:\Test This.ps1 (add a space in), how to run C:\Test This.ps1 $ip ?

memory issue calling .Net component in PowerShell

$
0
0

I have a .Net-based SDK that we also expose via a single PowerShell cmdlet--all of the methods in the SDK are called as methods in PowerShell once you get a reference to the base object. One of the .Net capabilities allows us to populate a collection of objects under the base object. In C#, I'm able to successfully populate the collection without issue. In PowerShell, when I perform the equivalent function, memory usage grows to like 5gb. It's not clear to me why the PowerShell object is so much bigger (really orders of magnitude) than the equivalent C# call. I'm not clear where to look to see if it's a PowerShell issue or an issue with my SDK. If I look at the results object types in PowerShell using get-method, they appear equivalent to those in C# so I'm not following where the change is coming from.

Darren


Darren Mar-Elia MS-MVP, Group Policy
www.gpoguy.com
www.sdmsoftware.com - "The Group Policy Experts"

Send email after finding out the PrimaryStatus of the hard drives

$
0
0

Hi,

I have a script that will run through all names in the active directory and scan each to find things like the name, model, driveUsage and Primary status. However, I don't want to go through all logs to find the failing hard drive in one of the computers. I want to be able to send an email if one of the hard drives in any computer fails (PrimaryStatus is 2 or 3). My current script is:

Import-Module ActiveDirectory

$Computers = Get-ADComputer -Filter "OperatingSystem -NotLike '*Windows Server*'" | ForEach-Object {$_.Name} | 
out-file names.txt

$computerNames = Get-Content -Path C:\scripts\names.txt

foreach ($computer in $computerNames) {

  $rtn = Test-Connection -computername $computer -Count 1 -BufferSize 16 -Quiet

  IF($rtn -match 'True') {
  write-host "$computer"
  gwmi -Namespace root\dcim\sysman -computername $computer -Class DCIM_PhysicalDiskView | select-object Ele*,Mod*,Ser*,Driveu*,pri* | Format-table –autosize
  
  }

  ELSE { Write-host "$computer not pingable" }

}

Any help on this will be greatly appreciated. Thanks!


Get-MailboxPermission in Exchange 2013 Online returns insufficient information (cmdlet changed?)

$
0
0

Hi,

I use something similar to the below to get a list of accounts with permisisons on a mailbox:

$username = "SOMEACCOUNT"
$mailbox = Get-Mailbox $username
$faperms = $mailbox | Get-MailboxPermission -ErrorAction Stop | Where-Object { ($_.IsInherited -eq $false) -and ($_.User -notlike "NT AUTHORITY\*") -and ($_.User -notlike "Domain\$username") } | Sort-Object User

A matter of months ago, this used to return an object like so:

RunspaceId      : 3b6g8ac6-bb3d-4wy0-b898-834c10a7fq71
AccessRights    : {FullAccess}
Deny            : False
InheritanceType : All
User            : EURPR08B123\itsx43604-1411484821
Identity        : SOMEACCOUNT
IsInherited     : False
IsValid         : True
ObjectState     : Unchanged

Note the user property. I thought this was a little odd (querying local Exchange 2010 returns a samaccountname), but it wasn't a huge problem because I was able to handle this with an if condition (stripped down code for this post):

foreach($perm in $faperms)
{
    if($perm.User -match "EURPR0")
    {
          $permUser = (Get-User $perm.User).Identity
    }
}

... and this would give me a username (samaccountname).

However recently the return for the User property has changed. The same command now returns the DisplayName of the user who has full access permission on the mailbox object. DisplayName is not unique, so this could pose a potential problem if you're trying to translate the User property into an identifiable account.

Anyone have any thoughts on this? It seems as though the cmdlet has changed in the way it functions but is it still not quite right? Should this go on Connect? Is there a sure fire workaround?

Regards,

Robin

Get-WinEvent unusual errors

$
0
0

Hi all,

looking to change one of my scripts to use Get-WinEvent in place of Get-EventLog. testing the command to see what properties are returned so I can update the script something unexpected happened.

Get-WinEvent : Attempted to perform an unauthorized operation.
At line:1 char:24
+ $applogs = get-winevent <<<<  -logname application
    + CategoryInfo          : NotSpecified: (:) [Get-WinEvent], UnauthorizedAc
   cessException
    + FullyQualifiedErrorId : Attempted to perform an unauthorized operation.,
   Microsoft.PowerShell.Commands.GetWinEventCommand

Before anyone states the obvious - yes I am running this in an elevated prompt.

Now here's the odd part, if I create two arrays - one using "get-winevent -logname application -computer RemoteServer" and another using "get-eventlog -computer RemoteServer Application" the first one errors roughly 20 times, the second no errors. if I allow both to complete (running at the same time) both have the same item count of 64855. Same errors occur if I logon to "remoteserver" and run it locally.

I'm assuming that its an issue with specific event logs, anyone have suggestions on how to troubleshoot this?

Thanks in advance.


Retrieving the COM class factory for component with CLSID {0002DF01-0000-0000-C000-000000000046} failed

$
0
0

I have come across a weird issue while running a PowerShell script through task scheduler. Below is the simple script which would open all the sites of a SharePoint farm in IE browser.

Add-PsSnapin Microsoft.SharePoint.PowerShell

$ShowIE = $True

$LogFile = "E:\Scripts\Warmedup_Sites.log"

$ie=New-Object -ComObject "InternetExplorer.Application"

$ie.visible = $ShowIE

Get-SPSite -Limit ALL | Get-SPWeb -Limit ALL | ForEach-Object{
$ie.navigate($_.url)
while ($ie.Busy -eq $true){
Start-Sleep -Milliseconds 1000;
}
add-content -path $LogFile -value $("[" + (get-Date).ToString() + "] " + $_.url)
}
$ie.quit()

1. In the 1st case the script runs successfully only when the powershell console is opened as "Run as adminstrator". Otherwise it throws below error. The account am running is already part of server administrators group, is a SharePoint Farm administrator and is a domain account

The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_
At E:\Scripts\Warmup_AllRootSites.ps1:20 char:1
+ $ie.visible = $ShowIE
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Method invocation failed because [System.__ComObject] doesn't contain a method named 'navigate'.
At E:\Scripts\Warmup_AllRootSites.ps1:23 char:4
+             $ie.navigate($SiteURL)
+             ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

add-content : Could not find a part of the path 'C:\Installs\Warmedup_Sites.log'.
At E:\Scripts\Warmup_AllRootSites.ps1:27 char:3
+         add-content -path $LogFile -value $("[" + (get-Date).ToString() + "] " + $Site ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Installs\Warmedup_Sites.log:String) [Add-Conten
   Exception
    + FullyQualifiedErrorId : GetContentWriterDirectoryNotFoundError,Microsoft.PowerShell.Command

Method invocation failed because [System.__ComObject] doesn't contain a method named 'navigate'.

2. In the 2nd case, when i run the same PowerShell script through a task scheduler, it fails again with below error. The task is set to "Run with highest privileges". And in actions tab am running like "PowerShell.exe -ExecutionPolicy Bypass E:\Scripts\Warmup_AllSites.ps1". I have gone through several blogs and forums related to this error but nothing helped me. I dont think this is a permission issue anywhere. It seems like the COM object is losing the reference and throwing the error when referred. Can someone please help me in this regard.

New-Object : Retrieving the COM class factory for component with CLSID 
{0002DF01-0000-0000-C000-000000000046} failed due to the following error: 
80080005 Server execution failed (Exception from HRESULT: 0x80080005 
(CO_E_SERVER_EXEC_FAILURE)).
At E:\Scripts\Warmup_AllSites.ps1:18 char:5
+ $ie=New-Object -ComObject "InternetExplorer.Application"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMExcept 
   ion
    + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman 
   ds.NewObjectCommand

Property 'visible' cannot be found on this object; make sure it exists and is 
settable.
At E:\Scripts\Warmup_AllSites.ps1:20 char:1
+ $ie.visible = $ShowIE
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At E:\Scripts\Warmup_AllSites.ps1:23 char:4
+             $ie.navigate($_.url)


Thanks, Ramesh Mukka


Problems due powershell upgrade

$
0
0

Hi guys!

I want to update powershell from version 2.0 to 4.0 on some VM 2008 R2 but i read about some problems after updating powershell and now i'm scared to fail.

Can you show me the best practices to update powershell please?

These VM are working great, i don't want to stop them for repairing.

Thanks

A

Why do I get 'Access is Denied' when using Set-Service with Admin privileges?

$
0
0

Hello,

Im a Domain Admin and run the following from the ISE on a Domain Controller.  I start the ISE with 'Run as Administrator'.  I take a list of our DCs and based on some filtering logic, come up with a list of Services on each DC I want to Stop and set to Manual startup.  Executing the code below, I get the error whenever I hit this Service on any DC, whereas other Services the Stop and Set work fine with no issue.  Im not using PS Remoting here either.  Any ideas why I get this error on some Services and what I can do to eliminate it?  Thanks in advance.

$OurDCs = Get-ADDomainController -Filter * | Sort Name | Select -ExpandProperty Name

foreach ($DC in $OurDCs ) {                                                                                                                                                                   

$DCServices = get-service -CN $DC | ....... }

ForEach ($Service in $DCServices) {

       $Service | Stop-Service -Passthru | Set-Service -CN $DC -StartupType Manual
 
Set-Service : Service 'Windows Installer (msiserver)' cannot be configured due to the following error: Access is denied
At C:\Users\Edward\Set-ServicesOnDCs.ps1:184 char:44
+        $Service | Stop-Service -Passthru | Set-Service -CN $DomainCOntroller -StartupType Manu ...
+                                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
    + FullyQualifiedErrorId : CouldNotSetService,Microsoft.PowerShell.Commands.SetServiceCommand


Thanks for your help! SdeDot


Microsoft Dynamics AX Scheduler

$
0
0
Is there a way using Powershell to access a scheduler on an DAX AOS server to determine the status of a job? I have a pair of jobs on a SQL Server 2008 R2 database that need to run as soon as the DAX job has completed successfully. The DAX job has varying run times depending on the previous day's activities. Because of this I can't set the jobs on the SQL Server to run at a specific time. I have search for a solution to his but I haven't found anything useful.

Add line to a text file just after a specific line with PowerShell

$
0
0

Hi,

I have to edit remotely a file called nsclient.ini on hundreds of computers, the file contains some command definitions. For example:

[/settings/external scripts/scripts]    
check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo

I need to add a new line just beneath [/settings/external scripts/scripts] This new line should not overwrite the existing lines beneath.

Thanks for your help.

ISE Addon for Checkout or Checkins via TFS 2013

$
0
0

Hi

I am coordination the development of some PowerShell scripts to work against our SharePoint Farm.  Now as there is more that just me developing these scripts, I think we need to start doing regular checkin and checkouts in our TFS 2013.  Anyway, I naively thought there must be an addon  I could add to ISE for this; since it seems such a common requirement. However, there does seem much out there that is actively being used. Are there alternatives that are widely used such a series of PS functions anyone knows about. 

Daniel 


Freelance consultant


Run Script under different user - always

$
0
0
Is there a way to make it where a users runs a powershell script and when they execute it it runs under different credentials without prompting for username/password?  the scenario is this, Im writing a script for our helpdesk that will pull certain information from AD  that will require domain admin privliges to ascertain.  Of course I do not want our helpdesk to have the username/password that will run the script.  Is there a way to store this info in an encrypted file that can be read each time the script is run?   thanks  

SQL Query Fails through Powershell

$
0
0

I am trying to alter the Permission set on the Assemblies using powershell and I keep getting the same error. For the life of me, I just cant figure out where I may be going wrong here. Any help is much appreciated.



# 1.2. 4 Load required Assembly

[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, Culture=Neutral,Version=11.0.0.0, PublicKeyToken=89845dcd8080cc91")

# 1.2.5 Connect to SQL Instance (in this case the default instance)

$SqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") "."

# 1.2.6 Show current SQL Version. Not required but verifies if connection can be established

$SQLServer | Select Edition, VersionString

#WI: Change security settings:

$SQLServer.Databases | 
        ForEach-Object { 
            $DB = $_
            $DB.ExecuteWithResults('SELECT * FROM sys.assemblies') } | 
            ForEach-Object { $_.Tables[0] } |
                %{ 
                    Write-Host "ALTER ASSEMBLY [$( $_.name )]  WITH PERMISSION_SET = SAFE" 
                    $DB.ExecuteWithResults("ALTER ASSEMBLY [$($_.name )]  WITH PERMISSION_SET = SAFE")
                 }

The Error message is


Exception calling "ExecuteWithResults" with "1" argument(s): "Execute with results failed for Database 'test'. "
At line:22 char:63+                     $DB.ExecuteWithResults("ALTER ASSEMBLY [$($_.name )]  WITH P ...+                                                               ~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : FailedOperationException



Lokesh Gunjugnur


How to find if a user does not have permissions to their folder?

$
0
0

scenario: user loses permissions to their file share or user folder

goal: identify the user that has a matching username in AD but lost permissions to their folder

issues: I can find the users that have permissions to their folder and I can find other users. I am having issues when the user lost permissions to the folder and just focusing on that user and not the other ones like "administrators, users, " or common system accounts.

The scripting guy post helped me get further than my original code:
http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/14/hey-scripting-guy-september-14-2009.aspx

I have numerous versions below and after a few hours am giving up for the night. Please help!

The section in bold is where I am struggling with logic to show me results of only users that have the same AD name as the folder name, but do not have permissions to that folder.

Import-Module ActiveDirectory

cls
$OutFile = "c:\scripted\share_folder_permission.csv"
Del $OutFile
$RootPath = "c:\users\"
#get-user \\FILESHARE\users\$_.$UserName
#$rootpath = "\\FILESHARE\users"

#$username='DOMAIN\MYLOGIN205'
$Folders = dir $RootPath | where {$_.psiscontainer -eq $true}
foreach ($Folder in $Folders){
$username='DOMAIN\' + $Folder.Name
$acl = Get-Acl -Path $Folder.Fullname
#$acl.Access |ForEach-Object { $_.identityReference.value | Where-Object { $_ -eq $username }}

#$acl.Access | ForEach-Object { $_.identityReference.value | Where-Object { $_ -eq $username }  } {
$acl.Access | ForEach-Object { $_.identityReference.value | Where-Object { $_ -ne $username }  } {

$adaccount = Get-QADUser $folder
if ($adaccount.accountisenabled){
 $outinfo = "user " + $username + " " + $folder.fullname + " does not have access"
Add-Content -Value $OutInfo -Path $OutFile

}
}<#if ($_.identityReference.value -eq $username){
 $outinfo = "user " + $username + " " + $folder.fullname + " has access"
 Add-Content -Value $OutInfo -Path $OutFile
} #>

#if ($_.access -ne $username){
 #$outinfo = "user " + $username + " " + $folder.fullname + " does not have access"
 #Add-Content -Value $OutInfo -Path $OutFile
#}

  #end foreach for acl loop
} #end searching folder in folders


# 

Need to to set single values on a set of properties for each user in a list

$
0
0

I've got a list of Active Directory user accounts that need the following properties set for each respective user account:

SAMAccountName

UserPrincipalName

EmailAddress

Mail

mailNickname

 

I've been working under the assumption that I'll use a CSV file with the following headers:

  • OldSam: Use this for the existing SamAccountName/Alias for the given user
  • NewSam:  Use this to change the SamAccountName/Alias for the given user
  • NewUpn:  Use this to change the UPN for the given user
  • EmailAddress:  Use this to change the EmailAddress listed in AD for the given user.  We use o365 for email..
  • Mail:  Use this to change the Mail entry listed in AD for the given user. 
  • mailNickName:  Use this to change the mailNickname entry listed in AD for the given user.

I'm a novice when it comes to PS, but I'm trying.  Any help is appreciated.

Recursively select all subordinates for all users from AD

$
0
0

I'd like to use AD to maintain a list of a user's subordinates, which will be used in a custom application to control the display of information.  Currently, this list is manually maintained, and it would be a lot easier if we could rely on AD for this.

Is there a way to recursively select all users and all of their subordinates (direct reports as well as direct report of direct reports) from Active Directory using PowerShell (or something else)?

The example org structure is:

1. President
  2. VP 1
    3. Team Member 1
    3. Team Member 2
  2. VP 2
    3. Team Member 3
    3. Team Member 4

I would like to get a csv file that contains the username of the manager and the username of their subordinates.  In this example:

MANAGER,SUBORDINATE
president, vp1
president, team1
president, team2
president, vp2
president, team3
president, team4
vp1, team1
vp1, team2
vp2, team3
vp2, team4
The levels of nesting can obviously vary, but I'd like it to go as deep as it need to in order to capture all levels and provide the output.  

'set-acl.exe' not recognized as the name of a cmdlet,

$
0
0

hi all,

I would like to seek some assistance as I am not able to use the "set-acl.exe' powershell command to take ownership of [HKEY_CLASSES_ROOT\CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\ShellFolder], this is for removing the network icon on the explorer left pane.

Viewing all 21975 articles
Browse latest View live


Latest Images

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