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

Create profile and set console font

$
0
0

Hi,

I'm not really a powershell expert, even though i use it daily. I've been looking into creating a profile to make life easier. So i made a little script to auto create a profile and set the console properties, load some modules etc.

The one thing i have not found an answer for is how can i set the console to use Lucinda Console font in stead of that dreadful raster font?


This posting is provided "AS IS" with no warranties or guarantees and confers no rights


Add a carriage return in a .csv file

$
0
0

I running the following command which works but I would like to format the output in the CSV file. The "SecondaryAddresses" field is where my issue is. The field contains multiple addresses as such:
{joe@abc.com, joe@mno.com, joe@xyz.com}

Current output in .csv file.

Desired output in .csv file.

I want to be able to add a return into the .csv file so the data is in one cell.

Get-Mailbox jblake -DomainController "DC01" -ResultSize Unlimited | Select-Object DisplayName,alias,PrimarySmtpAddress, @{Name=“SecondaryAddresses”;Expression={$_.EmailAddresses | Where-Object {$_.PrefixString -ceq “smtp”} | ForEach-Object {$_.SmtpAddress}}}

Chris

PowerShell scripts

$
0
0

Hello There,

i need to know about bulk email address hide in office 365 cloud and want know if there is any way through by PowerShell

script. because there are large number of unwanted users in our Office 365 cloud and want to hide the from Global Address List. any idea how to hide the unwanted email with PowerShell scripts.

[SOLVED] Apply unatted.xml to image using DISM

$
0
0

I have applied unattend.xml to image using command:

DISM /Image:C:\mount /Apply-Unattend:C:\autounattend.xml

The operation completed successfully.

I have committed and saved image.

When I install there is no unattended setup...

Why?




How do I read a txt file and keep only IP addresses based on the first 2 or 3 octets of the IP?

$
0
0

Hello,

I have a text file and each line contains random text followed by an IP address as follows.

some text....172.30.25.30 some text.....172.30.85.10 some text..172.30.25.35 some text.......172.30.85.11 some text....172.30.15.1 some text...172.30.15.2 some text.......172.10.1.1 some text...172.20.4.2 some text..172.10.1.2 some text.....172.20.5.1

I'd like to create an output file which has only one entry for each unique entry in the file where either the first 2 or 3 octets are unique as follows:

Output File

172.30.25

172.30.85

172.30.15

172.10.1

172.20

Any suggestions are appreciated!


Thanks for your help! SdeDot



problem in Get-Aduser

$
0
0

Hi friends

i have lost my patiense & i will cry.

it's about 1 hour that i am struggling with a simple issu.

in my domain i have 3 users called u1, u2, u3    both names & samAccount names are same for each user.

when i run 

PS C:\> Get-Aduser -filter {name -eq "u1"}  ----> it works

but followings doesn't work & show no output:

$i = 1

PS C:\> Get-Aduser -filter {name -eq "u$i"}  ----> no result (nothing is shown in output)

a Guy said: " PowerShell won't resolve the variable name inside a scriptblock.  You have to define you're username outside and then use the variable"

but the problem is, without -filter, if the command checks the existence of an object in AD & in case that object is not present, it produces the error.

let me clarify:

i am writing a function that checks the existence of say these 3 users in AD database & if they don't exist in AD, (without getting the error which describes "object not found"), creates them.

for ($i = 1; $i -le 3; $i++){
     if (!(Get-ADUser -Filter {name -eq "u$i"})) {New-ADuser -name "u$i"}
     }

#if we don't use script block , i will get a terminating error & the code won't continue:

   for ($i = 1; $i -le 3; $i++){
      if (!(Get-ADUser "u$i")) {New-ADuser -name "u$i"}
     }

Get-ADUser : Cannot find an object with identity: 'u1' under: 'DC=HP,DC=lab'.

At C:\Users\Administrator\Desktop\Untitled2.ps1:2 char:13

+       if (!(Get-ADUser "u$i")) {New-ADuser -name "u$i"}

+             ~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (u1:ADUser) [Get-ADUser], ADIdentityNotFoundException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNo 

   tFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

 

The '++' operator works only on numbers. The operand is a 'System.String'.

At C:\Users\Administrator\Desktop\Untitled2.ps1:1 char:27

+    for ($i = 1; $i -le 3; $i++){

+                           ~~~~

    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException

    + FullyQualifiedErrorId : OperatorRequiresNumber





My code won't compile

$
0
0

Hi guys,

I'm busy creating a search tool and i'm renewing it time by time.

Now my code won't compile and i use the right quotes

I'm searching for a long time, do you see a reason for this?:

How do I parse for the 2nd CN in a line?

$
0
0

Hi,

Via Powershell, I list all my NTDS Settings Objects with some properties, but out of the Distinguished Name I just want the 2nd CN which contains the Server Name.  I just do a Get-Adobject on the Objectclass of nTDSDSA to get this data, so how would I read this via the pipeline and just grab the 2nd CN or server name?

DistinguishedName
-----------------
CN=NTDS Settings,CN=Srv01,CN=Servers,CN=SA,CN=Sites,CN=Configuration,DC=mydomain,DC=com
CN=NTDS Settings,CN=SrvName01,CN=Servers,CN=SB,CN=Sites,CN=Configuration,DC=mydomain,DC=com
CN=NTDS Settings,CN=SrvSomething01,CN=Servers,CN=SC,CN=Sites,CN=Configuration,DC=mydomain,DC=com
CN=NTDS Settings,CN=WhoKnows001,CN=Servers,CN=SC,CN=Sites,CN=Configuration,DC=mydomain,DC=com


Thanks for your help! SdeDot


parsing a pscustomobject field by field (or element)

$
0
0

Hi Guys,

I need to parse an array(or custom object) and send to a text file with custom modifications.  I need to add text between each element so it can get process on the other end.

I can't figure out how to move a cursor through a record 

I know my "second" foreach is not working, it just copies the data from user to element... 

 I also don't know how to read only the column name (but i'm sure i can figure that one out)
#users.csv:
#username,full name,email,address,postalcode,phone
#ewright,Eric Wright,eric@somedomain.com,123 Any Street,L4C 1N8,555-1212
#jvoigt,Jens Voigt,jens@somedomain.com,456 Any Street,L4C 1N8,555-3456
#ppocklington,Peter Pocklington,peter@anotherdomain.com,890 Back Street,M2H 4Y1,555-9876

$userlist = Import-CSV c:\users.CSV

foreach ($user in $userlist)
{
  $totextfile = ""
   foreach ($element in $user)
   {
      $totextfile += "$($element | Get-Member | select name)='$element',"
   }
   $totextfile # | outfile bla bla....
}


Anthony Cartier-Info

Run cmdlets from non AD users? Is it possible?

$
0
0

Hello!

I call powershell script from local user and obviously get access error. For example I need to get this info from AD:

(Get-MailBox -database DB2 -resultsize unlimited | Get-MailBoxStatistics | Add-Member -MemberType ScriptProperty -Name TotalItemSizeinGB -Value {$this.totalitemsize.value.ToGB()} -PassThru | measure-object -property TotalItemSizeinGB -sum).Sum

 

I can use “-credential $Cred” only with Get-Mailbox. What about the others  cmdlets?

Anyway, there is a huge similar cmdlets giving access error if I don’t use AD user with proper permissions.

I need this for monitoring system which works from LocalSystem account.

Could somebody advice please?

Create timer function that does not use start-sleep

$
0
0

Hey all I would like to create a timer function that does not use the start-sleep command because this freezes my GUI. I've wrote the start of a function but it seems to move on before the specified time has finished.

Here's what I have:

$Global:timerCounter=0
    $Global:timer = new-object System.Windows.Threading.DispatcherTimer

    Function Timer{
        param(
            [parameter(Mandatory=$true)]
            [int]$time
        )
        $timer.Interval = [TimeSpan]"0:0:$($time)"
        $timer.Add_Tick({
            $Global:timerCounter++
            if($Global:timerCounter -ge 1) {
                $Global:timer.Stop()
            }
        })
        $timer.Start()
    }

Then in my script i would like to call Timer -time #of seconds. It seems that when I call it the add_tick is registered and then started but it continues on with the rest of my script. Is there a better way of doing this without using start-sleep?

Thanks!

Invoke-RestMethod returns 400 server error.

$
0
0

The objective is to request the access and refresh token from Google API Oauth authorization code. I understand the 400 server error is due to a malformed URL, but I am not able to determine why it is malformed. As you can see, I implemented a 'try' & 'catch' statement on the error exception. The result doesn't provide any more information of why the Invoke-RestMethod will not work. What am I missing? Thanks

$TokenUrl = "https://accounts.google.com/o/oauth2/token"

$body = @{
  code="enter oauth authorization code here"
  client_id="enter google api client id here"
  client_secret="enter google api client secret here"
  redirect_uri="urn:ietf:wg:oauth:2.0:oob"
  grant_type="authorization_code"
}

Try {
$json = Invoke-RestMethod -Uri $TokenUrl -Method Post -Body $body
}
Catch {
    Write-Host $_.Exception.ToString()
    $error[0] | Format-List -Force

Try Catch does not work for imported cmdlets

$
0
0

Hello,

i'm trying to enable lync users from a remote server.

for this i'm importing a few cmdlets from the lync server to the remote server:

$LyncSession = New-PSSession -ConnectionUri $LyncUri -Authentication Negotiate
Import-PSSession -Session $LyncSession -CommandName Get-CsAdUser, Enable-CsUser, Grant-CsExternalAccessPolicy


later in the script, when i enable the user i'm using a try catch to catch any error that may appear:

try{
            Enable-CsUser -Identity $csaduser.UserPrincipalName -RegistrarPool "server.domain.intra" -SipAddressType SamAccountName -SipDomain domain.intra -ErrorAction Stop
}
catch {
          Log-Data -LogMessage $Error[0].Exception -UserDN $csaduser.DistinguishedName -LogError
}


from some reason the try catch dos not catch the error....although an error occurs :

PS C:\Admin\Scripts> $Error[0] |fl * -Force


writeErrorStream      : True
PSMessageDetails      :
OriginInfo            : server.domain.intra
Exception             : System.Management.Automation.RemoteException: Filter failed to return unique result,
                        "[SipAddress : sip:username@domain.intra] "
TargetObject          :
CategoryInfo          : InvalidOperation: (:) [Enable-CsUser], InvalidOperationException
FullyQualifiedErrorId : ProcessRecord,Microsoft.Rtc.Management.AD.Cmdlets.EnableOcsUserCmdlet
ErrorDetails          :
InvocationInfo        :
ScriptStackTrace      :
PipelineIterationInfo : {}

how can i catch this error ?

thanks,

Marius


extract excel sheet rows and columns into variables

$
0
0

Hi Power shell experts.

i am new to power shell.. could you please help me to write a code to extract the excel values into variable in powershell.

need to gather all folder path values in one variable ($FolderPath) and Days values into another variable ($Days) with looping funtion..

could you please help me..!

Thanks in advance. 

Is it possible to monitor State change of a .CSV file using powershell scripting ?

$
0
0

Hi All,

I just would like to know Is it possible to monitor State change of a .CSV file using powershell scripting ? We have SCOM tool which has that capability but there are some drawbacks in that for which we are not able to utilise that. So i would like to know is this possible using powershell.

So if there is any number above 303 in the .CSV file then i need a email alert / notification for the same.


Gautam.75801


GRANT LOGON TO SERVICE RIGHTS TO A USER REMOTELY

$
0
0

Hi all,

I have 20 Windows 2008 servers running an application

I want to grant logon to service rights to a particular domain user on all these 10 servers. I have three services in which the user needs to be granted logon to service permission.

Can I achieve this with a powershell script / psexec

I have domain admin rights to all the server

pumping_iron

Write-Output all fields on one line

$
0
0

I have a Write-Output command 

Write-Output $start, $end, $title, $location, 

what i get is:

May-29-12 4:30:00 PM
June-25-12 5:45:00 PM
Holy Yoga
Meeting Room B

what I want is:

May-29-12 4:30:00 PM,June-25-12 5:45:00 PM,Holy Yoga,Meeting Room B

so what I am missing is chomp for PS so i dont have crlf after every field and a way to keep the commas there

as I am trying to make a csv

Need to Manipulate Phone Number

$
0
0

Good day all -

Following this blog here (http://blogs.technet.com/b/nexthop/archive/2011/02/01/howtoadphonetolineuri.aspx) to manipulate phone number is our AD organization. Unfortunately when Lync populates the contact field from AD it looks at the Telephone Number and Office Number. In our organization these numbers are reversed. Meaning, the 10 digit number is xxx.xxx.xxxx is listed in the "Office" field of AD and the 4 Digit Extension is listed in the "Phone". With that said, we do have have different calling blocks. Meaning must of our numbers are:

555.555.9xxx

and 555.556.6xxx

All internal extensions (listed in the Telephone number field) begin with 5 and would be replaced with the last xxx in the above example.

So for the 555.250.9xxx block would be 200-499 .... for example extension 5394 would be Direct Dial Number 555.555.9394

And for the 555.556.6xxx block would be 600-799 ...  for example extension 5657 would be  Direct Dial Number 555-555.6657

So my question is this...with the above - how can I populate the below script correctly? Thanks for helping out.

$enabledUsers = Get-CsAdUser -Filter {Enabled -ne $Null}

foreach ($user in $enabledUsers)

    {

        $phoneNumber = $user.Phone

        $phoneNumber = $phoneNumber -replace "[^0-9]"

        $extension = $phoneNumber -match "^5"

        if ($extension)

            {

                $phoneNumber = "TEL:+120655" + $phoneNumber

            }

        else

            {

                $phoneNumber = "TEL:+142556" + $phoneNumber

            }

      

        Set-CsUser -Identity $user.Identity -LineUri $phoneNumber

    }

Remove Second Row From CSV

$
0
0

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

Sample data:

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

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

Any ideas?

Thanks in advance
Adam

Recovering the deleted computer account from AD

$
0
0

We have AD Recycle Bin enabled in our environment, with Recycle bin enabled we are able to restore the users.

I would like to know how to recover the deleted computers?

I am trying for below command with Administrator. Active Directory powershell

Get-ADComputer -Filter 'CN -eq "{Hostname}'" -IncludeDeletedObjects.

Can you please suggest?


Thanks HA

Viewing all 21975 articles
Browse latest View live