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

Trying to remove a built in app

$
0
0

Hello, I am trying to remove a built in windows app that comes with Windows 10, unfortunately I am not getting any response in the Windows 10 forum, so I am hoping that someone here can help out...

https://social.technet.microsoft.com/Forums/en-US/5b3a0263-3d98-4d3f-93b3-2ebab7f1e490/removal-of-apps-is-failing?forum=win10itprosetup#b60532c1-4c7a-40b0-86be-6fe4d2d11e4f


Automating the clearing of cache in internet explorer

$
0
0
Internet explorer has a key combo to clean the cache ctrl, shift + delete.  I would like to clean the browser in the same manner but make it an automated task after data has been input through the browser.

showing full list of group that the user is member of

$
0
0

i used "Get-ADUser <username> -properties MemberOf" to get which groups the user is member of, and it works good but it does't show all the group names because of the lack of space, and it shows three dots "..." at the end of the memberof line.

is there any way i can use to show all the groups name??

 

Import-CSV from OPENFILES output

$
0
0

Hi all,

I'm trying to put the output of OPENFILES into a powershell variable using Import-CSV. I would think this to be straight forward but I can't seem to figure it out. Any help would be greatly appreciated.

$a = (openfiles /query /s <servername> /fo csv | select-string "searchString") | import-csv -header SessionID,username,platform,path

from this I get:

import-csv : Cannot find drive. A drive with the name '"54830268","<username>","Windows","C' does not exist.
At line:1 char:82
+ ... csServices") | import-csv -header SessionID,username,platform,path
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ("54830268","<us...e>","Windows","C:String) [Import-Csv], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.ImportCsvCommand

I've tried it with and without the parentheses. Makes no difference.

Thanks.


-- Tim.

The WS-management service cannot process the request

$
0
0

Hello everyone

I am fighting with "Desired State Configuration" but I must say I am not finding easy. I've got a windows server 2012 and created a .MOF file with no problems. However when I run: 

start-dscconfiguration -wait -verbose -path <some_path>

 

I get the following error:

The WS-Management service cannot process the request.

The service cannot find the resource identified by the resource URI and selectors.

+CategoryInfo :ObjectNotFound: (root/Microsoft/...gurationManager:String) [], CimException

+FullyQualified ErrorId: Hresult 0x80338000

+PCComputerName: beftaki

Please note the client machine is windows 7.  

Any suggestions please?

Thank you



Powershell script to catch groups with admin and non-admin accounts

$
0
0

Hi,

I'm doing AD tidy up work for a company and are trying (and failing) to write a script that will query all groups across the AD and look for groups whose members usernames contain users with '*admin*' AND users without '*admin*'. Basically, the idea is that I'm looking to try and find groups that have admin AND non-admin accounts in them, because I need to split them out so that admins have admin groups with admin access and non-admins don't. There is a naming convention in place for admin accounts, hence why I'm using '*admin*'

I've tried using something along the lines of this:

Import-Module ActiveDirectory

$Groups=Get-ADGroup -Filter *
ForEach ($Group in $Groups) {

 $hasAdmin=$false
 $hasNotAdmin=$false

 foreach($groupmember in Get-ADGroupMember $group) {
  if ($groupmember.SamAccountName -match "*admin*") {
  $hasAdmin=$true
  }
   if ($groupmember.SamAccountName -notmatch "*admin*") {
  $hasAdmin=true
  }
 }
 if ($hasadmin -and $hasnotadmin) {
 write-host $group
 }
}

But it doesn't work. Tried a number of different scripts from the web (sorry, my own powershell skills are limited), so I wondered if anyone may have any suggestions on where I'm going wrong?



Account Expiration email notification

$
0
0

I've parsed together a few scripts found here to create a script that will:

- Notify a users manager if the users account will expire within 30 days. 
- If the user does not have a listed manager, default to the helpdesk

My issue is (besides I'm not a powershell expert) is that a manager who has multiple employees with expiring accounts will receive multiple emails (i.e. We have some managers receiving 20-30 individual emails for individual users). Is there a way to change this so that each manager will only receive one email with a list of users?

Based on how this is written, I'm not sure how to parse it all into an array (or another solution?) being it is processing it one-by-one currently? Any help/thoughts or editing would be extremely appreciated!!

------                    

Function Get-UsersEmail{
   [CmdletBinding()]
   Param(
      [Parameter(Position=0,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [String]$adsPath
   )
   Try{
      $user  = [ADSI]"LDAP://$adsPath"
      $email = $user.mail
   }Catch{
      [String]$email = ""
   }
   Return $email
}

# Determine expiration date and return "<never>" or expiration date in variable $expiry
Function Get-ADUserExpiry{
   [CmdletBinding()]
   Param(
      [Parameter(Position=0,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [String]$sid
   )
   $user           = [ADSI]"LDAP://<SID=$sid>"
   $accountExpires = $user.accountExpires.Value
   $longValue      = $user.ConvertLargeIntegerToInt64($accountExpires)
   If($longValue -gt [DateTime]::MaxValue.Ticks){
      $longValue = 0
   }
   $dateValue = [DateTime]$longValue
   If($dateValue -eq 0){
      $expiry = "<Never>"
   }Else{
      $expiry = [DateTime]::FromFileTime($user.ConvertLargeIntegerToInt64($user.accountExpires.Value))
   }
   Return $expiry
}

# End of functions
# ----------------------------------------------

# Define Variables
$default  = "helpdesk@company.com"
$LineBreak   = "`r`n"

Import-Module ActiveDirectory
$results = search-adaccount -AccountExpiring -TimeSpan "30" -usersonly

ForEach($result In $results){
   Do{
      # Set variable to string
 $expiry    = ""
      $to        = ""
      $body      = ""

 #
 $subject   = "User Account Expirations"
      $sid       = $result.SID
      $userName  = $result.sAMAccountName

      #get distinguished name/sid of user
 $user      = [ADSI]"LDAP://<SID=$sid>"
      $manager   = $user.Manager
      $firstName = $user.givenName
      $lastName  = $user.sn

 # Passes $SID to above function 'get-aduserexpiry' and saves the expiration date to $expiry
      $expiry    = Get-ADUserExpiry $sid

 # If manager exists, call function get-usersmail on the manager
 If($manager -ne ""){
         $to = Get-UsersEmail $manager
      }

 # If no manager exists set to field as default (helpdesk)
 Else{
         $to = $default
      }

 # Send email if Manager exists and Expiration exists
      If($to -ne "" -And $expiry -ne "<Never>"){
         $subject += " - $firstName $lastName"
         $body    = "You are listed as the manager responsible for the following user account which will expire in 30 days. Please email the helpdesk if the account should remain enabled." + $LineBreak + $LineBreak
         $body    += "LogonName: $userName"  + $LineBreak 
         $body    += "FirstName: $firstName" + $LineBreak
         $body    += "LastName: $lastName"   + $LineBreak
$body    += "Listed Manager: $to"   + $LineBreak
         $body    += "ExpiryDate: $expiry"   + $LineBreak + $LineBreak 
$body    += "Thank You"+ $LineBreak
                
         Write-Host "Sending email to users manager ($to) for user $userName"
         Write-Host $subject
         Write-Host $body
         Write-Host ""
         Send-MailMessage -To $to -From "helpdesk@company" -Subject $subject -Body $body -smtpserver "xxx"
}
   }Until($True)
}

----

more-info: What I'm asking is very similar to this user (http://stackoverflow.com/questions/16533334/powershell-script-for-soon-to-expire-ad-users), but it isn't quite working properly (i.e. the display looks poor and lists all information duplicated in the email instead of just the user name) and that requires an imported .csv of all users and their managers which I don't have and haven't determine how to create.

Problem using Get-CimInstance remotely for some namespaces

$
0
0

I am trying to get some info on my array controller remotely on an HP server. HP provides a namespace for this, and a class about the array controller. The following, using the get-WMIObject command, works:

Get-WMIObject -ComputerName server01 -Namespace "root\hpq" -ClassName HPSA_ArrayController

However, this does not:

Get-CimInstance -ComputerName server01 -Namespace "root\hpq" -ClassName HPSA_ArrayController

It gives me the following error: "The WS-Management service cannot process the request. The DMTF class in the repository uses a different major version number from the requested class. This class can be accessed using a non-DMTF resource URI."

What is more puzzling is that if I enter a remote session to server01 and run the Get-CimInstance command (without the computername parameter, of course), it gives me a result as expected. I should also point out that querying information remotely using Get-CimInstance for other namespaces (e.g. root\cimv2) works fine.

Any idea what may be going on?


Eric Hodges


Query Text From GUI-Window

$
0
0

Hello everyone

I've got a very nice .exe file to query my network for all kinds of stuff like hostnames, IPs or subnets.

Now i would like to work with this queried information by processing it with powershell. Since the arrays of information can be quite large, it's much of an effort to get them into powershell one by one by Hand.

Is there a way to get the content of that Window into my powershell automatically i.e. to read the content of a WindowsForm-Textbox?

Thanks for your help!

Regards

SSPI Call Fails with different inner exceptions

$
0
0

We have a web service that gets called from one of our web apps.  Prior to the last update, the app worked correctly.  After the last Microsoft update, we started getting SSPI call fails with different inner exceptions.  The first comes when running the app in local host mode (Windows 7) for development:

Server Error in '/' Application.

The encryption type requested is not supported by the KDC

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details:System.ComponentModel.Win32Exception: The encryption type requested is not supported by the KDC Source Error:

Line 478:              private List<Contracts.ClientSupportServices.SavedSearch> GetClientSavedSearches(Guid userId, bool onlyFolders)Line 479:              {Line 480:                      IEnumerable<Contracts.ClientSupportServices.SavedSearch> searches = _freshService.Execute(s => s.GetSavedSearchesForUser(userId));Line 481:                      if (searches == null)Line 482:                      {

Source File:c:\Repos\ocs\Source\OCS\OnlineClientSupport\Controllers\ClientController.Search.cs   Line:480Stack Trace:

[Win32Exception (0x80004005): The encryption type requested is not supported by the KDC][AuthenticationException: A call to SSPI failed, see inner exception.]   System.Net.Security.NegoState.StartSendAuthResetSignal(LazyAsyncResult lazyResult, Byte[] message, Exception exception) +1730592   System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult) +89   System.Net.Security.NegoState.CheckCompletionBeforeNextSend(Byte[] message, LazyAsyncResult lazyResult) +65   System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult) +152   System.Net.Security.NegoState.StartReceiveBlob(LazyAsyncResult lazyResult) +101   System.Net.Security.NegoState.CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) +53   System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult) +927   System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult) +129   System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) +48   System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) +23   System.ServiceModel.Channels.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity) +93[SecurityNegotiationException: A call to SSPI failed, see inner exception.]   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336   RealMed.ServiceContracts.IClientServiceFresh.GetSavedSearchesForUser(Guid userId) +0   RealMed.OnlineClientSupport.Controllers.<>c__DisplayClassa9.<GetClientSavedSearches>b__a4(IClientServiceFresh s) in c:\Repos\ocs\Source\OCS\OnlineClientSupport\Controllers\ClientController.Search.cs:480   RealMed.Library.Service.WcfServiceWrapper`1.Execute(Func`2 action) in c:\Repos\ocs\Source\Library\Library\Service\WcfServiceWrapper.cs:111   RealMed.OnlineClientSupport.Controllers.ClientController.GetClientSavedSearches(Guid userId, Boolean onlyFolders) in c:\Repos\ocs\Source\OCS\OnlineClientSupport\Controllers\ClientController.Search.cs:480   RealMed.OnlineClientSupport.Controllers.ClientController.GetClientSavedSearches(Guid userId) in c:\Repos\ocs\Source\OCS\OnlineClientSupport\Controllers\ClientController.Search.cs:475   RealMed.OnlineClientSupport.Controllers.ClientController.Index(Guid userId, WebProfile userProfile) in c:\Repos\ocs\Source\OCS\OnlineClientSupport\Controllers\ClientController.Search.cs:24   lambda_method(Closure , ControllerBase , Object[] ) +200   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +19   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +209   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +15   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +49   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +44   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +15   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +54   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +44   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +12   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +58   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +11   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9644037   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

The second error occurs on the development server (Server 2008) with a different inner exception of "The system detected a possible attempt to compromise security.  Please ensure that you can contact the server that authenticated you."

(I had a screen cap of the entire stack trace but cannot include in this post).

Has anyone else seen this behavior since?  Thanks.

Set Permissions in SharePoint on a Document Library

$
0
0

Hello I am in SharePoint 2013 SP1 October 2015 CU Enterprise Edition and I am tasked with updating permissions on a Document Library on multiple subsites in a site collection.

SiteCollection\Subsites\Document Library\  YES they have a SPACE in the name! Grrr

I barely know PowerShell and I wonder if you know how I can set the permissions for that Document Library (with a space in it's name).

The permissions are all the same, or will be.  I just need to interate through.

This is one that my coworker wrote and I am doing their job after they are no longer with the company.  I am trying to reverse engineer it.  I don't know that I need to remove permissions.  I just want to say

This subsite with this Document Library name needs to be given these permissions.  If inherited permissions, break it and assign these permissions.

Thank you!  Below is the script I am trying to see if I can get to "work"

start-transcript c:\PowerShellScripts\Proposals\dailyProposalstranscript.txt
rm c:\PowerShellScripts\Proposals\allsites.txt
rm c:\PowerShellScripts\Proposals\allsitesnq.txt
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Get-SPsite -identity https://WebApplicationqa/depts/SiteCollection/ | get-spweb -Limit All | select url | export-csv -path c:\PowerShellScripts\Proposals\allsites.txt -NoTypeInformation

Get-Content c:\PowerShellScripts\Proposals\allsites.txt | % {$_ -replace '"', ""} | Set-Content c:\PowerShellScripts\Proposals\allsitesnq.txt
Get-Content c:\PowerShellScripts\Proposals\allsitesnq.txt |  Where { $_ -Match "https://WebApplicationqa/depts/SiteCollection/" } | Set-Content c:\PowerShellScripts\Proposals\allsites.txt

function AddGroupToSite ($web, $groupName, $permLevel)
{
    $account = $web.SiteGroups[$groupName]
    $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
    $role = $web.RoleDefinitions[$permLevel]
    $assignment.RoleDefinitionBindings.Add($role);
    $web.RoleAssignments.Add($assignment)
}

function RemoveAccountFromAllSites ($siteURL, $accountName, [switch]$skipRootSite)
{
    #Get Site Collection
    $site = Get-SPSite $siteURL

    #Check if the accountName variable contains a slash - if so, it is an AD account
    #If not, it is a SharePoint Group
    $rootWeb = $site.RootWeb
    if ($accountName.Contains("\")) { $account = $rootWeb.EnsureUser($accountName) }
    else { $account = $rootWeb.SiteGroups[$accountName] }
    $rootWeb.Dispose()

    #Step through each site in the site collection
    $site | Get-SPWeb -limit all | ForEach-Object {

        #Check if the user has chosen to skip the root site - if so, do not change permissions on it
        if (($skipRootSite) -and ($site.Url -eq $_.Url)) { write-host "Root site" $_.Url "will be bypassed" }
        else {
            #Check if the current site is inheriting permissions from its parent
            #If not, remove permissions on current site
            if ($_.HasUniqueRoleAssignments) {
                $_.RoleAssignments.Remove($account)
            }
            else {
                write-host "Site" $_.Url "will not be modified as it inherits permissions from a parent site."
            }
        }
    }
    #Display completion message and dispose of site object
    $site.Dispose()
}

foreach ($line in get-content c:\PowerShellScripts\Proposals\allsites.txt) {
    $web = Get-SPWeb "$line"
	if ($web -ne $null) {
        $web.BreakRoleInheritance($false, $false)
        AddGroupToSite -web $web -groupName "Permission Name Here" -permLevel "Contribute"
	    $web.Dispose()
	}
}

RemoveAccountFromAllSites –siteURL "https://WebApplicationqa/depts/SiteCollection/" -accountName "PERMISSION NAME HERE" -skipRootSite


foreach ($line in get-content c:\PowerShellScripts\Proposals\allsites.txt)
{
  $web = get-spweb $line
  $SPWeb = Get-SPWeb "$line"
  $SPList = $SPWeb.Lists["Document Library Name With Space Here"]
  $SPItems = $splist.Items

  $SPList.Items | foreach {
    if( $_ -ne $null) {
		if($_["HRBP"] -eq "Carla Wilson") {
			AddGroupToSite -web $web -groupName "PERMISSION NAME" -permLevel "Contribute"
		}

		}
    }
  }
  $SPWeb.Dispose()
  $web.dispose()
}
Stop-transcript

PowerShell logon script with UAC

$
0
0

Hi Everyone,

I have a script that works great for most people, but for some it fails. This is especially true with Windows 10 when UAC is enabled.

Part of the logon script maps drives for users. I capture the output which says it is successful but the user does not see them.

It turns out that when the group policy logon script runs, it does it with elevated rights. This means if you open a command prompt as an Administrator, you can see the drives.

Does anyone know how I can get around this so when I map drives, I do it for the standard user and not an elevated one?

Without UAC enabled, the script works every time

For information, this is the part of my script that maps drives:

# Build a set of results that are for the site the user is in
    $result = $table.select("site='$site'")
# Site is the AD site
# Result will usually contain something like this:
# Site   Group   DriveLetter DriveRoot
# ADSITE dm_home H:          \\home-server\users\
# My users are nearly all member of "dm_HOME"
    # If there are any results, process them
    if ($result.count)
        {
        # For every row in the result, attempt to map each drive
        foreach ($line in $result)
            {
                If ($userGroups -contains $line.Group -or $line.Group -eq "*")
                    {
                    $drive = $line.DriveLetter; $driveroot = $line.Driveroot
                    WriteEvent -EventID 108
	                try
                        {
                        $drivemapresult = Net Use $drive $driveroot
                        WriteEvent -EventID 115 # this is a custom code block which writes to the event log in Windows
                        }
                        catch
                            {
                            #write-warning "$drive has not mapped correctly, contact IT Service Desk!"
                            $errormessage = $errormessage + "$drive has not mapped correctly`r`n"
                            }
                    }
            }
        }

Thanks

Dan

System.Data.Odbc.OdbcException: in Powershell 5 but not in VS2015 running POSHTools

$
0
0

Getting an System.Data.Odbc.OdbcException: when I run a script natively in PowerShell 5 (on Win10 and Server 2k12r2), however if I run the same script in Visual Studio 2015 Enterprise with PowerShell Tools for VS2015 v3.0.323 installed it runs fine and no errors or exceptions.

Any help would be greatly appreciated.

PSVersion                      5.0.10586.63                                                                        
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                             
BuildVersion                   10.0.10586.63                                                                       
CLRVersion                     4.0.30319.42000                                                                     
WSManStackVersion              3.0                                                                                 
PSRemotingProtocolVersion      2.3                                                                                 
SerializationVersion           1.1.0.1

Query I'm running:

$IBIConnection = New-Object System.Data.Odbc.OdbcConnection
            $IBIConnection.ConnectionString = "DSN=iBI DaaS;Uid=myUsername;Pwd=;"

            $IBIOdbcCmd = New-Object system.Data.Odbc.OdbcCommand
 


            $IBIAllSQLQuery = "select [id] as [Feature]
                                    , [[title] as [Description]
                                    , [bugeco.fixed] as [Fixed]
                                from [ES.bugeco]
                                where ([release] like ( '%YYZ' ) or [ES.bugeco].[release_affected] like ( '%YYZ' ) )
                                and [id] in ( 12345, 123456 )
                                order by [id] asc"

            # Init Table
            If ($IBIDataTable -ne $null)
            {
                $IBIDataTable.Clear()
                $IBIDataTable.Dispose()
                Write-Host "Clearing DataTable"
            }
            $IBIDataTable = New-Object system.Data.DataTable "Bug_Table"
            $FeatureCol = New-Object System.Data.DataColumn Feature,([int32])
            $DescriptionCol = New-Object System.Data.DataColumn Description,([string])
            $FixedCol = New-Object System.Data.DataColumn Fixed,([string])
            $IBIDataTable.Columns.Add($FeatureCol)
            $IBIDataTable.Columns.Add($DescriptionCol)
            $IBIDataTable.Columns.Add($FixedCol)

            # Connect to SQL
            $IBIConnection.open()
            $IBIOdbcCmd.CommandText = $IBIAllSQLQuery
            $OdbcAdapter = New-Object system.Data.Odbc.OdbcDataAdapter
            $OdbcAdapter.SelectCommand = $IBIOdbcCmd
            $IBIOdbcCmd.Connection = $IBIConnection

            # Fill Table with SQL Data
            [void]$OdbcAdapter.Fill($IBIDataTable)
            
            # Close SQL Connection
            $IBIConnection.close()

Exception Thrown:

Exception             : System.Management.Automation.MethodInvocationException: Exception calling "Fill" with "1" argument(s): "ERROR [HY000] The request was invalid or the request is without authentication or cannot be otherwise served." --->
                        System.Data.Odbc.OdbcException: ERROR [HY000] The request was invalid or the request is without authentication or cannot be otherwise served.
                           at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
                           at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod)
                           at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader)
                           at System.Data.Odbc.OdbcCommand.ExecuteReader(CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
                           at CallSite.Target(Closure , CallSite , Object , Object )
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : OdbcException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, F:\Workspaces\Visual Studio 2015\Projects\PowerShellProjects\PowerShellProjects\psScripts\HSD_ES Test.ps1: line 55
PipelineIterationInfo : {}
PSMessageDetails      :

Powershell Variable Storage limit

$
0
0


Hi

I am trying to use the below powershell script to download an attachment from my o365 email address. The size of the attachment is 9mb. The script is able to read the message and attachment but unable to store the data of attachment to $attachments variable.  However, there is no such issue when i use a smaller file (size < 1mb).

Is there any store limitation on powershell variables? if so, then what is the work around available here with us.

##-----------------------------------------------------##
##        PICK AUTH Method                             ##
##-----------------------------------------------------##
 
## HARD CODING PSW    ##
#$password = ConvertTo-SecureString "xxx" -AsPlainText -Force
#$cred = New-Object System.Management.Automation.PSCredential "xxx@xxx.onmicrosofot.com",$password
 
## USER PROMPT PSW    ##
#$cred = Get-Credential
 
##-----------------------------------------------------##
##    END PICK
##-----------------------------------------------------##
 
$url = "https://outlook.office365.com/api/v1.0/me/messages"
$date = "2014-11-21"
 
## Get all messages that have attachments where received date is greater than $date  
$messageQuery = "" + $url + "?`$select=Id&`$filter=HasAttachments eq true and DateTimeReceived ge " + $date
$messages = Invoke-RestMethod $messageQuery -Credential $cred
 
## Loop through each results
foreach ($message in $messages.value)
{
    # get attachments and save to file system
    $query = $url + "/" + $message.Id + "/attachments"
    $attachments = Invoke-RestMethod $query -Credential $cred
 
    # in case of multiple attachments in email
    foreach ($attachment in $attachments.value)
    {
        $attachment.Name
        $path = "c:\Temp\" + $attachment.Name
     
        $Content = [System.Convert]::FromBase64String($attachment.ContentBytes)
        Set-Content -Path $path -Value $Content -Encoding Byte
    }
}
 

Regards

Jasneet

Get samaccountname from display name - bulk csv

$
0
0
I have a csv file with AD users' display names. Does anyone have the script to get samaccountnames from such csv?

Powershell Form in a HTML page

$
0
0

Hello Experts,

I want to publish Powershell form in a HTML page. Please let me know if this is a possibility. 

The idea is that any user can access the form using the webpage seamlessly and I can pass the inputs to my Orchestrator tool to do the rest of the work.

Regards. 


Priyabrata

Issue with script used in a TFS vnext Build - Returns exact duplicates from Get-ChildItem

$
0
0

I am trying to develop a powershell script to run during a build and have based it on one I found on MSDN that was for updating the AssemblyInfo.* version to match a build version.

The problem I am having is that the Get-ChildItem command syntax from the example seems very complicated to me when what I want is really simple.  I need to get out all files that match the pattern *.wxs recursively.

While the code below is working, the output shows that it "finds" the file four times with the exact same path and I can't figure out how to change it so that it doesn't return the duplicates.

Perhaps someone more knowledgeable can help me as this is more or less the first time I've worked with powershell.

An excerpt of the script as well as the output showing it "finds" four copies of the same file in the same place is below.

thx.

# Apply the version to the assembly property files
$files = gci $Env:BUILD_SOURCESDIRECTORY -recurse  |
    ?{ $_.PSIsContainer } |
    foreach { gci -Path $_.FullName -Recurse -include *.wxs }

if($files)
{
    Write-Host "Will apply $NewFullVersion and $NewVersion to $($files.count) files."

    foreach ($file in $files) {
 Write-Host $file.FullName
        $filecontent = Get-Content($file.FullName)
        attrib $file -r
        $filecontent -replace $FullVersionRegex, "define FullInstallVersion = ""$NewFullVersion""" -replace $PartVersionRegex, "define InstallVersion = ""$NewVersion""" | Out-File $file -Encoding "UTF8"
        Write-Host "$file - version applied"
    }
}
else
{
    Write-Warning "Found no files."
}


Output shows as if there were four files but really there is of course one.


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

Starting task: Powershell: $/WiDSPlus/BuildScripts/ApplyVersionToWIXInstallers.ps1

******************************************************************************
BUILD_SOURCESDIRECTORY: g:\builds\Agent 3-TFSBUILD\2\s
Full Version: 2016.2.19.46831
Version: 16.2.19
Will apply 2016.2.19.46831 and 16.2.19 to 4 files.
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs - version applied
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs - version applied
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs - version applied
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs
G:\builds\Agent 3-TFSBUILD\2\s\Main\WCF\WidsPlusService\Installer\Product.wxs - version applied

Copy-Item including any files that are duplicated

$
0
0

I am trying to work out how to copy multiple files from shared network locations to a single network shared folder but I need to keep the duplicate files rather than then overwritting.  They can be renamed or appended but I have to keep all files.

This is what I have so far which has been built up from bits and pieces I have found online but it doesn't work and there are no resources out there that seem to suggest this is possible.  I'm basically looking at the destination and if the file already exists to append it with a 1,2,3 etc.  But the below is not working.

$SourceFile = "C:\Support\Files.csv"
$Destination = "C:\Support\TestDestination"

If (Test-Path $Destination) {
    $i = 0
    While (Test-Path $Destination) {
        $i += 1
        $Destination = "c:\Support\TestDestination\File$i.txt
    }
} Else {
    New-Item -ItemType File -Path $Destination -Force
}

Copy-Item -Path $SourceFile -Destination $Destination -Force

Any assistance you can offer would be greatly appreciated.

Thanks in advance

Find users with expired password

$
0
0

How come I cannot use the following get-aduser filter to find users with expired password?

This does not return any users however I DO have accounts with expired passwords.

get-aduser -Filter {passwordexpired -eq $true}

PS C:\tmp> Get-ADUser us-svcmsaprod -Properties passwordexpired

DistinguishedName : CN=us-svc****,OU=US Service Accounts,DC=us,DC=**,DC=com
Enabled           : True
GivenName         : US-****
Name              : us-svc****
ObjectClass       : user
PasswordExpired   : True
SamAccountName    : us-svc****

Copy members from one AD Group to another

$
0
0

I'm still learning powershell so be gentle please

I've got the following that works

get-adgroup -filter {name -like "RDS*"} | select SamAccountName | foreach {$_.SamAccounName} {Get-ADGroupMember $_.SamAccountName} 

Which works so I attempted to use that as a base to copy group members of one group to another, which lead me to

Get-adgroupmember RDS| select SamAccountName | foreach {$_.SamAccounName} {ADD-ADGroupMember NEW_RDS $_.SamAccountName} 

All this does is error.

If I do the following $users = Get-adgroupmember RDS | select SamAccountName and the just type $users I get the expected the list so I' assuming the 2nd part is where I'm going wrong

Can it be done this simply?

Viewing all 21975 articles
Browse latest View live


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