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

Advanced Functions - can pipeline input be transformed in Begin block?

$
0
0

I need to transform data passed into an Advanced Function before the Process block.  Can I re-use the input variable name and assign a new object to it in the Begin block?  I want to maintain the script as a Function and avoid a separate script for the transformation.

[CmdletBinding()]
Param (
    [Parameter(ValueFromPipeline)][array]$arr
)

Begin {
    # 'transform arr'
    $arr =  @{1='a';2='b';3='c'}
}
Process {
    $arr.GetEnumerator() | Out-String
    # more processing here
}
End {
    # Output here
}

The script is named Example1.ps1 - it would be called something like this:

.\Example1.ps1 @('a','b','c')

Is this a valid use of the pipeline?  Other suggestions?


AD Computers - Count OS Version by OU

$
0
0

Goal: Count computer objects in AD by OU, by OperatingSystemVersion, across multiple domains. Return output should include the following: Domain | OU Name | Operating System Name | Operating System Version | Count

I have a skeleton script created , but I'm having difficulty getting the counts split by OS version. I'm working with group-object, which does get the counts by OS version, but I'm not sure what the best way is to output those values in the table above.

Import-Module -Name ActiveDirectory

Clear-Host

$Output = @()
$Domains = ("abc.contoso.com","def.contoso.com","ghi.contoso.com")

foreach ($DC in $Domains) {

    $OUs = Get-ADOrganizationalUnit -Filter * -Server $DC -Properties Description, DistinguishedName

    Foreach ($OU in $OUs) {

        $Computers = Get-ADComputer -Filter {Enabled -eq "true"} -Server $DC -SearchBase $OU -Properties Name, Enabled, OperatingSystem, OperatingSystemVersion | select Name, Enabled, OperatingSystem, OperatingSystemVersion

        Write-Output "Scanning OU: $($OU.DistinguishedName)"

        $OutputItem = New-Object PSObject;

        $OutputItem | Add-Member NoteProperty "Domain" $DC
		$OutputItem | Add-Member NoteProperty "OU Name" $OU.Name
		$OutputItem | Add-Member NoteProperty "OperatingSystem" $NEEDHELP
		$OutputItem | Add-Member NoteProperty "OperatingSystemVersion" $NEEDHELP
		$OutputItem | Add-Member NoteProperty "Count" 

        $Output += $OutputItem

    }

}

$Output | Out-GridView

Automate future users to be added to the correct GAL's

$
0
0

Hi there,

I am new to PowerShell and I wanted to find outhow to Automate future users to be added to the correct GAL's.

Here is what I have done so far...

Created a new Address Policy for staff

Created a new Address Book Policy for students

Test Staff and Student GALS Update the main GAL policy, to add the new school domain to the exclusion list.

All help would be appreciated.

Thank you,

John B.


WebService authentication issue

$
0
0

Hi

I have been having issues connecting to an internal webservice - 401 Unauthorized.  I get this connecting from PowerShell and from a Project created using Visual Studio.

For some reason it looks like basic authentication is not being used so adding the following in the Visual Studio Project (Reference.cs created from wsdl file) works:

public partial class testServiceNoKeepAlive : testService
   {
       protected override System.Net.WebRequest GetWebRequest(Uri uri)
       {
           System.Net.HttpWebRequest request;
           request = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
           request.KeepAlive = false;

           System.Net.NetworkCredential networkCredentials = Credentials.GetCredential(uri, "Basic");

           if (networkCredentials != null)

           { byte[] credentialBuffer = new UTF8Encoding().GetBytes(networkCredentials.UserName + ":" + networkCredentials.Password); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer); }

           else

           { throw new ApplicationException("No network credentials"); }

           return request;
       }

   }

Can something similar be done in PowerShell?

Thanks

Paul

Script to get the disk usage and memory from a list of servers

$
0
0
I have a list of servers in a text file. I want a script to fetch the memory and the full disk space and free disk space and the percentage free space of the drives on these servers in a csv file.

Replacing all addresses in proxyaddresses with array

$
0
0

we have local AD that synchronizes to O365

we are adding a new email address with new domain to all users in two phases.

1) add new email address and let settle.

2) make new email address the primary email address (smtp: -> SMTP:)

I have a script I found where everything seems to work until the last command:

Set-ADUser -identity $UserName -Replace @{ProxyAddresses=$NewProxyAddresses}

The error I get with this command is:

Invalid type 'System.Management.Automation.PSObject'.
Parameter name: ProxyAddresses
    + CategoryInfo          : InvalidArgument: (user:ADUser) [Set-ADUser], ArgumentException
    + FullyQualifiedErrorId : Invalid type 'System.Management.Automation.PSObject'.
Parameter name: ProxyAddresses,Microsoft.ActiveDirectory.Management.Commands.SetADUser

The output of $NewProxyAddresses is:

smtp:user@olddomain.com
smtp:user@domain.com
X400:C=us;A= ;P=Company;O=Exchange;S=surname;G=givenname;
SMTP:firstlast@newdomain.com

The output of the $newProxyAdderesses is correct, but I am unable to run the set-aduser command


Powershell - Extract sections from range found in word document

$
0
0
Below code works fine, we got start and end point which needs to be extracted but im not able to get range.set/select to work

I'm able to get the range from below, just need to extra and save it to csv file...

$found= $paras2.Range.SetRange($startPosition, $endPosition) - this piece doesnt work...


    $file = "D:\Files\Scan.doc"
    $SearchKeyword1 =  'Keyword1'
    $SearchKeyword2 =  'Keyword2'    
    
    $word = New-Object -ComObject Word.Application
    $word.Visible = $false
    $doc = $word.Documents.Open($file,$false,$true)
    $sel = $word.Selection
    $paras = $doc.Paragraphs
    $paras1 = $doc.Paragraphs
    $paras2 = $doc.Paragraphs
    
    foreach ($para in $paras)
    {
        if ($para.Range.Text -match $SearchKeyword1)
        {
            write-host $para.Range.Text
            $startPosition = $para.Range.Start
    
    }
    }
    foreach ($para in $paras1)
    {
        if ($para.Range.Text -match $SearchKeyword2)
        {
            write-host $para.Range.Text
            $endPosition = $para.Range.Start
        }
    }
    
    Write-host $startPosition
    Write-host $endPosition
    $found= $paras2.Range.SetRange($startPosition, $endPosition)
    
    
    # cleanup com objects
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()

I have multiple .png images in a folder , I want to place those images as objects in each cell of the excel sheet using powershell

$
0
0

I have a folder with multiple images.

I want them to be placed in excel .One image in one cell . How can I achieve it ?


Get functions in profile

$
0
0

I have a profile which loads every time I open PowerShell which contains custom functions that I have created.

How can I get a list of all the functions I have created in there?

I tried Get-Command but there is no way to filter on the profile, I can't seem to add a description or source to a function either.

Help with splitting string

$
0
0
Import-Csv  -Path  'J:\CanvasData\courses_utf8nobom.csv' | where {$_.course_id -ne "C3066" -and $_.course_id -ne "C3110" -and $_.course_id -ne "C2569" -and $_.course_id -ne "C3103" -and $_.course_id -ne "C3657" -and $_.course_id -ne "C5060" -and $_.course_id -ne "C5160"} | 
 foreach-object{
$_.long_name -split ('-')[0]
$_ | Export-Csv 'J:\Temp\newcourses.csv' -NoTypeInformation -Append
}

Can someone please help me with this code, i'm trying to split a string and only take everything before the - also i need to repeat the process removing everything after and including an (

Many thanks

using out-datatable from csv input

$
0
0

  I'm trying to BulkCopy data from csv using the out-datatable, but hitting and error when doing the
writetoserverAsync. I have the functions Get-Type and Out-Datatable defined in script.

$scriptRoot = 'c:'
$log = "c:\"
$filename = 'itemattr.txt'


$sqlTable='Attribute'
$DataSource='(local)'
$DataBase='sales'
$copyOptions = 'CheckConstraints,TableLock' #,UseInternalTransaction'

$ConnectionString = 'Integrated Security=SSPI;Data Source={0}; Database={1}' -f $DataSource,$DataBase
$csvDataTable = Import-Csv -Path $scriptRoot\$filename  -delimiter '|' -header   ItemId,
		    Item_attribute,
            Item_cvalue,
            item_modified,
            ItemType,
            ProdLine
	Select-Object ItemId,
		    Item_attribute,
            Item_cvalue,
            item_modified,
            ItemType,
            ProdLine | 	Out-DataTable

$bulkCopy = new-object Data.SqlClient.SqlBulkCopy($ConnectionString,$copyOptions)
$bulkCopy.BatchSize = 5
$bulkCopy.NotifyAfter = 50
$bulkCopy.EnableStreaming = $true
$bulkCopy.Add_SQlRowscopied({ Write-Host "$($args[1].RowsCopied) rows copied" -fore green})
$bulkCopy.DestinationTableName=$sqlTable

($task = $bulkCopy.WriteToServerAsync($csvDataTable)).ConfigureAwait($false)
if($task.Exception){
	$task.Exception.InnerException
}else{
	Write-Host 'Upload succeeded' -fore green
}
 Error:
Cannot find an overload for "WriteToServerAsync" and the argument count: "1"

 Thanks.

Get App Pool Information

$
0
0

I need to see what domain user accounts are used on app pools in IIS. I have the following script.  The output lists the server name and the application pool name. I cannot not get the user name.  What am I missing. Thank you.

Import-ModuleWebAdministration

$allpools=@()


$IISAppPool

=Get-WmiObject-AuthenticationPacketPrivacy-ImpersonationImpersonate-ComputerName server -namespace"root/WebAdministration"-Classapplicationpool |Select__SERVER,Name,WAMUserName



foreach

($poolin$IISAppPool){


$poolidentity

=[pscustomobject]@{server=$server;AppName=$pool.name;user=$pool.Username}


$allpools

+=$poolidentity


 

}


$allpools

|Export-Csv-Path'c:\apppools.csv'-NoTypeInformation 


Combining csv files

$
0
0

Hi,

I have no experience with PowerShell, however I've been tasked with merging two CSV files. The files involve remote computer information that is pulled from a computer list. One CSV file contains last user etc. the other is specific with hard drive information as some of these machines have multiple drives. I found a script that will combine CSV2 to the last column of CSV1.  The rows match perfectly however the script changes order of the columns in CSV2.  Is there a way to get this done without changing the column orders in CSV2?.

James

How to rename multiple registry entries at once.

$
0
0

Hi all, 

I just started trying to learn powershell and I thought I'll create a script to clean up office. 

For folders I managed to write the code:

Get-ChildItem -Path "C:\MSOCache\All Users" *0FF1CE*| Rename-Item -NewName {$_.Name + ".OLD"} -Force -ErrorAction 'silentlycontinue

However, this does not work with Registry where I need to search with wildcard? Correct me if I'm wrong.

$Path="HKLM:\SOFTWARE\Microsoft"
Get-Item -Path $Path\Windows\CurrentVersion\Uninstall\*TEST* | Rename-Item -NewName TEST.OLD -Force

Get-Item -Path $Path\Windows\CurrentVersion\Uninstall\*TEST*


    Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall


SKC  VC Name                           Property                                                                                                                                        
---  -- ----                           --------                                                                                                                                        
  0   0 xxxTESTzzz                     {}                                                                                                                                              
  0   0 zzzTESTzzz                     {}            

So the Reg  keys are being found. If I run the code as above, it only changes one of the two.

I also tried exactly as per Office folder. 

$Path="HKLM:\SOFTWARE\Microsoft"
Get-Item -Path $Path\Windows\CurrentVersion\Uninstall\*TEST* | Rename-Item -NewName {$_.Name + ".OLD"} -Force

It just says that the key at the specified path does not exist. I assume that when I run the ps it searches for *TEST* folder and not for keys containing TEST in name. 

What I want to achieve is exactly as per MSOCache, renaming xxxTESTxxx to xxxTESTxxx.OLD and zzzTESTzzz to zzzTESTzzz.OLD

Greatly appreciating your help, also if possible with explanation.

Thanks!

Help With Windows Powershell

$
0
0
I am on Windows Server 2012 trying to connect WINRM to my client i am using PowerShell (PS) for example  PS> $cred = New-Object System.Management.Automation.PSCredential -ArgumentList @(‘USERNAME’,(ConvertTo-SecureString -String ‘PASSWORD’ -AsPlainText -Force)) and that works but when i try the 2nd part Invoke-Command -ComputerName vscope-demo2 -ScriptBlock (ipconfig /all) -Credential $cred it says it cannot convert & the method is not supported Or Invaild help me please!?

Resolving Linux file owners returned by Get-Acl

$
0
0

This may not be the correct place for this question, and if so I apologize.

I've been handed a project of surveying all the files on many Linux servers to see which users across the entire cluster are using the most files, and to sort users by latest file modified. The person who gave me this project wants me to do it in bash by fiddling with the string outputs of many commands. I could do it much easier in PowerShell, except for these problems: the servers are too old to run PowerShell for Linux, and when I run it on Windows through Samba shares, Get-Acl can't resolve the returned SIDs to user names. If I could just figure out how to resolve a SID to a Linux owner name, I'd be all set, and I'd be able to sort and sum any file properties I wanted as objects.

For example, I could run this:

Get-Item -Path \\server\share\testfile | Get-Acl | Select owner

I'd get a result of a string SID, like so:

O:S-1-5-21-3211650329-300098617-3820912319-1070

Even though the user name and user ID are the same on every node of the cluster, I get a different SID returned from each node.

But if I look at the file in Windows Explorer and look at its security tab, Windows is able to resolve the owner to server\username. So that information is SOMEWHERE.

Is there anything I can do in PowerShell that will let me access this mapping?

Set-Content cmdlet: paramater cannot be found that matches 'Encoding'

$
0
0

Hello,

I am trying to execute the following command on a server in PowerShell v4 but receive an error stating that a parameter cannot be found that matches parameter name 'Encoding'. I am using this command in a script to change the encoding of the CSV file to UTF-8. 

Get-Content -Path "X:\File.csv" | Set-Content -Path "X:\File.csv" -Encoding UTF8 -Force

The command runs fine on my local machine with PowerShell v5. The 'Encoding' parameter appears to be available in Get-Help Set-Content when I run it on the server. 

Test-Path returns $False while file exists.

$
0
0

Hello all,

I found that Test-Path returns a $False even when a file exists. I created c:\temp\input.csv but it is not recognised by the script.

Clear-Host
Write-Host "Test-Path"
$FileName = "C:\temp\input.csv"
if(Test-Path -Path $FileName)
{ Write-Host "The file $FileName exists"} else { Write-Host "The file $FileName does not exists." }

Write-Host "[System.IO.DirectoryInfo]"
[System.IO.DirectoryInfo]$file = "c:\temp\input.csv"
$Froot    = $file.Root.ToString()
$Fparent  = $file.Parent.ToString()
$Fname    = $file.Name.ToString()
$FullName = $Froot + $Fparent + "\" + $Fname
if(Test-Path -Path $FullName)
{ Write-Host "The file $FullName exists"} else { Write-Host "The file $FullName does not exists." }

And a picture:

I do something wrong here, but what?

Any help is appreciated.

With kind regards,

Willem-Jan

Need help to search csv file for values like 100 GB (107,374,182,400 bytes) or 50 GB (53,687,091,200 bytes)

$
0
0

Hello Folks,

I am trying to read csv file using PowerShell which has values like 100 GB (107,374,182,400 bytes) or 50 GB (53,687,091,200 bytes) and column name like ProhibitSendReceiveQuota. I tried below code just for a test but it is not working and no error as well

foreach ($line in (Import-Csv "C:\Temp\data.csv"))
{
  # Check if the 'ProhibitSendReceiveQuota' value in the line is 50 GB

  if ($line.ProhibitSendReceiveQuota -eq "50 GB")
   {
   #If ProhibitSendReceiveQuota is 50 GB then store output in csv file

   $line.Alias | Out-File -FilePath "C:\Temp\Test_50GB.csv" -Append
                  
   }
}

I even tried using pattern like below

$csv = Import-Csv "C:\Temp\data.csv"

$pattern = "^.*?ProhibitSendReceiveQuota Size: (?50\d+(?:\.\d+){0,1}.*)$"

$csv | Select-String -Pattern $pattern

And I got error -

Select-String : The string ^.*?ProhibitSendReceiveQuota Size: (?50\d+(?:\.\d+){0,1}.*)$ is not a valid regular expression: parsing
"^.*?ProhibitSendReceiveQuota Size: (?50\d+(?:\.\d+){0,1}.*)$" - Unrecognized grouping construct.
At line:1 char:17
+ $finds = $csv | Select-String -Pattern $pattern
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

How can I achieve this? Any help in this regards is greatly appreciated.

Thank you

Abhay


Abhay


get all places of URL usage

$
0
0

Hello guys,

is there a way to find out all the places where a specific URL is used by using PowerShell ?

I tried it this way:

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

get-spsite -limit all| Where-Object {$_.Url -like "https//AAA.BBB.com/CCC"}

Thank you in advance.

Viewing all 21975 articles
Browse latest View live


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