Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Firefox and/or Chrome settings changed with Powershell (or XML)

$
0
0

Hi there,

My aim is it to install these two programs silently (already done). But not also do I want to install them silently, I also want to give them a specific configuration. I know how to change the settings manually, but is it also possible to change the settings with Powershell or XML?

If this is also possible, than I would also take this idea:

Changing the settings manually, saving the settings (somehow) copy pasting the settings after the installation has been done.

I hope anyone can help me out here.


Powershell Newcomer



Import-PSSession and temp files in a concurrent environment

$
0
0

Hi everyone,

I am doing Remote PowerShell in a programmatic way, such as explained here: http://blogs.technet.com/b/exchange/archive/2009/11/02/3408653.aspx ; last section "Remote Request using a local run space (Scripting the remote class)"

However in order to release memory and temp files, I need to Remove the PSSession after all the calls, and this removes the temp files created at the "Import-PSSession", as well as releasing memory. Everything fine until here...

Now try to execute this in a main thread, and start two concurrent threads for examples doing the same thing. Almost everytime this will prevent Powershell from properly removing the temp files.

Is this a Powershell issue that can't be resolved ?

Environment:

  • Windows 7 Enterprise, Windows Server 2008 R2
  • Remote PowerShell on SharePoint or Exchange (does not change the issue)
  • Powershell V2

Please let me know if you require any further information. Thank you for your help. 

Olivier.

Hide Item From SharePoint in PowerShell

$
0
0

Hi,

i try to hide a page from my navigation in PowerShell, can you help me ! 

The method ExcludeFromNavigation is not good, it clears the item from navigation, but i just want to hide this item.

thanks :)

Per user to set AD information if possible?

$
0
0

Hi,

I use this powershell script to add AD post information,  but how can I set different post informaion per user account? Pls help!

Get-AdUser -Filter * -searchbase "ou=zip,ou=it,ou=sh,ou=users,dc=abc,dc=net" | Set-AdUser -PostalCode 1111111

Thanks.

Upload Files to an FTP site

$
0
0

Hi,

I need to upload some files to an FTP site.  Done some looking and have only found this the code below.  It looks like it might work but I need to create a folder as well and there doesn't seem to be straight forward way to do this.  IS there a way to do this using ftp.exe, the windows ftp client as I know that mkdir will create a folder


Function Upload_ftp
#Load the System.Net namespace.
[System.Reflection.Assembly]::Load
("System.Net, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

#The full path to the source file.
$Source =  "C:\MyFiles\SourceFile.txt"

#The full destination path (will be created).
$Destination = "ftp://www.myserver.com/myfolder/destination.txt"

#Use the static method Create to create a web request.
#Pass the destination as an argument, and cast it to a FtpWebRequest.
$R=[System.Net.FtpWebRequest][System.Net.WebRequest]::Create($Destination)

#Tell the request how it will login (using a NetworkCredential object)
$R.Credentials = New-Object System.Net.NetworkCredential($username, "$password)

#...and what kind of method it will represent. A file upload.
$R.Method = "STOR"

#Here I use the simplest method I can imagine to get the
#bytes from the file to an byte array.
$FileContens = [System.IO.File]::ReadAllBytes($Source)

#Finaly, I put the bytes on the request stream.
$S = $R.GetRequestStream()
$S.Write($FileContens, 0, $FileContens.Length)
$S.Close()
$S.Dispose()


Alter De Ruine

Powershell v3 Invoke-WebRequest HTTPS error

$
0
0
Using Powershell v3's Invoke-WebRequest and Invoke-RestMethod I have succesfully used the POST method to post a json file to a https website.

The command I'm using is

$cert=New-ObjectSystem.Security.Cryptography.X509Certificates.X509Certificate2("cert.crt")

$cred = Get-Credential -message "Enter Credentials: " Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Body $json -ContentType application/json -Method POST



However when I attempt to use the GET method like:

Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET



The following error is returned

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:8 char:11 + $output = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred
+  CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand




I have attempted using the following code to ignore SSL cert, but I'm not sure if its actually doing anything.

   [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Can someone provide some guideance on what might be going wrong here and how to fix it?

Thanks




PowerShell Test-Path Command

$
0
0

Hi,

I am having problems with Test-Path Cmdlet

I have created two variables Username and Password and then I am creating a PSCredential Object

$credentials = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $username, $password

$FullRemotePath= "\\$Server\C:\Program Files\Redstor Online Backup Plus"

Then I am passing these arguments to Test-Path Cmdlet

Test-Path -path $FullRemotePath -Credential $credentials

I am getting the following Error:

Test-Path : Cannot retrieve the dynamic parameters for the cmdlet. The provider does not support the use of credential

s. Perform the operation again without specifying credentials.

At C:\Users\binyamin.k\Documents\Power_Shell_Programs\MyTest.ps1:35 char:10

+ Test-Path <<<<  -path $FullRemotePath -Credential $credentials

    + CategoryInfo          : InvalidArgument: (:) [Test-Path], ParameterBindingException

    + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.TestPathCommand

CAN YOU PLEASE HELP ME ON THIS? I HAVE ALSO TRIED TO USE INVOKE-COMMAND BUT I GOT THE FOLLOWING ERROR

Connecting to remote server failed with the following error message : The WinRM client cannot process

the request. Default authentication may be used with an IP address under the following conditions: the transport is HT

TPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure

TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to

set TrustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshoot

ing Help topic.

    + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException

    + FullyQualifiedErrorId : PSSessionStateBroken

Regards

problem getting loginhours for users

$
0
0

when i do it one at a time it works

$vUser=[ADSI]"LDAP://CN=mylastname\, myfirtname,OU=S99X01,OU=Field Offices,DC=mydomain,DC=int"
$vHours=$vUser.loginhours
$vUser.path
$vHours

works just fine

but

$vLdap='LDAP://'
$vQuote='"'
$vAdsi='[ADSI]'
foreach($_ in(get-qaduser *|select dn))
    {
    $vUser=$_.dn
    $vUser=$vAdsi+'"'+$vLdap+$vUser+'"'
    $vLoginHours=$vUser.loginhours
    $vUser
    $vLoginHours
   
    }

and i get no joy...

help please? it is driving me crazy, i have tried many small changes but nothing seems to work

i even write-host for the var's and i dont see the dif, so why not work?

 

thx

bob


Office365 User report based on Get-MsolUser and AccountSkuId

$
0
0

I asked this question in the Office365-forum but was asked to post it here instead so I hope someone can help me.

We have a mixed O365-enviroment with federated accounts that have the E3-licens and unfederated accounts that have the E1-licens.
I have with this code got the AccountSkuId I want to filter on:

Get-MsolAccountSku | Format-Table AccountSkuId, SkuPartNumber
with the result:

AccountSkuId            SkuPartNumber
------------            -------------
company:STANDARDPACK    STANDARDPACK
company:ENTERPRISEPACK  ENTERPRISEPACK

I am now trying to create a report that lists only the E1-accounts with this code:

$colUsers = Get-MsolUser -MaxResults 10 | Where-Object {$_.accountskuid -eq "company:STANDARDPACK" -and $_.IsLicensed -eq $True}

But this just gives me zero accounts :(
What am I doing wrong?
Is there another way to filter on the E1-licens?

In my PS report I export these properties:
UPN
Primary SMTP
Secondary SMTP's
Displayname
First Name
LastName
Assigned Licenses
WhenCreated UTC
Title

This report is used as a base for internal billing of our departements.

/Anders

Adding values to array - Export Array as CSV

$
0
0

Hi,

I'm New to powershell, trying to create a small script to get macaddress from IP address.

$ipsheet = get-content c:\work\ipsheet.txt
$ipvalue=""
$macvalue=""
foreach ($ip in $ipsheet)
{if (test-Connection $ip -Count 2 -Quiet )
{ $macvalue+=(gwmi -Class Win32_NetworkAdapterConfiguration -computer $ip -filter "IpEnabled = TRUE" | where { $_.IpAddress -eq $ip }).MACAddress
} else
{
$ipvalue+=$ip
$macvalue+="not pinging"}}

I have two issues here, First the ipaddress or macaddress details collected in $ipvalue/$macvalue is continuous, i mean its not as array. I want it as array line by line. I have also tried to use `n to append data to next line but dint get it properly.

Second, i want to export this csv file in below format

Ipaddress,macaddress,

10.1.1.1,00:aa:bb:cc:dd:ee

I have checked so many forum but none of it helped much. please help.. thank you in advance.


Display Japanese characters in English Powershell console

$
0
0

Hi,

I am new to Powershell.I have problem in reading the output in Japanese ,below is the script I am using

$query = "Select * From Msvm_ComputerSystem "
$VOs = (gwmi -query $query -namespace "root\virtualization" -Cred $cred -Computername $computer )

This script runs in a server ,connects to remote hyper-v server to get information.

formatted output displays as shown below -

Name=WIN-B3529U0800R
ElementName=WIN-B3529U0800R
Description=Microsoft ???????
EnabledState=2
Caption=???????
IP=
ProcessId=
HostName=WIN-B3529U0800R
Name=AAA180ED-94A5-47D7-8F91-CEC30B351D5B
ElementName=?????
Description=Microsoft ???
EnabledState=2
Caption=???
IP=
HostName=WIN-B3529U0800R

All the question marks are Japanese characters which displays fine in Japanese powershell.Requirement is to get the ouput correctly(Japanes/Chinese) in English Hyper-v and pass it to java code for further processing.Please suggest how can I fix this.

Thanks,

Chetan

Can somebody help me export this script to TXT or CSV?

$
0
0

I've found a script that I'm using to discover all members and nested members of a distribution group.  The script is great, but I can't seem to find out how to export the tree view results to .txt or .csv

Any ideas?

Props to Hugo Peeters for the script!


###################################
# Get-MyGroupMembersRecursive.ps1 #
# Created by Hugo Peeters         #
# http://www.peetersonline.nl     #
###################################

param($ParentGroupNames)

$ParentGroupNames = 'xxxxxx'

$Global:myCol = @()

function Indent
 {
 param([Int]$Level)
 $Global:Indent = $null
 For ($x = 1 ; $x -le $Level ; $x++)
  {
  $Global:Indent += "`t"
  }
 }

function Get-MySubGroupMembersRecursive
 {
 param($DNs)
 ForEach ($DN in $DNs)
  {
  $Object = Get-QADObject $DN
  If ($Object.Type -eq "Group")
   {
   $i++
   Indent $i
   Write-Host ("{0}{1}" -f $Indent,$Object.DisplayName) -ForegroundColor "red"
   $Group = Get-QADGroup $DN
   If ($Group.Members.Length -ge 1)
    {
    Get-MySubGroupMembersRecursive $Group.Members
    }
   $i--
   Indent $i
   Clear-Variable Group -ErrorAction SilentlyContinue
   }
  Else
   {
   $userfound = Get-QADUser $DN | Select Name, Email
   Write-Host ("{0} {1}" -f $Indent,$userfound.Name)
   $Global:myCol += $userfound
   Clear-Variable userfound -ErrorAction SilentlyContinue
   }
  }
 }

ForEach ($ParentGroupName in $ParentGroupNames)
 {
 $Global:Indent = $null
 $ParentGroup = Get-QADGroup -Name $ParentGroupName
 Write-Host "====================="
 Write-Host " TREE VIEW PER GROUP"
 Write-Host "====================="
 Write-Host ("{0}" -f $ParentGroup.DisplayName) -ForegroundColor "Blue"
 If ($ParentGroup -eq $null)
  {
  Write-Warning "Group $ParentGroupName not found."
  break
  }
 Else
  {
  $FirstMembers = $ParentGroup.Members
  ForEach ($member in $firstmembers)
   {
   Get-MySubGroupMembersRecursive $member
   }
  }
 }
Write-Host ""
Write-Host "=====================" 
Write-Host " All Unique Members: "
Write-Host "=====================" 
$myCol | Sort Name | Select Name, Email -Unique



System.Net.WebRequest not presenting my certificate

$
0
0

Below is a snippet of code I have written to make a SOAP request to an internal Web Service we have.  If I run this with Fiddler running Fiddler alerts that the site is requesting a cert.  If I provide the cert to Fiddler this runs perfectly.  If I turn off Fidler then I get an error that the connection was closed.  I am beating my head against the wall because I am adding the cert to the ClientCertificates collection, and when I debug it I can see that it has it.  Any ideas why it is not presenting it at run time?  (you will see where I have tested with grabbing it from the local machine store and creating it from the file, and neither option is working)

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($certPath)
#$cert = get-item cert:\LocalMachine\* | get-ChildItem | Where-Object -FilterScript {($_.FriendlyName -eq "HRSYS")}
$soapWebRequest = [System.Net.WebRequest]::Create($url)
$soapWebRequest.ClientCertificates.Add($cert)
$soapWebRequest.Headers.Add("SOAPAction", $serviceAddress")
$soapWebRequest.ContentType = "text/xml;charset=`"utf-8`""
$soapWebRequest.Accept = "text/xml"
$soapWebRequest.Method = "POST"
$soapWebRequest.Timeout = 60000
$soapWebRequest.UseDefaultCredentials = $true

Use AD cmdlets against another domain in a different forest

$
0
0

My user account and machine where migrated to a new domain in a different forest last night. My account in the old domani is still active, as there is still stuff I need to do until we get rid of it.

I am trying to run some AD cmdlets, to take care of some objects in the old domain, but it is trying to run against the objects in the new domain, which I believe is because the machine I am running from is on the new domain. How can I force it to run against the old domain? My script is as follows:

Import-Module ActiveDirectory
cls

$ouName = "Some OU"
$moveOU = "OU=No Migrate,OU=$ouName,OU=Parent,DC=old,DC=domain,DC=com"

Get-ADComputer -Server server.old.domain.com -Filter * -SearchBase "OU=$ouName,OU=Parent,DC=old,DC=domain,DC=com" -Properties LastLogonDate | ForEach-Object {`
	If ($_.LastLogonDate -le (Get-Date).AddDays(-30))
	{
		If ($_.Enabled -eq $true)
		{
			Set-ADComputer -Identity $_.sAMAccountName -Enabled $false
		}
		
		Move-ADObject -Identity $_.DistinguishedName -TargetPath $moveOU
	}
}

So basically it goes through and finds any machine that hasn't logged in within 30 days, disables it then moves it to the specified OU. I added the -server parameter, to force it to use a server within that domain, but yet still fails saying it can not find an object with the specified name, within the new domain.

Is it possible to use the general AD cmdlets, acrss domains in different forests, or do I need to run them from a machine that is on the old domain?


If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

Sample code required for Invoke-RestMethod using HTTPS and Basic Authorisation

$
0
0

I'm trying to use powershell V3 to play with a HTTPS restful API but am having difficult connecting to it!

I used FireFox's RESTClient to verify I'm using correct API calls and basic authorisation headers.

When I transfer the same calls into Powershell it fails to connect :(

my code:


# This nugget should help me to get around any self-signed certificate issues I believe
$netAssembly = [Reflection.Assembly]::GetAssembly([System.Net.Configuration.SettingsSection])
 
if($netAssembly)
{
    $bindingFlags = [Reflection.BindingFlags] "Static,GetProperty,NonPublic"
    $settingsType = $netAssembly.GetType("System.Net.Configuration.SettingsSectionInternal")
 
    $instance = $settingsType.InvokeMember("Section", $bindingFlags, $null, $null, @())
 
    if($instance)
    {
        $bindingFlags = "NonPublic","Instance"
        $useUnsafeHeaderParsingField = $settingsType.GetField("useUnsafeHeaderParsing", $bindingFlags)
 
        if($useUnsafeHeaderParsingField)
        {
          $useUnsafeHeaderParsingField.SetValue($instance, $true)
        }
    }
}

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

$username = 'XXX'
$upassword = 'XXX'

$auth = $username + ':' + $upassword

$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)

$headers = @{"Authorization"="Basic $($EncodedPassword)"}

Invoke-RestMethod -Uri https://192.168.5.3:8444/csa/rest/login/CSA-Provider/admin -Header $headers -Method Get


The first time this is run I get the following error :

 

PS C:\Users\landg> C:\Users\landg\Documents\Scripts\CSA API\CSA_API_DEMO_take5.ps1
Invoke-RestMethod : Unable to connect to the remote server
At C:\Users\landg\Documents\Scripts\CSA API\CSA_API_DEMO_take5.ps1:35 char:1
+ Invoke-RestMethod -Uri https://192.168.5.3:8444/csa/rest/login/CSA-Provider/admi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

And all subsequent runs produce this error :

PS C:\Users\landg> C:\Users\landg\Documents\Scripts\CSA API\CSA_API_DEMO_take5.ps1
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At C:\Users\landg\Documents\Scripts\CSA API\CSA_API_DEMO_take5.ps1:35 char:1
+ Invoke-RestMethod -Uri https://192.168.5.3:8444/csa/rest/login/CSA-Provider/admi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I've run out of things to try but feel certain it's a security/certificate issue with my setup.

I also noticed when I go back to basics that this also produces the same error - 

Invoke-WebRequest -Uri https://www.google.co.uk -Method Get

but works if I use HTTP://

All suggestions would be greatly appreciated.

Kind Regards,

Graham.


How can I create a new mailbox with "EmailAddressPolicyEnabled" attribute of the mailbox set to $false when the newly created AD account has no SMTP address?

$
0
0

This is a tow step process for us:

1- The AD account is first created - but there is no SMTP address created at this time

2- I then need to enable-mailbox for that new user - but I don't want the EmailAddressPolicyEnabled attribute of the mailbox set to $True. How can I modify my script to accomplish that?

Here is what I have:

$mailbox=import-csv C:\Downloads\NewUser.CSV
ForEach ($mailbox in $mailbox) {Enable-Mailbox -Identity $Mailbox.Identity -Database $Mailbox.Database -ManagedFolderMailboxPolicy "90 day policy" -ManagedFolderMailboxPolicyAllowed}
Set-CASMailbox -Identity $mailbox.Identity -ActiveSyncEnabled:$false -POPEnabled:$false -OWAEnabled:$false -IMAPEnabled:$false


ExchangeGuru

Help importing CSV to SQL

$
0
0

Hi, i  want to get ad replication into a SQL DB with this script but it is not working, what i am missing?

Thanks



Add-PSSNapin SqlServerCmdletSnapin100

$sqlsvr = 'myserver'
$database = 'mydb'
$table = 'dbo.mytable'


repadmin.exe /showrepl * /csv > c:\mycsv.csv

Import-Csv c:\mycsv.csv | % {
  
Invoke-Sqlcmd -ServerInstance $sqlsvr -Database $database -Query "INSERT INTO dbo.mytable ([Source DSA])
 VALUES    ('$($_.Source DSA)')"
}

  


Scripting

$
0
0

Hi Folks,

I have a script that I used on Windows Server 2003 and it will work on Windows Server 2008r2.  I use it to run NTBackup.  However, it is not clear to me that WSH will continue to be available.

Should I be moving to "Powershell" and can I write jscript for Powershell?

Should I learn about WMI?  


Thanks for the help,

Chris.

A positional parameter cannot be found that accepts argument ' '.

$
0
0

I'm getting this error that I have been trying to resolve.  Need some help please.

PS H:\> C:\Errors-chk_exch4.ps1
A positional parameter cannot be found that accepts argument ' '.

At C:\Errors-chk_exch4.ps1:1 char:17

+     Get-WinEvent <<<<  -computername $server -filterhashtable $filter_system ` | where-object { ($_.LevelDisplayName -ne "Information") -and (($_.Id -ne 1111) -and ($_.ProviderName -ne "Microsoft-Windows-Term
inalServices-Printers")) -and (($_.Id -ne 6037) -and ($_.ProviderName -ne "LsaSrv")) }  ` | Select-Object LogName, MachineName, timeCreated, LevelDisplayName, ID, ProviderName, Message `
    + CategoryInfo          : InvalidArgument: (:) [Get-WinEvent], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWinEventCommand

Powershell: Scan computer names in a certain AD OU with credentials

$
0
0

I just started messing with powershell a couple days ago so I don't know much about it, but...

I'm looking for a powershell script that will scan all the computers in a certain AD OU with credentials and export it to a document. I have been pulling bits and pieces of other peoples scripts to try and create one but I'm having no luck.

Thanks.

Viewing all 2562 articles
Browse latest View live


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