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

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


Cannot sign in with ADDS users created with powershell

$
0
0

Hey guys, didn't really knew where to post this so I'm posting it here, tell me if I'm wrong. I've created users with powershell on active directory, using a windows 8.1 2008 R2 server, the problem is that I cannot log in with the accounts I've created, there is a solution by changing something in the network account's policies, but I need my code to be portable, any thoughts ? I create my users with those parameters:

   

$props=@{
Name=$username
AccountExpirationDate='4/10/2016'
ChangePasswordAtLogon=$true
AccountPassword=$AccountPassword
Credential='Administrator'
Enabled=$true
HomeDirectory="P:\DossiersPersonnels\$username"
HomeDrive='P:'
HomePage='http://google.ch'
Manager='Administrator'
title='user'
POBox='25662'
ProfilePath="C:\Users\$username"
SamAccountName=$username
}

this is the error I get when I try to log in with one of the account:

 the sign-in method you're trying to use isn't allowed

Output help

$
0
0

So I am trying to generate a list that contains Users, the SamAccount, followed by associated PC's.  For all the PC's in our domain, I added a custom attribute - extensionattribute2 - which contains the SamAccount of the assigned user.  

The code I wrote gets the SamAccount of all users and assigns to a Variable.

Using a Foreach loop, I generate the Employee Name and then get a list of PC's assigned to the user.  

The problem is that the output in the CSV that is generated lists System.Object[]

as the PCName when there are multiple PC's per SamAccount

When I Use a Write-Host to output everything on the screen, it does what I expect.  

How can I get the same results to go to a CSV or even a text file?  

Here is my code: 

Import-Module activedirectory
## Get list of all SamAccounts
$CSVReport = "\\networklocation\allpcsanduser.csv"
$OUT=@()
$Names = (Get-ADUser -Properties * -Filter * | Where-Object {$_.Name -notlike '*!Template*'`
                                                -and $_.distinguishedname -notlike '*Training*'  `
                                                 -and $_.distinguishedname -notlike '*OU=Exchange Resource*'`
                                                   -and $_.distinguishedname -notlike '*OU=Resource Email*'`
                                                    -and $_.distinguishedname -notlike '*ServiceAccounts*'`
                                                     -and $_.distinguishedname -notlike '*OU=WorkstationID*'`
                                                      -and $_.distinguishedname -notlike '*OU=Pager*'`
                                                       -and $_.distinguishedname -notlike '*OU=Test ID*'`
                                                        -and $_.distinguishedname -notlike '*OU=Loaner Laptops*'`
                                                         -and $_.distinguishedname -notlike '*Builtin*'`
                                                          -and $_.distinguishedname -notlike '*OU=DeadPCs*'`
                                                           -and $_.distinguishedname -notlike '*OU=Auditor*'`
                                                            -and $_.distinguishedname -notlike '*Microsoft Exchange System Objects*'`
                                                             -and $_.Name -notlike '*krbtgt*'} | Sort-Object | Select-Object -ExpandProperty SamAccountName)

Foreach ($item in $Names)
        {
        $Employee = (Get-ADUser -Identity $item -Properties Name | Select-Object -ExpandProperty Name)
        $PCs = (Get-ADComputer -Filter{extensionAttribute2 -eq $item} -Properties * |Select-Object -ExpandProperty name)
        Write-Host ($Employee + "*" +  $item + "*"+ $PCs)
        $OUT+=New-Object PSObject -Property @{'Employee'=$Employee;'SAM'=$item;'PCName'=$PCs}
        $OUT | Select-Object Employee,SAM,PCName | Sort-Object Name | Export-Csv $CSVReport -NoTypeInformation
        }

The output I get on the screen looks like this:

Brady, Joe*JGB*BRADYJ BRADYJ-WINDOWS7
Brady, Mark*MGB*BRADYM-W
Brainerd, Evan*ewb*BRAINERDE-L
Braming, Stephanie*sgb*BRAMINGS-BLM BRAMINGSWIN764R BRAMINGS-V BRAMINGS-L

(I added the * to make it easier to copy/paste and then sort in Excel.)  

I am hoping I am missing something simple.  Thanks in advance.

Matt 


Matt Dillon


Remove Second Row From CSV

$
0
0

I've got a group of small CSV files - only about 15 and with about 30 rows each in. I'm running a script against them once a month so because they're so small and being processed infrequently they can read-in and treated as a string. I need to remove the second row of the file though and I've got nowhere with it so far.

Sample data:

TimeIndex,CPU,FCP,NFS,CIFS,ISCSI,NetworkIn,NetworkOut,NetworkTotal,Filername
TimeIndex,CPU,FCP,NFS,CIFS,ISCSI,NetworkIn,NetworkOut,NetworkTotal,000-samplehostname

So the header is correct, but the sample hostname on the second row would be different for each file and that row shouldn't be there. The simplest thing to do is just wipe that row entirely.

Any ideas?

Thanks in advance
Adam

Help: Converting Script to Non-Interactive

$
0
0

Hi all,

I have a pretty simple script for turning services off and on (usually used for multiple services that need to be processed in a particular order). What I need to do is convert it from using a switch established by a Read-Host question "Would you like to start or stop services" to something that I can just pass the state request inline with the script (i.e. service-test.ps1 -stop/-start). Below is the script as-is, what would I need to do to make it non-interactive?

Thanks!

Mike

# This script starts and stops services.
# Each section waits until the service is stopped before advancing the script.


#Set the names of the services
$TestService = 'AdobeARMservice'

#Establish Stop or Start
$State = Read-Host "Would you like to stop or start all services?"
Switch ( $State.ToUpper() ) {

#Stop services
    "Stop" {
    #Stops Service
    Stop-Service $TestService
    Write-Host $TestService'...' -NoNewLine
    $TestService = Get-Service $TestService
    While($TestService | Where-Object {$_.Status -eq 'Running'}){
    Write-Host '.'-NoNewLine
    Start-Sleep 3
    }
    Write-Host "`n$TestService stopped"

    Write-Host "All services have been stopped."
    }

#Starts services
    "Start" {

    #Starts service
    Start-Service $TestService
    Write-Host $TestService'...' -NoNewLine
    $TestService = Get-Service $TestService
    While($TestService | Where-Object {$_.Status -eq 'Stopped'}){
    Write-Host '.'-NoNewLine
    Start-Sleep 3
    }
    Write-Host "`n$TestService started"

    Write-Host "All services have been started."
    }
}


Michael Kaminski

Unable to query a service using powershell or command prompt

$
0
0

Hi All,

I have a service with the below details:

Service name: System Center Management APM

Service display name: Microsoft Monitoring Agent APM

When ever i try yo start / stop the service using command prompt or powershell it says as invalid service.

We need to enable this service in our 450 remote computers in the domain but not sure why is it not working only for this service.

Only this service is the issue and rest all services works fine.

Any help would be really appreciated.


Gautam.75801

FormatConditions.Add Method dont work

$
0
0

Hello

 I try to make a Excel Report form the AD.

I'd like to make some Format Condition in the Excelsheet. I use this Code for that

 
                $Selection = $Worksheet.Range("G:G")
                $Selection.FormatConditions.Add(2,0, $FormatPasswordNeverExpires) | Out-Null
                $Selection.FormatConditions.Item(1).Interior.Color = $BadColor
                $Selection.FormatConditions.Item(1).Font.Color = $BadText
                $Selection.FormatConditions.StopIfTrue = "False"

But i recive the following error

Exception calling "Add" with "3" argument(s): "The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))"
At line:141 char:17+                 $Selection.FormatConditions.Add(2,0, $FormatPasswordNeverExpires ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : ComMethodTargetInvocation

I think it is the second Parameter that is wrong, but I dont find a Solution.

Any help will be welcom

Andreas


Using Foreach within a pipeline

$
0
0

I am working on a Azure Dev/Test script where I am pulling in all my environment configurations via XML configuration file.  The file lists all the VM's that I need to create, the VM details and the associated disks that I need to attach.  Here is the structure of the XML that I am working with.

<VirtualMachine><Role>Web Server</Role><VMName>SCWEB01</VMName><InstanceName>SCWEB01</InstanceName><ScaledSize>A3</ScaledSize><ProdSize>D14</ProdSize><Disks><Disk><DiskLabel>Data</DiskLabel><DiskSize>500</DiskSize><LunNum>0</LunNum></Disk><Disk><DiskLabel>Logs</DiskLabel><DiskSize>500</DiskSize><LunNum>1</LunNum></Disk><Disk><DiskLabel>Stuff</DiskLabel><DiskSize>500</DiskSize><LunNum>2</LunNum></Disk></Disks></VirtualMachine>

What I am doing is looping thru each of the Virtual Machines and I am able to know that one VM has 3 disks and another VM has only two disks.  The problem is when I go and create the VM using New-AzureVMConfig, the VM creation and addition additions are all may thru pipelines.  

Here is the funciton that I created:

function Import-AzureDevTestVMList { [CmdletBinding(SupportsShouldProcess=$False,SupportsTransactions=$False,ConfirmImpact="None",DefaultParameterSetName="")] param([Parameter(Mandatory = $true)] [xml] $AzureConfigFile, [Parameter(Mandatory = $false)] [string] $CSVFileLocation) write-host "Number of Virtual Machines: " $AzureConfigFile.NetworkConfiguration.VirtualMachines.VirtualMachine.Count $NumberVmsIndex = $AzureConfigFile.NetworkConfiguration.VirtualMachines.VirtualMachine.Count $W2K8R2SP1image = Get-AzureVMImage | where { $_.ImageFamily -eq "Windows Server 2008 R2 SP1" } | Sort-Object -Descending -Property PublishedDate $W2012R2images = Get-AzureVMImage | where { $_.ImageFamily -eq "Windows Server 2012 R2 Datacenter" } | Sort-Object -Descending -Property PublishedDate $vmIndex = 0 FOREACH ($virtualMachine in $AzureConfigFile.NetworkConfiguration.VirtualMachines.VirtualMachine) { $domainjoin = $virtualMachine.Domain.DC1 + "." + $virtualMachine.Domain.DC2 $disks = $virtualMachine.Disks.Disk $diskCount = 0 $diskCount = $AzureConfigFile.NetworkConfiguration.VirtualMachines.VirtualMachine[$vmIndex].Disks.Disk.Count Write-Host "Current Index: " $vmIndex ":" $virtualMachine.VMName, $virtualMachine.Role, $virtualMachine.ImageName, "Disks: " $diskCount Foreach ($disk in $disks) { write-host "Found Disk: "$disk.DiskLabel,$disk.DiskSize,$disk.LunNum } if ($virtualMachine.ImageName -eq "Windows Server 2008 R2 SP1") { $vmconfigs = New-AzureVMConfig -Name $virtualMachine.VMName -InstanceSize $virtualMachine.InstanceName -ImageName $W2K8R2SP1image[0].ImageName | Add-AzureProvisioningConfig -WindowsDomain -JoinDomain $domainjoin -Domain $virtualMachine.Domain.OU -DomainUserName $virtualMachine.DomainUser -DomainPassword $virtualMachine.DomainPassword -AdminUsername $virtualMachine.LocalAdminUser -Password $virtualMachine.LocalAdminPassword |% ($disks) | Add-AzureDataDisk -CreateNew -DiskSizeInGB $disks.DiskSize -DiskLabel $disks.DiskLabel -LUN $disks.LunNum

} else { $vmconfigs = New-AzureVMConfig -Name $virtualMachine.VMName -InstanceSize $virtualMachine.InstanceName -ImageName $W2012R2images[0].ImageName | Add-AzureProvisioningConfig -WindowsDomain -JoinDomain $domainjoin -Domain $virtualMachine.Domain.OU -DomainUserName $virtualMachine.DomainUser -DomainPassword $virtualMachine.DomainPassword -AdminUsername $virtualMachine.LocalAdminUser -Password $virtualMachine.LocalAdminPassword #$vmconfigs | Select-Object = Add-AzureDataDisk -CreateNew -DiskSizeInGB $disk.DiskSize -DiskLabel $disk.DiskLabel -LUN $disk.LunNum } $vmIndex = $vmIndex + 1 } return $vmconfigs }

My question is how would you loop thru an object that as a variable number of sub elements.  I have tried various ways of doing a for-each within a pipelined for-each but none of them allow me to add the disks.
            $vmconfigs = New-AzureVMConfig -Name $virtualMachine.VMName -InstanceSize $virtualMachine.InstanceName -ImageName $W2K8R2SP1image[0].ImageName |
            Add-AzureProvisioningConfig -WindowsDomain -JoinDomain $domainjoin -Domain $virtualMachine.Domain.OU -DomainUserName $virtualMachine.DomainUser -DomainPassword $virtualMachine.DomainPassword -AdminUsername $virtualMachine.LocalAdminUser -Password $virtualMachine.LocalAdminPassword |% ($disks) | Add-AzureDataDisk -CreateNew -DiskSizeInGB $disks.DiskSize -DiskLabel $disks.DiskLabel -LUN $disks.LunNum 
If anyone has any guidance on this, I would greatly appreciate it.



Get Richtextbox text length

$
0
0

Hey all I'm righting a little GUI. My problem is I need to use a richtextbox but there doesn't seem to be a way to get the length or count of characters in the richtextbox. I was looking here https://msdn.microsoft.com/en-us/library/System.Windows.Forms.RichTextBox_properties(v=vs.110).aspx and it looks like selection length or text length should work but it doesn't seem I have these options. Does anyone have any ideas?

Ultimately I want to determine if there is already text in the richtextbox and if there is go down a line if not stay on the first line.

Thanks!! 

help with encoding and decoding a file

$
0
0

I'm writing a couple of scripts that will transfer a file using UDP.

I'm testing reading in a file and writing it back out on the same computer and need some guidance.

#this reads in the file, encodes it, writes it back out in the encoded form.

$localpath = "c:\test\test.log"
$contents = [IO.File]::ReadAllBytes($localPath)
$contents = [Text.Encoding]::ASCII.GetBytes($contents)
[io.file]::WriteAllBytes('c:\test\test1.log',$contents)

#I'm trying to read in the encoded data and decode and write it back out, but I get an error

$localpath1 = "c:\test\test1.log"
$contents1 = [IO.File]::ReadAllBytes($localPath1)
$contents1=[Text.Encoding]::ASCII.GetString($contents1)
[io.file]::WriteAllBytes('c:\test\test2.log',$contents1)

Here is the error I get

Cannot convert argument "1", with value: "91 50 48 49 52 45 48 57 45 50 57 32 49 48 58 52 50 58 48 51 44 48 56 56 93 32 91 73 78 70 79 93 32 67 108 
105 101 110 116 32 82 80 67 32 108 105 115 116 101 110 105 110 103 32 111 110 32 49 50 55 46 48 46 48 46 49 58 54 48 54 51 32 46 46 46 13 10 91 50 4
8 49 52 45 48 57 45 50 57 32 49 55 58 48 49 58 52 54 44 53 48 57 93 32 91 73 78 70 79 93 32 71 111 116 32 108 111 103 111 117 116 32 97 108 101 114 
116 32 102 111 114 32 101 108 111 103 101 115 111 110", for "WriteAllBytes" to type "System.Byte[]": "Cannot convert value "91 50 48 49 52 45 48 57 
45 50 57 32 49 48 58 52 50 58 48 51 44 48 56 56 93 32 91 73 78 70 79 93 32 67 108 105 101 110 116 32 82 80 67 32 108 105 115 116 101 110 105 110 103
 32 111 110 32 49 50 55 46 48 46 48 46 49 58 54 48 54 51 32 46 46 46 13 10 91 50 48 49 52 45 48 57 45 50 57 32 49 55 58 48 49 58 52 54 44 53 48 57 9
3 32 91 73 78 70 79 93 32 71 111 116 32 108 111 103 111 117 116 32 97 108 101 114 116 32 102 111 114 32 101 108 111 103 101 115 111 110" to type "Sy
stem.Byte[]". Error: "Cannot convert value "

Thanks for any advice.

Why is my compare script finding group inheritance ?

$
0
0

Hello,

When I run my script it is returning groups that do not have the user AD group membership in it directly.

Example if the person is a member of the Local Admins Group it is returning that he is a member of power user, backup operators, remote desktop users.

I just want to know if the AD group is in the local group or not.

Clear-Host
#This script gets the group and nested members of a user and compares it to the local groups on a server.
# If the user group is part of the local group it returns TRUE otherwise FALSE.

#*******************************************************
#Gets nested group members for an user
function GetGroups ($object)
{
    Get-ADPrincipalGroupMembership $object | ForEach `
    {
        $_
#       Get-ADPrincipalGroupMembership $_
  GetGroups $_  
    }
}
#*********************************************************
# Uncomment this line to grab list of computers from a file
 $Servers = Get-Content c:\temp\!_listv2.txt
#$Server = $env:computername # for testing on local computer
#$Servers = "xxxxxxx" # for testing on local computer

# User Information to run against a server.
$User = Get-ADUser "UserABC" -properties memberOf # user ID to compare against.
#$User = Read-Host 'What is the username?'

# Retrieves AD groups that the user is a member of
#$ADGroups = GetGroups $user | select name -Unique
[Array] $ADGroups = GetGroups $User | Where-Object -FilterScript {
    $psitem -notin ('CN=Domain Users,CN=Builtin,DC=hteeter,DC=ht', 'CN=Users,CN=Builtin,DC=hteeter,DC=ht','CN=CERTSVC_DCOM_ACCESS,CN=Builtin,DC=hteeter,DC=ht')
}

# Change these two to suit your needs
#$ChildGroups = "domain users" # Compare to a single local domain group
$ChildGroups = $adgroups.name

#$LocalGroups = "Remote Desktop Users" # Compare to a single local group
 $localgroups = Get-WMIObject win32_group -filter "LocalAccount='$true'" -computername $Servers | select name
 
$MemberNames = @()

foreach ($localgroup in $LocalGroups.name)
{ foreach ($Server in $Servers)

 $Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
       $Members = @($Group.psbase.Invoke("Members"))
       $Members | ForEach-Object {
                $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
        }
        $ChildGroups | ForEach-Object {
                $output = "" | Select-Object Server, LocalGroup, AD_Group, InLocalGrp
                $output.Server = $Server
    $output.LocalGroup = $LocalGroup
                $output.AD_Group = $_
    $output.InLocalGrp = $MemberNames -contains $_
                Write-Output $output
    $output | Export-Csv c:\temp\compare.csv -Append -NoTypeInformation
    
    
        }
}

}

Passing a Variable to Write-Host with format table in color

$
0
0

I'm trying to check if backups are running or not.  My code seems to work fine.  I'm trying to output in color, however the whole line is in color.  I only want one column in color.  Example if it's "true" color the word"true" in green, and leave all else gray.  if it's "false" color the word "false" in red.

example:

Name:      BackupInProgress

Database1True <-----want this in green

Database2False <-----want this inn red

$Servers = Get-Content C:\serverlist.txt

foreach($Server in $Servers) {

$Check = Get-StorageGroup -Server $Server | Get-MailboxDatabase -Status | Select Name, BackupInProgress
if ($check.BackupInProgress -eq $true) {
Write-Host -ForegroundColor Green ($check | ft | Out-String)
}
else {
Write-Host -ForegroundColor Red ($check | ft | Out-String)
}
}

PowerShell Stopwatch Format

$
0
0

Hi,

So, I am trying to change the format of the output generated when using [diagnostic.stopwatch] StartNew()

$resultstime = new-timespan -Minutes 1
$resultstime = [diagnostics.stopwatch]::StartNew()
$resultstime.Elapsed

The above will give me a format of 'hh:mm:ss:ms' as an example: 00:00:10:62499, this is great but I would rather negate the milliseconds and just have 'hh:mm:ss'

Can this be done? If so, please help.

Call get-credential from within a Runspace

$
0
0

Hey all so I'm having some trouble calling get-credential from within a runspace. Popup messages work fine so I would think this should too. I know I can use get-credential outside of the runspace and pass the value to it but is there anyway I can do it inside?

Here's my test:

$hash = [hashtable]::Synchronized(@{})
$hash.Host = $host
$hash.flag = $false
$runspace = [runspacefactory]::CreateRunspace()
$runspace.Open()

$runspace.SessionStateProxy.SetVariable('Hash',$hash)
$powershell = [powershell]::Create()
$powershell.Runspace = $runspace

$powershell.AddScript({
    Get-Credential
}) | Out-Null

$handle = $powershell.BeginInvoke()

While (-Not $handle.IsCompleted) {
    Start-Sleep -Milliseconds 100
}

$powershell.EndInvoke($handle)
$runspace.Close()
$powershell.Dispose()

Thanks I'm still really knew to runspaces and would love any help.

Building an array of custom objects

$
0
0

I am trying to use regular expressions (-imatch) to search for hyperlinks in word documents and output a list of filepath/hyperlink pairs found. Please don't laugh at my code for finding the hyperlinks. It is probably far from optimal, but it is working. What I can't get to work is probably the easier part of the project - building the table of results. What I tried to do is create a custom object called $Output with two NoteProperty members called FlPth (for the filepaths) and Hyperlink (for the hyperlinks). The I have an array called $colOutput which is supposed to collect all the individual $Outputs as I step through files containing hyperlinks. In the end I just get an array full of 20 identical pairs of FlPth/Hyperlink pairs. I know as it steps through them I am getting the right values for FlPth and Hyperlink, but something is wrong with the way I am adding them to my array. Can you tell me where my error is?

$Path = "M:\My Documents\GoodSync\SOPSnap\QA" # Temporary path to concentrate on a problem file!
#$Path = "M:\My Documents\GoodSync\SOPSnap" #This is the general path.
$Regex = '\x13\s*HYPERLINK.*\x14' # Regex to catch Hyperlinks in word docs. It works!
$Excludes = '(\\_gsdata_\\|\\Archive\\|\\Drafts\\|\\Folder Settings\\|\\SOPSignOff\\|\\SOPSignOffHistory\\|\\Trash\\|lnk$)' # paths to skip
[System.Collections.ArrayList]$colOutput = @() # Make an arraylist for the results
$idx = 0 #array index counter
$output = New-Object -TypeName PSObject
$Output | Add-Member -type NoteProperty -Name FlPth -Value ""
$Output | Add-Member -type NoteProperty -Name Hyperlink -Value ""
$output | Get-Member | Format-Table

# Get all the files in $Path that end in ".doc". Expand this later to include .docx and .docm files as well and add the code to get into them
Get-ChildItem $Path -Filter "*.doc" -Recurse | #only doc files 
   Where-Object { $_.Attributes -ne "Directory" -and $_.FullName -notmatch $Excludes} |
      ForEach-Object {
         $FlPthTemp = $_.FullName
         $MatchedLine = Get-Content $FlPthTemp | Select-String -Pattern $Regex -Allmatches |
            ForEach-Object {
                $_ -imatch '(?<=\x13\s*HYPERLINK).*(?=\x14)' | out-null; $Hlink = $Matches[0]
                $idx 
                $Output.FlPth = $FlPthTemp
                $Output.Hyperlink = $Hlink
                $colOutput.Add($Output)
            }
        }
         
          
#Export the results to a csv
$colOutput | Format-List



WMI Win32_VideoController and differentiating integrated vs discrete graphics

$
0
0
I am trying to do some hardware and config inventory with WMI and I am having trouble with graphics cards in certain circumstances. I can use something like this (get-wmiobject -class:'Win32_VideoController' -namespace:'root\CIMV2' -computername:'.').DriverVersion and I will get the driver version of the currently active card. Works great for a desktop machine, but for a laptop with both integrated and discrete graphics, unless some program that triggers discrete graphics is also running, I get inventory info about the Intel HD only, and in 99% of cases what I really want is the discrete graphics. I figure there are two possible ways to address it. Either there is a way to use WMI to get all installed cards, not just the currently active one, or there is a PowerShell way to specifically trigger use of the discrete card. Can anyone point me in the right direction?

Search a file share. Filepath is to long and no count

$
0
0

Hi guys,

Please have a look at this code. It  works fine for normal directories only on a fileshare it gives the error filepath is to long.

And i need a of all the files it pops up. But when i use the count option i don't get the list.

When i use a for each object with count it does not give me output in a file. Can you help me a bit on this.

Maybe change it to "System.IO"?

$systems = 'D:\temp\serverlist.txt'
$output = 'D:\temp\result.txt'


ForEach ($system in (Get-Content $systems))
 {
      Invoke-Command -ComputerName $system -ScriptBlock  {
      get-psdrive -p "FileSystem" `
|     % {
               get-childitem $_.Root -include *financial* -recurse  | sort-object Length -descending


    }
 }  | out-file $output } 

Kind regards,


-match not working

$
0
0

Hi All,

I am searching uninstall string in registry for all installed components which start with SQL Server and end with Services

The following script is not working.  Please advise what i am doing wrong.

$unInstall64 = Get-ChildItem  "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match  "^SQL Server.*Services$" } | select UninstallString 
$uninstall64

Thanks

Replacing Single Line of Code in XML File on Multiple Systems

$
0
0

Hey Guys -

I'm not a pro PowerShell user, but dabble in it when I can.  I have a task I need to perform which I need assistance with, please - one that I'd think would be easy for the pros.

I am needing to deploy a script which will change a single line of code in an XML files on multiple systems on our domain.  The challenge is that the XML also contains user-specific data which is why I can't just copy/replace a new file in.  Here's what I'm wanting it to do:

- See if XML has a line that starts with "<isolationLevel"

- If so, replace it with another similar line of code

That's it - Is this easily possible?  Thanks!


Ben K.

Strange behaviour of read-host

$
0
0

Hello, after some hours fighting against PowerShell (v3.0 in Win2012 and v4.0 in Win8.1) I have found an strange behavior in my script.

I ask for a text to the user (using "$text = Read-Host") and I append it to an array one by one. In the middle of this process I have to show some additional information to the user, so I print it in screen and use an additional "Read-Host 'Press ENTER'" before clean the screen.

When I show the content of the array it have more items than I expect. Why?

Next script is a very simplify version with minimal lines:

#__________________________________________________________________________________________________
#__________________________________________________________________________________________________
function capturarNivel1(){
    Write-Host " ------ Strange error ------ "
    $tmptxt = Read-Host "`nIntro text to be captured";
    Read-Host "Press ENTER  or Intro text. IT IS CAPTURED BY ERROR"
    Write-Host "`nreturned value tmptxt=[$tmptxt]`n" # Here the captured value is correct
    return $tmptxt
    }
#__________________________________________________________________________________________________
#__________________________________________________________________________________________________
function main(){
    $lFiltros = @()
    Clear-Host

    $filtro = capturarNivel1
    Write-Host "`nreceived value filtro=[$filtro]`n"
    $lFiltros += $filtro
    foreach($s in $lFiltros){
        Write-Host "[$s]"
        }
    }
#__________________________________________________________________________________________________
#__________________________________________________________________________________________________

main

The output is this:

 ------ Strange error ------

Intro text to be captured: AAAAAAAA
Press ENTER  or Intro text. IT IS CAPTURED BY ERROR: 11111111

returned value tmptxt=[AAAAAAAA]


received value filtro=[11111111 AAAAAAAA]

[11111111]
[AAAAAAAA]
PS C:\Users\Pablo\Desktop\ErrorPowerShell>

Viewing all 21975 articles
Browse latest View live


Latest Images

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