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

Question on get-aduser and properties

$
0
0

I am fairly new to PowerShell and have gotten quite a bit of help browsing the Forums and asking questions.

I have been working on getting Properties from get-aduser, and its bafflilng to me on the below examples.

To find if a user account is enabled I have used:

get-aduser -identity USERNAME | %{$_.enabled}

   This will return True or False

To check if a user account is Locked I found this will return True or False

(get-aduser -identity USERNAME -Properties LockedOut).LockedOut

Why is this?  When I try

get-aduser -identity USERNAME | %{$_.LockedOut}, it returns blank

Subsequently if I try

(get-aduser -identity USERNAME -Properties Enabled).Enabled, it returns blank.


Calculate bandwidth per user bandwidth usage for RRAS users

$
0
0

Hello PowerShell Experts,

I am trying to make a script in powershell that can detect that how much bandwidth each RRAS(Routing and remote Access VPN Server) connected user is consuming, then adding up individual bandwidth and compare it to the total available bandwidth on the server. Can any body provide me with the logic of the script or some article or hint using which this can be achieved.

Thank You.

Frank

Help Needed in Reading lines

$
0
0

Hi,

I am trying to read the file from text file and inserting into sqlserver table. I am facing trick issue, The code is reading the file but inserts into null value.

table structure:

create table Sample(Id int primary key identity(1,1),Name varchar(100),Age int)

sample code which loops through

$datatable = New-Object "System.Data.DataTable"
 $datatable.Columns.Add("Name",[string])
 $datatable.Columns.Add("Age", [int])
  # Read in the data, line by line
    while (($line = $reader.ReadLine()) -ne $null)  {

			 $data = $line.Split("|")
			 $row = $datatable.NewRow()
			 $row.Item("Name") = $data[0]
			 $row.Item("Age") = [int]$data[1]
			 $datatable.Rows.Add($row)


        # Once you reach your batch size, write to the db,
        # then clear the datatable from memory
        $i++; if (($i % $batchsize) -eq 0) {
        $bulkcopy.WriteToServer($datatable)
        Write-Output "$i rows have been inserted in $($elapsed.Elapsed.ToString()).";
        $datatable.Clear()
        }
    }  

sample data

Name1|10
Name2|20
Name3|30
Script started...
Property 'EnableStreaming' cannot be found
At E:\Sample\PowerShell\Test.PS1:4+ $bulkcopy. <<<< EnableStreaming = 1+ CategoryInfo          : InvalidOperat+ FullyQualifiedErrorId : PropertyAssig



AllowDBNull        : True
AutoIncrement      : False
AutoIncrementSeed  : 0
AutoIncrementStep  : 1
Caption            : Name
ColumnName         : Name
Prefix             :
DataType           : System.String
DateTimeMode       : UnspecifiedLocal
DefaultValue       :
Expression         :
ExtendedProperties : {}
MaxLength          : -1
Namespace          :
Ordinal            : 0
ReadOnly           : False
Table              : {}
Unique             : False
ColumnMapping      : Element
Site               :
Container          :
DesignMode         : False

AllowDBNull        : True
AutoIncrement      : False
AutoIncrementSeed  : 0
AutoIncrementStep  : 1
Caption            : Age
ColumnName         : Age
Prefix             :
DataType           : System.Int32
DateTimeMode       : UnspecifiedLocal
DefaultValue       :
Expression         :
ExtendedProperties : {}
MaxLength          : -1
Namespace          :
Ordinal            : 1
ReadOnly           : False
Table              : {}
Unique             : False
ColumnMapping      : Element
Site               :
Container          :
DesignMode         : False

It's putting age values in Name column and makes age column is null. not sure why it skips the name column. Any suggestions please


loving dotnet

Powershell script as a scheduled task

$
0
0

I have a powershell script that I'd like to run every 30 minutes in the background. To do this I've created a scheduled task that executes the script. However, when it runs it quickly flashes the powershell window.

The command I use in the scheduled task is :

powershell.exe -NoLogo –Noprofile -WindowStyle Hidden -ExecutionPolicy Bypass -Command "& {D:\script.ps1}"

Is there a way to schedule this script in a way that it doesn't flash the powershell window?

Get-ChildItem exclusion from file

$
0
0
Hi, how load exceprion from some file, instead of: ?{($_.fullname -notmatch "foldername")} . The list can be very lage

Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $computer  -ErrorAction SilentlyContinue |

%{Get-ChildItem ('\\' + $computer + '\' + ($_.DeviceID).remove(1) + '$\*') -File *.doc,*.docx -Recurse  -Force -ErrorAction SilentlyContinue |

?{($_.fullname -notmatch "Windows") -and ($_.fullname -notmatch "Program Files") -and ($_.fullname -notmatch "Program Files (x86)")} |

Add-Content $env:TEMP\$computer.txt


Thank!

How can I remove a user from a set of specific groups?

$
0
0

Hi,

I'm trying to remove a user from a set of specific groups.

I have found plenty of articles on how to remove a user from all groups.

e.g

I want to say :

Remove Bob from Group1,Group2 and Group3.

Should I create an array with the group names, then and loop through it?

Thanks

monitoring bandwidth via Powershell script

$
0
0

Hello,

I am trying to monitor the bandwidth via powershell script for that so far I have written this script to fetch the bandwidth but I have some confusions,

$query = "Select BytesTotalPersec from Win32_PerfFormattedData_Tcpip_NetworkInterface where name='Microsoft Hyper-V Network Adapter'"
Get-WmiObject -Query $query;

Output :

__GENUS          : 2
__CLASS          : Win32_PerfFormattedData_Tcpip_NetworkInterface
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
BytesTotalPersec : 122118
PSComputerName   :

Now I have three questions :

1) What will be the formula to convert the BytesTotalPerSec to  MB/s ?

2) Is the BytesTotalPerSec really the bandwidth utilized by the adaptor?

3) If I want to store BytesTotalPerSec value in the variable what would be the procedure.?

Thanks

Frank

Install software remotely via Powershell

$
0
0

I'm trying to remotely install an application (Office 2010 Pro to be exact) and it works when I run it locally, but fails when i try it remotely. I have this syntax which I see commonly online as the preferred method to remote install, but it's not working. There are no errors when I run the script... the install just never starts. Again no issues when running locally.

Any help or troubleshooting recommendations would be much appreciated. I have to get this installed on hundreds of computers.

Current Code:

$InstallString = '"\\servershare\Office 2010\setup.exe" /adminfile Updates/OfficeSetup.MSP /config ProPlus.WW/config.xml"'
([WMICLASS]"\\computer1\ROOT\CIMV2:Win32_Process").Create($InstallString)


Please mark my post as helpful or the answer or better yet.... both! :) Thanks!


retrieve the value of a combobox (AD)

$
0
0

Hello !

I have an active directory like this :

-A

--A1

--A2

---A2.1

...

I made a GUI with primal forms :


 

#Generated Form Function
import-module activedirectory
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 05/09/2015 13:48
# Generated By: Jeremy
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$Label_ville = New-Object System.Windows.Forms.Label
$comboBox2_ville = New-Object System.Windows.Forms.ComboBox
$comboBox1_BU = New-Object System.Windows.Forms.ComboBox
$Label_BU = New-Object System.Windows.Forms.Label
$textBox_prenom = New-Object System.Windows.Forms.TextBox
$Label_Prenom = New-Object System.Windows.Forms.Label
$textBox_name = New-Object System.Windows.Forms.TextBox
$Label_Nom = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$handler_label4_Click=
{
#TODO: Place custom script here

}

$handler_label2_Click=
{
#TODO: Place custom script here

}

$handler_comboBox1_SelectedIndexChanged=
{
#TODO: Place custom script here

}

$handler_label1_Click=
{
#TODO: Place custom script here

}

$handler_form1_Load=
{
#TODO: Place custom script here

}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
	$form1.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 207
$System_Drawing_Size.Width = 387
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "Primal Form"
$form1.add_Load($handler_form1_Load)
function Load-ComboBox
{
    Param (
        [Parameter(Mandatory=$true)]
        [System.Windows.Forms.ComboBox]$ComboBox,
        [Parameter(Mandatory=$true)]
        $Items,
        [Parameter(Mandatory=$false)]
        [string]$DisplayMember,
        [switch]$Append
    )

    if(-not $Append)
    {
        $comboBox.Items.Clear()
    }

    if($Items -is [Array])
    {
        $comboBox.Items.AddRange($Items)
    }
    else
    {
        $comboBox.Items.Add($Items)
    }

    $comboBox.DisplayMember = $DisplayMember
}

$Label_ville.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 109
$Label_ville.Location = $System_Drawing_Point
$Label_ville.Name = "Label_ville"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 55
$Label_ville.Size = $System_Drawing_Size
$Label_ville.TabIndex = 7
$Label_ville.Text = "Ville"
$Label_ville.add_Click($handler_label4_Click)

$form1.Controls.Add($Label_ville)

$comboBox2_ville.DataBindings.DefaultDataSourceUpdateMode = 0
$comboBox2_ville.DropDownStyle = 2
$comboBox2_ville.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 109
$comboBox2_ville.Location = $System_Drawing_Point
$comboBox2_ville.Name = "comboBox2_ville"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 134
$comboBox2_ville.Size = $System_Drawing_Size
$comboBox2_ville.TabIndex = 6
Load-ComboBox $Combobox2_Ville (Get-ADOrganizationalUnit -SearchBase "OU=$OU,DC=SODIAAL,DC=FR" -Searchscope 1 -Filter * ) -DisplayMember "Name"

$form1.Controls.Add($comboBox2_ville)

$comboBox1_BU.DataBindings.DefaultDataSourceUpdateMode = 0
$comboBox1_BU.DropDownStyle = 2
$comboBox1_BU.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 80
$comboBox1_BU.Location = $System_Drawing_Point
$comboBox1_BU.Name = "comboBox1_BU"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 134
$comboBox1_BU.Size = $System_Drawing_Size
$comboBox1_BU.TabIndex = 5
$comboBox1_BU.add_SelectedIndexChanged($handler_comboBox1_SelectedIndexChanged)
Load-ComboBox $Combobox1_BU (Get-ADOrganizationalUnit -SearchBase "DC=SODIAAL,DC=FR" -Searchscope 1 -Filter * ) -DisplayMember "Name"
$Combobox1_BU.SelectedItem = $comboBox1_BU.Items[0]
$OU = $comboBox1_BU.Items[0]

$form1.Controls.Add($comboBox1_BU)

$Label_BU.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 83
$Label_BU.Location = $System_Drawing_Point
$Label_BU.Name = "Label_BU"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 64
$Label_BU.Size = $System_Drawing_Size
$Label_BU.TabIndex = 4
$Label_BU.Text = "BU "

$form1.Controls.Add($Label_BU)

$textBox_prenom.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 53
$textBox_prenom.Location = $System_Drawing_Point
$textBox_prenom.Name = "textBox_prenom"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 134
$textBox_prenom.Size = $System_Drawing_Size
$textBox_prenom.TabIndex = 3

$form1.Controls.Add($textBox_prenom)

$Label_Prenom.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 60
$Label_Prenom.Location = $System_Drawing_Point
$Label_Prenom.Name = "Label_Prenom"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 64
$Label_Prenom.Size = $System_Drawing_Size
$Label_Prenom.TabIndex = 2
$Label_Prenom.Text = "Prenom "
$Label_Prenom.add_Click($handler_label2_Click)

$form1.Controls.Add($Label_Prenom)

$textBox_name.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 24
$textBox_name.Location = $System_Drawing_Point
$textBox_name.Name = "textBox_name"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 134
$textBox_name.Size = $System_Drawing_Size
$textBox_name.TabIndex = 1

$form1.Controls.Add($textBox_name)

$Label_Nom.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 27
$Label_Nom.Location = $System_Drawing_Point
$Label_Nom.Name = "Label_Nom"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 82
$Label_Nom.Size = $System_Drawing_Size
$Label_Nom.TabIndex = 0
$Label_Nom.Text = "Nom"
$Label_Nom.add_Click($handler_label1_Click)

$form1.Controls.Add($Label_Nom)

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm

 

error :

Get-ADOrganizationalUnit : the syntax of the object name is incorrect

Combobox2_ville (Get-ADOrganizationalUnit <<<< -SearchBase "OU=$OU, DC=CONTOSO,DC=FR" - Searchscope 1 -filter * ) -DisplayMember "Name"

I can not seem to have the value of the second combobox

If I put the value manually it works

Can you help me ?

Thank you :)

 


Help Needed in PowerShell

$
0
0

Hello Guys,

I am trying to check the URL exists logic. I have text file contains 10000 url's and i wanted to check if some url broken because of no image exists on the directory. I tried with Wget and it took 3 hours to check it and response which url doesn't have image. I browsed through and found once nice article about powershell will do much faster. I can understand the below code. But little confused how to call my "Url.txt" file on this code. Any suggestion please how to use the below code to check image exists and if not output the url which is broken.

Link to Article

#requires -version 4.0

Function Test-URI {
<#
.Synopsis
Test a URI or URL
.Description
This command will test the validity of a given URL or URI that begins with either http or https. The default behavior is to write a Boolean value to the pipeline. But you can also ask for more detail.

Be aware that a URI may return a value of True because the server responded correctly. For example this will appear that the URI is valid.

test-uri -uri http://files.snapfiles.com/localdl936/CrystalDiskInfo7_2_0.zip

But if you look at the test in detail:

ResponseUri   : http://files.snapfiles.com/localdl936/CrystalDiskInfo7_2_0.zip
ContentLength : 23070
ContentType   : text/html
LastModified  : 1/19/2015 11:34:44 AM
Status        : 200

You'll see that the content type is Text and most likely a 404 page. By comparison, this is the desired result from the correct URI:

PS C:\> test-uri -detail -uri http://files.snapfiles.com/localdl936/CrystalDiskInfo6_3_0.zip

ResponseUri   : http://files.snapfiles.com/localdl936/CrystalDiskInfo6_3_0.zip
ContentLength : 2863977
ContentType   : application/x-zip-compressed
LastModified  : 12/31/2014 1:48:34 PM
Status        : 200

.Example
PS C:\> test-uri https://www.petri.com
True
.Example
PS C:\> test-uri https://www.petri.com -detail

ResponseUri   : https://www.petri.com/
ContentLength : -1
ContentType   : text/html; charset=UTF-8
LastModified  : 1/19/2015 12:14:57 PM
Status        : 200
.Example
PS C:\> get-content D:\temp\uris.txt | test-uri -Detail | where { $_.status -ne 200 -OR $_.contentType -notmatch "application"}

ResponseUri   : http://files.snapfiles.com/localdl936/CrystalDiskInfo7_2_0.zip
ContentLength : 23070
ContentType   : text/html
LastModified  : 1/19/2015 11:34:44 AM
Status        : 200

ResponseURI   : http://download.bleepingcomputer.com/grinler/rkill
ContentLength :
ContentType   :
LastModified  :
Status        : 404

Test a list of URIs and filter for those that are not OK or where the type is not an application.
.Notes
Last Updated: January 19, 2015
Version     : 1.0

Learn more about PowerShell:
http://jdhitsolutions.com/blog/essential-powershell-resources/

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************

.Link
Invoke-WebRequest
#>

[cmdletbinding(DefaultParameterSetName="Default")]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter the URI path starting with HTTP or HTTPS",
ValueFromPipeline,ValueFromPipelineByPropertyName)]
[ValidatePattern( "^(http|https)://" )]
[Alias("url")]
[string]$URI,
[Parameter(ParameterSetName="Detail")]
[Switch]$Detail,
[ValidateScript({$_ -ge 0})]
[int]$Timeout = 30
)

Begin {
    Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"
    Write-Verbose -message "Using parameter set $($PSCmdlet.ParameterSetName)"
} #close begin block

Process {

    Write-Verbose -Message "Testing $uri"
    Try {
     #hash table of parameter values for Invoke-Webrequest
     $paramHash = @{
     UseBasicParsing = $True
     DisableKeepAlive = $True
     Uri = $uri
     Method = 'Head'
     ErrorAction = 'stop'
     TimeoutSec = $Timeout
    }

    $test = Invoke-WebRequest @paramHash

     if ($Detail) {
        $test.BaseResponse |
        Select ResponseURI,ContentLength,ContentType,LastModified,
        @{Name="Status";Expression={$Test.StatusCode}}
     } #if $detail
     else {
       if ($test.statuscode -ne 200) {
            #it is unlikely this code will ever run but just in case
            Write-Verbose -Message "Failed to request $uri"
            write-Verbose -message ($test | out-string)
            $False
         }
         else {
            $True
         }
     } #else quiet

    }
    Catch {
      #there was an exception getting the URI
      write-verbose -message $_.exception
      if ($Detail) {
        #most likely the resource is 404
        $objProp = [ordered]@{
        ResponseURI = $uri
        ContentLength = $null
        ContentType = $null
        LastModified = $null
        Status = 404
        }
        #write a matching custom object to the pipeline
        New-Object -TypeName psobject -Property $objProp

        } #if $detail
      else {
        $False
      }
    } #close Catch block
} #close Process block

End {
    Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #close end block

} #close Test-URI Function
Any help please


loving dotnet

string to Datetime

$
0
0

Hi,

I am reading values from text file and my database column type is date. not datetime

value in my text file

data[2] = 20150903 12:39:12

Exception

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At D:\BatchandQueries\PowerShell\Walmart\Test.PS1:128 char:45+                         $shoppingDate = [datetime]::ParseExact <<<< ($data[2],'MM/dd/yyyy HH:mm:ss',$null)+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException

Code:

 [DateTime]$BirthDate = Get-Date -Date "1970-01-01 00:00:00Z"
$BirthDate = [datetime]::ParseExact($data[2],'MM/dd/yyyy HH:mm:ss',$null)

How to send this string value as date to my sqlserver database column whihc has the type of date. please help me



loving dotnet

ByPass MachinePolicy and UserPolicy when executing unsigned powershell script file

$
0
0

Hi All,

On my machine i have AllSigned policy set for MachinePolicy and UserPolicy 

I am able to execute scripts in powershell ISE Windows except powershell script files.

Is it possible to override these 2 policies and execute unsigned powershell script file ?


 >Get-ExecutionPolicy -list

                                                                              Scope                                                                     ExecutionPolicy
                                                                              -----                                                                     ---------------
                                                                       MachinePolicy                                                                          AllSigned
                                                                          UserPolicy                                                                           AllSigned
                                                                            Process                                                                           Undefined
                                                                         CurrentUser                                                                          Undefined
                                                                        LocalMachine                                                                             Bypass



TIA

SCSM and PowerShell

$
0
0


Hi,

I am trying to change a Runbook activity status to "Failed" in SCSM using the below command in SCSM:

Set-SCSMObject -SMObject $Object -Property Status -Value "Failed"

But I get the below error when I run it:


Set-SCSMObject : Unable to cast object of type 'System.String' to type 'Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject'.

Does anyone know how to fix it or what is wrong with that code block?

Any help will be appreciated.

Thanks

script to identify orphaned user home folders

$
0
0

Within our company we create user home folders with a PS script. Each user gets a home folder which gets the same name as the user's samaccountname.

Because sometimes a user's home folder is not removed at the same time like the account is disabled, we kind of lost track of inactive folders simply forgotten and folders which to keep. For that reason I'd like to run a script on a monthly basis which will check for each folder whether an user account with a corresponding sAMAccountname exists.

If a folder does not have a corresponding user name, then the name of that folder should be written into a csv file.

At the end of the script the csv file should be mailed to a mail recipient to be able to check what to do with these folders.

Being a complete PS noob and lacking persons around me with more PS knowledge I don't really know how to achieve this. Can somebody point me in the right direction?

Powershell Get-ChildItem question

$
0
0

Hello All, I am trying to write a short script to make filter and get the full path of the parent folder with "S3080130" in it.  I have tried the followings

Get-ChildItem -Path C:\test-v\ -Directory -Recurse  | Select-String -Pattern S3080130

S3080130 abcde

While if I perform this
Get-ChildItem -Path C:\test-v\ -Directory -Recurse  | FT FullName

Return the followings
C:\test-v\Group3\IVYY2\S3080130 abcde
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM\01 BCK
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM\02 ENG
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM\03 SDR
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM\04 DDR
C:\test-v\Group3\IVYY2\S3080130 abcde\PRM\05 COY
and return all other folders as well

Can I just return the following instead if I only need to filter out S3080130* folder but without its subfolders ?
C:\test-v\Group3\IVYY2\S3080130 abcde

Thanks

Peter


Unable to Create an array of Hash table for populating with 'NA' values for missing data

$
0
0

Hi Powershell Team,

I am trying to Create an array of Hash table.

Currently, I get the result of the below command to a csv file.


#Array Declaration

[array]$Output = @()

Foreach ($User in $UserCSV)
{

#Search for my user in a file, if exists in AD, get following properties

$output += Get-ADUser $SA_name -Properties UserPrincipalName, CanonicalName, Description, Title, userWorkstations, Enabled, LockedOut, PasswordExpired,PasswordLastSet, PasswordNeverExpires,whenChanged,whenCreated -ErrorAction Stop | Select UserPrincipalName, CanonicalName, Description, Title, userWorkstations, Enabled, LockedOut, PasswordExpired,PasswordLastSet, PasswordNeverExpires,whenChanged,whenCreated 

#Else I want to form my own Key Value pairs for the similar to the output of Get-ADUser

$output +=  @(@{"UserPrincipalName"="NA"}, @{"CanonicalName"="NA"}, @{"Description"="NA"}, @{"Title"="NA"}, @{"userWorkstations"="NA"}, @{"Enabled"="NA"}, @{"LockedOut"="NA"}, @{"PasswordExpired"="NA"}, @{"PasswordLastSet"="NA"}, @{"PasswordNeverExpires"="NA"}, @{"whenChanged"="NA"}, @{"whenCreated"="NA"})

}


#Put all these stuff into another excel.

# If User was present, it should output his properties, else, it should output NA against his properties.

#Currently, if I don't do this, i'm getting lesser rows for user properties resulting in mis-match in the final csv

Import-Csv $ImportFile -Delimiter ',' |
    Foreach { $_.Status = $Status[$i++] ; $_ } | Select-Object *,@{Name='UserPrincipalName';Expression={$($Output[$i++]).Title}} |
    Export-Csv $ExportFile -Delimiter ',' -NoTypeInformation

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

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

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

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

Lets say the user does NOT exist in AD, then I need to output NA against his properties.


In the final CSV, I would require the output as shown below:

-Adarsh


UPDATE #2:

After a bit of to and fro, got it to work for 1 key-value pair via below snippet:

$output +=  @{"UserPrincipalName"="NA"}


Import-Csv $ImportFile -Delimiter ',' |
    Foreach { $_.Status = $Status[$i++] ; $_.UserPrincipalName = $($Output[$j++]).UserPrincipalName; $_}|

Hopefully, should work if I add other properties as well.

Will update soon.

$output

+=  @{"UserPrincipalName"="NA"}#, @{"CanonicalName"="NA"}

$output +=  @{"UserPrincipalName"="NA"}#, @{"CanonicalName"="NA"}

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

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

UPDATE #3:

Corrected the Syntax by self.

Was trying to access it as multiple array elements via Name-Expression pair-like syntax as I needed to place a key-value pair as an Array Element.

This was because earlier, these values were placed in another csv via below command:

#Import a few values & add empty columns into a temporary CSV for now

Select SystemName, Name, @{Name=”ServiceAccount”;Expression={$_.StartName}}, state,startmode, @{Name="Status";Expression={""} },@{Name="UserPrincipalName";Expression={""}} , @{Name="CanonicalName";Expression={""}}  } |


Corrected line looks like:

#Get the values here

$output +=  @{"UserPrincipalName"="NA";"CanonicalName"="NA"}

#Export it to CSV here

Import-Csv $ImportFile -Delimiter ',' |
    Foreach { $_.Status = $Status[$i++] ; $_.UserPrincipalName = $($Output[$j]).UserPrincipalName;$_.CanonicalName = $($Output[$j++]).CanonicalName;$_}|
    Export-Csv $ExportFile -Delimiter ',' -NoTypeInformation








xDscResourceDesigner - Unable to find type [DscResourceProperty]

$
0
0

Hi, 

I downloaded and installed the xDSCResourceDesigner Module:

https://gallery.technet.microsoft.com/scriptcenter/xDscResourceDesigne-Module-22eddb29

Now when I try to run a command, I get this error message:

PS C:\cMyDSCModule> New-xDscResource
New-xDscResource : Unable to find type [DscResourceProperty].
At line:1 char:1
+ New-xDscResource
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (DscResourceProperty:TypeName) [], RuntimeExcepti 
   on
    + FullyQualifiedErrorId : TypeNotFound

What's wrong here? 

I hope someone can help me. I'm really new in DSC and PowerShell.

Regards,

Andi

Exchange photos

$
0
0
I'm looking for a script that i can apply to logon/logoff script that will get users pictures from the exchange server and apply them to there windows account picture. 

I have found multiple scripts that work that get the pictures from Active Directory, but the quality of photo in active directory isn't great and is much better in exchange

Any help please ?

Performance Counter / Logman.exe

$
0
0

Good Morning, Good Afternoon, and Good Evening,

At the moment, I have a script, which I found on the web. I did not right this hence why I am adding the link to give credit to the creator of the script.

http://www.jonathanmedd.net/2010/11/managing-perfmon-data-collector-sets-with-powershell.html

Basically, I just changed the original path of the first line to reflect my environment. I created the two text files; one, which contains a list of performance counters, and two, which contains a list of servers.

With regards to the script, it works as expected as it creates a performance counter on each server. The script however does not create correct counters

This is an example of the counter that it is creating. 

"\\urt-s28-sc\\\urt-s28-scP\\urt-s28-scr\\urt-s28-sco\\urt-s28-scc\\urt-s28-sce\\urt-s28-scs\\urt-s28-scs\\urt-s28-sco\\urt-s28-scr\\urt-s28-sc(\\urt-s28-sc*\\urt-s28-sc)\\urt-s28-sc\\\urt-s28-sc%\\urt-s28-sc \\urt-s28-scP\\urt-s28-scr\\urt-s28-sco\\urt-s28-sc"

Another admin created a typeperf  performance counter, and in properties they got this, which is correct.

"\Processor(*)\% processor Time


I am not getting what typeperf is doing  could someone please take a look at this code, and maybe direct me in a way for me to change the code. I actually have a deadline for this one so any help is welcomed.

This is the code. 

$pwd = "C:\Users\jmateo\Desktop\TestProjects"
$counters = @(gc $pwd\perfmon_counters.txt) # List of counters one per line
$servers = @(gc $pwd\perfmon_list.txt) # List of remote computers one per line
$frequence = "00:00:30" #hh:mm:ss
$logtype = "tsv" # possibles: bin,bincirc,csv,tsv
$max_duration = "168:00:00" # 7 days
$max_size = "50" # megabytes
$l = $servers.length
$i = 0
foreach ($server in $servers)
{
$counters | % {$_ -replace "", "\\$server"} | sc $pwd\$server.txt
Write-Progress -Activity "Setting up Collections...." -Status "Collection: $i of $l" -PercentComplete (100*$i/$l)
$strCMD1 = 'C:\Windows\System32\logman.exe create counter perf_$server -s $server -si $frequence -cf $pwd\$server.txt -f $logtype -v mmddhhmm -o C:\PerfLogs\log_$server -rf $max_duration -max $max_size -u adminusername adminpassword'
$i++
Invoke-Expression $strCMD1
Start-Sleep -Milliseconds 100
$startprocess = Invoke-WmiMethod -ComputerName $server -Class Win32_Process -Name Create -ArgumentList "logman.exe start perf_$server"
ri $pwd\$server.txt

auto pivot table update

$
0
0

 

  Im trying to automate a Pivot Table update. I put outputs in the code so you can see what I'm trying to update and with
what values.

To

 $date = 2015-09-07

From

 $dispshp = [DATE].[Ship Date].&[2015-09-01]

Update:

$workSheet.PivotTables(1).PivotFields("[DATE].[Ship Date]").CurrentPageName=$sdate

#Set the file path (can be a network location)
$filePath = "C:\shipment.xls"

#Create the Excel Object
$excelObj = New-Object -ComObject Excel.Application

#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $true

#Open the workbook
$workBook = $excelObj.Workbooks.Open($filePath)

#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("Customer")

$sdate= "{0:yyyy-MM-dd}" -f (Get-Date) # '2012-08-30

$sdate

$workSheet.Select()

$dispshp = $worksheet.PivotTables(1).PivotFields("[DATE].[Ship Date]").CurrentPageName

  #$workSheet.PivotTables(1).PivotFields("[DATE].[Ship Date]").CurrentPageName=$sdate

$dispshp

#Refresh all data in this workbook
$workBook.RefreshALL()

#Save any changes done by the refresh
$workBook.Save()

#Uncomment this line if you want Excel to close on its own
$excelObj.Quit()
 It gives an XML PARSER ERROR

 Thanks.
Viewing all 21975 articles
Browse latest View live


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