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

find ALL the attributes of a cmdlet

$
0
0

In another thread someone suggested I read this tip

https://technet.microsoft.com/en-us/library/ff730948.aspx

In there I learned that creationtime is part of cmdlet childitem but get help does not show it.  Now that I know it exists the following operation can acquire it:

get-childitem a.txt|select-object name,creationtime

The conclusion is that at lease one cmdlets has one or more hidden attributes.  A reasonable presumption is that many more cmdlets also have hidden attributes. (That is not a good thing by the way.  The cmdletshow-help childitem should present ALL the attributes and methods.) 

QUESTION:

How can I discover all the hidden attributes of any given cmdlet?


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


How to find updates installed

$
0
0

Hi all how to find the updates installed in 2003 and 8.. wimc qfe didnt give the exact output as what i see in updates installed in my system... found the below code but is not working 2003 and 8 os...

$Session = New-Object -ComObject "Microsoft.Update.Session" 
$Searcher = $Session.CreateUpdateSearcher() 
$historyCount = $Searcher.GetTotalHistoryCount() 
$b = $Searcher.QueryHistory(0, $historyCount) | Select-Object Date,Title, 
@{name="Operation"; expression={switch($_.operation){ 
1. {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}}}},

@{name="Status"; expression={switch($_.resultcode){ 
1. {"In Progress"}; 2 {"Succeeded"}; 3 {"Succeeded With Errors"};

1. {"Failed"}; 5 {"Aborted"}

Can some one help me in getting the exact out put for 2003 & 8

PowerShell set media playing position for playing using System.Windows.Media.MediaPlayer

$
0
0

Hi,

I am using System.Windows.Media.MediaPlayer in my PowerShell code.
Using Get-Members I can see, position property can be set/get.

Position  Property   System.TimeSpan Position {get;set;} 

If I try to set that, using

$media.Position.Seconds = 40 # error saying its read only property

and try to play audio file, an error happens.

Also, I am not able to get event firing, using:

Register-ObjectEvent -InputObject $Media -EventName MediaOpened -Action {Write-Host "hi"}

How can I get this done,using PowerShell and System.Windows.Media.MediaPlayer

Azure AD Module on Server 2012 R2

$
0
0

Hi all

I'm attempting to install and use the Azure AD module on Server 2012 R2 to administer an Office 365 tenant.
Does anyone know if this is supported?

The sign-in assistant and module installer appear to install fine, but the files never got copied into C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

When trying to use Import-Module I get a ResourceUnavailable message (as the files aren't there of course)

Is there something I'm missing? Or is this simply not supported on Server 2012 R2?

Cheers!

Running PowerShell script from console, or .exe file, without error, while using file dialog boxes.

$
0
0

Hi,

I have a script, which has file open dialog box statement in it, with Windows Forms, for its front end. If I run script from PoweShell ISE, it runs fine. The forms look, feel and file open dialog box behaves as usual.

The moment, I run script from console, or convert it to .exe file using PS2Exe, the two unusual things happen:

  1. The forms look and feel, looks outdated and plain.
  2. When I click button, for file open dialog box, the whole UI hangs and it becomes unresponsive.

Why is this so? How can I overcome this?

# code snippet
Add-Type -AssemblyName System.Windows.Forms
[reflection.assembly]::loadwithpartialname("system.windows.forms") | Out-Null

# form
$form = New-Object System.Windows.Forms.Form
$form.Height = 700
# rest of the code
$form.ShowDialog()

# open dialog code
$filedialog = New-Object System.Windows.Forms.OpenFileDialog
    $filedialog.initialDirectory = $initialDirectory
    $filedialog.filter = "All files (*.*)| *.txt*"
    $filedialog.ShowDialog() | Out-Null
    $form.Text = $filedialog.fileName

What is cause and solution for this problem?

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

$
0
0

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

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

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

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

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

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

Thank you.


zarberg@gmail.com

Set Outlook Folder and subfolders permissions using Powershell or vbs in Outlook. NOT on Exchange server.

$
0
0

Hi everybody,

Users need often to grant other user(s) access to the mailbox folder and all of its subfolders. Most users have 10s of folders and 10s of subfolders in their mailbox in Outlook 2010. These users have no access to the Exchange server neither do I.
I know it’s easy to get this done on the Exchange server but our Exchange is hosted somewhere else and it takes days to get things done and we just cannot wait!
My questions is: is there an automated way or script to run on the Windows 7 workstation where Outlook 2010 is installed (NOT on the Exchange server) to set the access permissions for other user(s) on a mailbox / folder and all of it’s subfolders at once?

Any help would be very appreciated. TIA.


win_builder

Fetch client IP addresses from the Netlogon.log file of all domain controllers in the domain

$
0
0

Hi,

The event ID 5807 is logged in the system logs of domain controllers as a result of which the IP addresses for the missing subnets are logged in Netlogon.log under %systemroot%/debug. The end goal is to fetch the IP addresses along with rest of the respective attributes from the Netlogon.log for all the domain controllers in the domain. I have the following script however, it gives me a 0KB file despite the fact that the Netlogon.log on the DC contains ample entries from last two months. 

function GetDomainControllers {
    $DCs=[system.directoryservices.activedirectory.domain]::GetCurrentDomain() | ForEach-Object {$_.DomainControllers} | ForEach-Object {$_.Name}
    return $DCs

}

function GetNetLogonFile ($server) {
    $path= '\\' + $server + '\c$\windows\debug\netlogon.log'
    try {$netlogon=get-content -Path $path -ErrorAction stop}
    catch { "Can't open $path"}
    #reverse the array's order to the end of the file
    [array]::Reverse($netlogon)
    $IPs=@()
    foreach ($line in $netlogon) {
        #split the line into pieces using a space as the delimiter
        $splitline=$line.split(' ')
        #Get the date stamp which is in the mm/dd format
        $logdate=$splitline[0]
        #split the date
        $logdatesplit=($logdate.split('/'))
        [int]$logmonth=$logdatesplit[0]
#last month and this month
        if (($logmonth -eq $thismonth) -or ($logmonth -eq $lastmonth)) {
            #only push it into an array if it matches an IP address format
            if ($splitline[5] -match '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'){
                $objuser = new-object system.object
                $objuser | add-member -type NoteProperty -name IPaddress -value $splitline[5]
                $objuser | add-member -type NoteProperty -name Computername -value $splitline[4]
                $objuser | add-member -type NoteProperty -name Server -value $server
                $objuser | add-member -type NoteProperty -name Date -value $splitline[0]
                $objuser | add-member -type NoteProperty -name Time -value $splitline[1]
                $IPs+=$objuser
            }
        } else {
            #break out of loop if the date is not this month or last month
            break
        }
    }
    return $IPs
}

#Get last month's date
$thismonth=(get-date).month
$lastmonth=((get-date).addmonths(-1)).month

#get all the domain controllers
$DomainControllers=GetDomainControllers
#Get the Netlogon.log from each DC
Foreach ($DomainController in $DomainControllers) {
    $IPsFromDC=GetNetLogonFile($DomainController)
    $allIPs+=$IPsFromDC
}

$allIPs | Sort-Object -Property IPaddress -Unique | Export-Csv "E:\bin\NetlogonIPs.csv"

PLEASE HELP!!


High light a row....

$
0
0

Am using the below code to display a Disk usage for Drives and to highlight the color as red if %free is above 85, but it didnt show up.. can some one help

a = Get-WmiObject Win32_LogicalDisk -filter "DriveType=3" -computer $textbox1Computername.Text |Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}},@{Name="% Free";Expression={((($_.freespace/1GB)/($_.size/1GB))*100).tostring("0.00")}}
$datagridview1.DataSource = [system.Collections.ArrayList]$a
$datagridview1.Rows |
ForEach-Object{
if ($_.Cells['% Free'].Value -gt '85')
{
$_.Cells | %{ $_.Style.BackColor = 'Red' }
}
else
{
$_.Cells | %{ $_.Style.BackColor = 'White' }

}
}

 

Powershell script to list Server Name and the current Windows Proxy server & port in use into CSV

$
0
0

People,

Can anyone here please assist me with the script below to list Server Name, the current Windows Proxy server & port in use into CSV ?


Import-Module ActiveDirectory

$Computers = Get-ADComputer -Filter * -SearchBase "OU=Production Servers,OU=Servers,DC=domain,DC=com" |

Where-Object { Test-Connection $_.Name -Count 1 -Quiet }

ForEach ($Computer in $Computers) {

.

.

.

| Export-csv "C:\Proxy-Setting.csv" -Append -NoTypeInformation -UseCulture

}


Thanks in advance.


/* Server Support Specialist */


out-file to a line not the end

$
0
0

Hi guys,

I have a script problem I'm trying to resolve. I want it so that a user can edit a single line of a txt tile. Is this possible using the out-file command?

"out-file 'C:\temp.txt' -append -inputobject $user_input"

This will add the line to the end of the file, but that's not what I want it do. Suppose I have a text file that looks like this.

1.Hello

2. Dad

3. Mum

and I want to edit it so hello is now bye. Why can't i just do:

"out-file 'C:\temp.txt'[0] -append -inputobject $user_input"

When I run this nothing happens. Any ideas?

Will the ‘Piping’, ‘Sort-Object –Property’ and ‘Select-Object’ query be executed at Lync Server side or at the client?

$
0
0
Hi,

I am writing a C# client, in which I want to get the last modified Lync user from the server which is hosted in different machine.
The powershell command I am planning to use to get such user is,
Get-CsUser -ResultSize 1 | Sort-Object -Property WhenChanged –Descending | Select-Object WhenChanged

Now I want to know, whether all the Sorting and the selecting WhenChanged attribute is done in server side.
Or does Get-CsUser return all the users to my C# client, where the remaining query is applied?

To put it in another way, are these three tasks are done at Lync server side?
1> Piping
2> Sort-Object -Property
3> Select-Object

Thanks in advance,
Sandeep

Script gets through two folders then hangs

$
0
0

Hi guys. My script is a slightly modified version of something I found elsewhere. What it does is take one directory and move all files in that directory that are a day old or less to another directory while maintaining the file structure. It compares the date for each file rather than on the directory.

The issue I'm having is that it gets through two folders then just hangs. I never get an error or anything like that. It simply doesn't go to the next file and I don't know why.

$sourceDir = "E:\iSpy\video\"
$targetDir = "F:\Recordings\"

Get-ChildItem $sourceDir -filter "*.mp4" -recurse | where-object {$_.lastwritetime -gt (Get-Date).Adddays(-1)} | `
    foreach{
        $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
        New-Item -ItemType File -Path $targetFile -Force;
        Copy-Item $_.FullName -destination $targetFile -whatif
    } 

Powershell "RunAs" causing recycle bin issues. Would like some input please.

$
0
0

I developed a script to assist our UserAdmins with creation of AD user accounts and create home folders on the server shares.  I am encountering an issue with the recycle bin becoming corrupt when the user first logs in.  This script must be run with an elevated account with permissions to the shares.  I also noted a change in the way the recycle bin is displayed in the share.

The home folder is created using: 

New-Item -ItemType Directory -Force -Path $directory

If I log into my machine as my elevated account and run powershell/powershell_ise, all is well.  The recycle bin displays as "Recycle Bin" with the correct icon image

However, if I log into my machine with my non-elevated account and select "Run as a different user" for Powershell or Powershell_ISE and use my same elevated account from above the users receive "corrupt" recycle bin errors when logging in or viewing the recycle bin properties.  Additionally, recycle bin is now listed as "$Recyle.Bin" and is using a folder icon.  This issue is resolved by removing the users AD account from the home folder permissions and re-adding it with identical permissions.

I see this behavior using Win8.1 x64 as well as Win7 x64 Enterprise.

On another somewhat relevant topic, when launching Powershell_ISE with "Run as a different user" it often freezes and must be forcibly closed.  Could be relevant, could be coincidence.

I appreciate any input you may have regarding this issue.

Thanks,

Jeff


PowerShell Remoting Issues, no data returned

$
0
0

Hello,

I'm a bit confused about PowerShell remoting. I want to get the canonical name of an OU using its GUID. I tried to do this will PowerShell however basic commands don't work when usingRemoting. For example

Run locally
([adsi]'LDAP://DC=demoxenapp,DC=int').DistinguishedName
Returns DC=demoxenapp,DC=int

Run over remoting session (using PowerShell ISE)
([adsi]'LDAP://DC=demoxenapp,DC=int').DistinguishedNameReturns an empty string.

Run over remoting session (using PowerShell ISE)
([adsi]'LDAP://DC=demoxenapp,DC=int')
I expect a DirectoryEntry however I get

Value for dictionary entry is not specified.
    + CategoryInfo          :
    + FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException
 

Any ideas....?

Thanks!


Dave



David Homer


Move-Item -force -bruteforce! -THE force!!!!!!

$
0
0

Hey guys, I'm trying to move some folders after a backup to overwrite old backups...i read online that Move-Item with -force will overwrite but no such luck

"Can't move file because files with the same name exist"

Move-Item H:\VMBackup\Current\* H:\VMBackup\Old -force

Do any of you know how to actually do this?  Google has let me down today.

Communication between scripts and remote job termination

$
0
0

Hello,

I have a script that starts some long running remote jobs, waits for them to finish and then processes data.

The script is started from Jenkins, therefore I don't have PowerShell console opened on my screen but its running as a process.

Problem is that I don't know how to efficiently terminate the script and all remote jobs it has started, if I kill the main script (killing the PowerShell.exe) it does not stop the remote jobs.

I was thinking to create a second script and to notify the first script that it should end, while the first script would terminate its remote jobs and preferably does some cleaning on the remote machines, but I still don't know how to do it technically. Does anybody have some idea how to communicate between scripts (while one of them is already running) or how to get hold of running remote jobs from another PowerShell instance?

Thank you!

Why does my script ignore values in variable only some of the time?

$
0
0

Hello,

I'm a beginner at Powershell and am writing a script to gather the deployment details on all Azure Cloud Services attached to a Azure Subscription, including the info for any service that does not have a deployment.  

I understand that the way I'm going about this may be wrong and I am NOT looking for any help creating a final script.  Some of my script is written specifically so that I can better understand what it's doing (for learning purposes).

What I am looking for is help understand why my current script behaves the way it does.

Here's my current script:

###
#Create a report that shows the created date and latest deployment date for all
#hosted services (cloud services)deployments in MyAzureSubscription
###
Select-AzureSubscription MyAzureSubscription
$ServiceNames = Get-azureservice

foreach ($service in $ServiceNames){

        $ServiceName = $service | select -ExpandProperty ServiceName
        $ServiceDateModified = $service | select -ExpandProperty DateModified
        $service |
        get-azuredeployment -ErrorAction SilentlyContinue -ErrorVariable NoDeployment |
        Select @{Name="ServiceName";Expression={$ServiceName}}, DeploymentName, Status, CreatedTime, LastModifiedTime, @{Name="ServiceDateModified";Expression={$ServiecDateModified}}, @{Name="NoDeployment";Expression={$NoDeployment}} |
        Sort-Object -Propert DeploymentName |
        export-csv "outputfile.csv" -notypeinformation -append

        #Test statements below
        #Write-Host "NoDeployment Below:"
        #$Service | select ServiceName | Write-Host
        #Write-Error $NoDeployment
        Write-Host $ServiceName
        }

The output file only contains a list of servicenames and deployment details for services that do have a deployment.  None of the services that have no deployments are added/exported to the csv file.  However, the "write-host $ServiceName" writes ALL the service names in the powershell window, regardless of whether there's a deployment or not.

What I don't understand is why the Select @{Name="ServiceName";Expression={$ServiceName}} only outputs the service names of services that have deployments instead of ALL service names regardless of whether they have a deployment or not.

I've already proven that the variable $ServiceName does, at some point, save the ServiceName into the $ServiceName variable by writing it to host on each iteration of the foreach loop.  So why is it ignoring some ServiceNames when outputting/exporting to the csv file?

Thanks!

Concatenate string from parameter without quotes

$
0
0

I am trying to insert text into the middle of a long text string. For simplicity, I have a fixed value $Beginning and a fixed value $Ending. $Middle is passed as a parameter. I then simply concatenate the three strings:

$Whole = $Beginning + $Middle + $Ending

Very simple.  If I declare $Middle within the script, such as $Middle = "Here is the middle", the quotes are not included in the final string, and I end up with $Whole =  "Here is the beginning, Here is the middle, Here is the end". 

But when $Middle is passed as a parameter (which requires quotes to capture the entire string), the quotes become part of the string, and I end up with $Whole = "Here is the beginning, "Here is the middle", Here is the end".

Why the difference? How do I concatenate strings passed as parameters without including the quotes?




Compare two directories

$
0
0

Hello guys,

I need to migrate a few file shares. I ll use robocopy to migrate from server 1 to server 2. Because its a lot of folders and files i would like to at the end of each script to call a power shell script to compare (by size) source and the destination and if they are different to send an alert.

I have tried a few script but they list all the contents of the directories with the space when all i want its just the root of the directories.

Can any one help me and point me on the right direction.

Regards,

Arestas

Viewing all 21975 articles
Browse latest View live