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

Switch statement - issue commands

$
0
0

Guys.

Been trying to get this to work for the last couple of hours. I am trying to run Set-QADUser command to set an AD attribute value from within one of my switch statements. I thought that using $_ would be ok to pass the users logon account.

What am i doing wrong here?

Connect-QADService -Service "ARS-Service-Name" -Proxy

$OUSelected = "OU-NAME"
Get-qaduser -SizeLimit 0 -SearchRoot $OUSelected |
    ForEach-Object {
        switch ($_.physicalDeliveryOfficeName){
            'London' {Set-QADUser -Identity $_ -ObjectAttributes @{'AD ATTRIBUTE HERE'= "AD ATTRIBUTE VALUE" }}
            'Milan'  {2}
            'Padova' {3}
            'Geneva' {4}
            default {'No site'}
        }
     }


how can get all computers from multiple domain which are in import-csv file

$
0
0

Get-ADForest | Select-Object -ExpandProperty Domains | Get-ADDomain | foreach {
$Computer = Import-Csv "D:\temp\file.csv" | Select-Object -ExpandProperty server
Get-ADComputer $Computer -Properties * | select name,site,OperatingSystem,@{N='Domain';E={$_.CanonicalName.Split('/')[0]}}
}

Hi 

I need to query all computers to know their properties but not getting success,

dfsutil to get site details in powershell

$
0
0

Hi

I need to get all servers (which are in input file )site details

I have created below script but it's not giving me output as required:

how can I export below command output in CSV file like servername,sitename



#############################
Import-Csv .\users.csv | foreach {
$servername = $_.server
dfsutil /sitename:$servername
}

#######################

How can I create multiple Office 365 Groups from an XLS

$
0
0

Bonus question, is there somewhere that fully explains how to reference XLS files across PowerShell commands? 

Beginner here: I recently created about 20 Office 365 Groups using PowerShell ISE and this command

New-UnifiedGroup -DisplayName "Group Name" -Alias groupname -AccessType private

I just copied this command a bunch of times into ISE, but was wondering if there was a way to reference a simple XLS with fields like

GroupName

Group1

Group2

Group3

Googling, I found references to doing this for bulk user creation and other sorts of things, but haven't found something that explains the XLS lookup enough to apply it to other commands. Maybe I just lack the PowerShell terminology to effectively Google this one. Trying to learn, though!

Thanks for your help!

Only first command runs when IF condition is met

$
0
0

I am trying to run multiple commands when the IF condition of my loop is met, however I cannot get anything past the first command to run. The idea is basically to check if a drive is already mounted, then mount a host to the drive if it is available. If the drive is already mounted, increment to the next drive letter and try again. Assume the array $Win7SysPath already exists. The mountedLetters array is being used for easy cleanup later in the script. 

# Creates Drives Letter Array
$letters = 70..89 | ForEach-Object { ([char]$_)+":" } 
#Sets increment counter to 0
$c=0
#Creates empty array for mounted Drive Letters
$mountedLetters=@()

#Function for Mounted Drives
function letterCheck{ 
    if ((Test-Path $letters[$c]) -eq $False){                 
        net use $letters[$c] $h
        mountedLetters += $letters[$c]
        $c++
    }
    else{       
        $c++
        letterCheck
    }     
}

foreach ($h in $Win7SysPath)
    {lettercheck}

Referencing this thread (https://social.technet.microsoft.com/forums/windowsserver/en-US/00e5f4c6-5be3-473c-b6b9-2d9f8b41558b/run-multiple-command-if-condition-is-met), I tried running the commands as background processes, with the invoke command and as a separate script all together, with no luck. All the individual commands run fine outside of the script. If there is a better way to get this done, please let me know. I am new to powershell scripting in general so any help is much appreciated.

-replace problems

$
0
0

I am a very green beginner with PowerShell - the following code that I am having problems with probably has some obvious and glaring error.  I am trying to replace text embedded in a text file with new text.  The original text file I am using as a test has 2 lines:

a(2,2) = (Ia01*r2*exp(2*a0beta*Ir2))/2.

c(6,6) = -(Ia03*ir6*exp(2*abeta0*r2))/2.

My script is (in PowerShell ISE) and the command screen answers are shown below.  I included some Write-Host lines to watch the progress of the script and the command screen results are also shown - no change has occurred, even though there is a match in each line. 

Why doesn't the replacement command work?  I would appreciate any help on this simple code.  Thanks.

 

$original_file    ='G:\My Documents\Math.txt'
$destination_file ='G:\My Documents\MathNew.txt.new'(Get-Content $original_file)|ForEach-Object{
    $line = $_Write-Host $line
    $newline = $line    -replace '2*a0beta*Ir2','2a0betaIr2'
    $newline = $newline -replace 'Ia03*Ir6','Ia03Ir6'Write-Host $newline}|Set-Content $destination_file

__________________________________________________________

PS C:\Users\Bills6540> G:\My Documents\Replacer.ps1
a(2,2)=(Ia01*r2*exp(2*a0beta*Ir2))/2.
a(2,2)=(Ia01*r2*exp(2*a0beta*Ir2))/2.
c(6,6)=-(Ia03*Ir6*exp(2*a0beta*r2))/2.
c(6,6)=-(Ia03*Ir6*exp(2*a0beta*r2))/2.

Need help with Exporting Data

$
0
0

Hi Guys

I'm trying to write a script to export site usage data in SharePoint. I was able to get data in following format:

"User","Jul <br> 14","Jul <br> 13","Jul <br> 12","Jul <br> 11","Jul <br> 10"
"ad\spuser1","0","0","0","1","1088"
"ad\spuser2","0","0","0","0","0"

This data is per SP site. I want to have data in following format(which is one single output file for all sites):

"SiteUrl", "SiteTitle","User","Jul <br> 14","Jul <br> 13","Jul <br> 12","Jul <br> 11","Jul <br> 10"

"Siteurl1","SiteTitle1","ad\spuser1","0","0","0","1","1088"

"Siteurl1","SiteTitle1","ad\spuser2","0","0","0","1","1088"

"Siteurl2","SiteTitle2","ad\spuser1","0","0","0","1","1088"

"Siteurl2","SiteTitle2","ad\spuser2","0","0","0","1","1088"

Below is the code I written:

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") $SitesList = Get-Content -Path 'Sites2.txt' function GetUsageInfo($Web) { Write-Host "Working on site: " $Web.Url $Period = New-Object Microsoft.SharePoint.Administration.SPUsagePeriodType $Report = New-Object Microsoft.SharePoint.Administration.SPUsageReportType [Microsoft.SharePoint.Administration.SPUsageReportType] $report = "user" $Usage = $web.GetUsageData($Report,$Period) $Usage | Export-CSV Out.csv -NoTypeInformation

} foreach($SiteUrl in $SitesList) { $SiteUrl = $SiteUrl.TrimEnd() $Site = New-Object Microsoft.SharePoint.SPSite($SiteUrl) $Web = $Site.OpenWeb() GetUsageInfo($Web) }

Can you pls help me with the script for getting output in required format.


Thanks Mohit



How to query whether Lync client is in "Presenting" mode with PowerShell

$
0
0

Hello,

I'm working on a PowerShell script that has the task to "decide" whether a software update to be pushed to a machine.

The idea is for it to check things like whether the machine is over VPN, connected to Wi-Fi and so on. Based on a list of requirements SCCM will be notified whether to start deployment or to defer the update.

The part I have problem is to determine whether the end user is currently presenting. I don't want pop-ups for my update to disrupt a meeting or a presentation that might be going on at the moment.

I wanted to "hijack" Lync algorithm for it. It is already capable to determining this quite well ( including if the monitor is duplicated ) .

Ideally I'll looking on how to make a call to a  DLL holding the algorithm, so I would get a proper answer even if Lync is currently offline. 

Worst case scenario I'll have to be satisfied even with just knowing whether Lync itself is presenting and check of PowerPoint and monitors myself. 

Problem is that I cannot find even a hint whether that can be done. I found how to change Lync availability using the Lync SDK, but getting it's current state seems to be eluding me. 

Does anyone have an idea?



AD groups in a csv.

$
0
0

Hi there,

does anyone can provide me a script to create a CSV. out of from AD via powershell script

Empty fields even if there are filled

$
0
0

Hello all,

Maybe a newbie question here but here is my problem, I send a request on powershell like this :

Get-ADUser -Filter {(Office -eq "something") -and (msRTCSIP-Line -like "tel:*")} | fl name, Office, msRTCSIP-Line

Fact is : the request sent me the valid names, but the fileds Office and msRTCSIP-Line are empty in the result of the cmd... When I check in the attribute editor of AD, the fields are filled with something.

What am I doing wrong ?

Thanks,


iperf like network test using Powershell or other 'native' windows functions

$
0
0

Hi,

I would really like to test a network connection between 2 servers in a 'raw TCP throughput style' i.e. no other bottlenecks like file I/O being part of the measurement.

The internets recommend IPERF strongly and this looks ideal, unfortunately the environment I need to test is very strict on ANY 'foreign' software being installed, even sysadmin style tools.

I imagined Powershell or by extension .NET would be ideal for this, setting up a 'listener' on one machine, then a 'client' on another and trying to max out the link.

Is this possible in a simple fashion, or am I completely mad thinking this can be done with local tools only?

Thanks!

The Search Filter Cannot Be Recognised

$
0
0

Hi

I have the following script which finds users who's accounts are expiring within the next 30 days and pulls out the user and the email address of their manager. Each time it runs I get the above message however if i call $table the data is correct

import-module activedirectory
$now = get-date
$future = (get-date).adddays(30)
$users = get-aduser -properties manager -filter {accountexpires -lt $future -and accountexpires -gt $now} -SearchScope Subtree -SearchBase 'OU=Users,OU=OU Enterprise,DC=domain,DC=local'
$table = @()
Foreach ($user in $users) {$table += New-object psobject -property @{user=$($user.userprincipalname); manageremail=$((get-aduser -properties emailaddress -filter {distinguishedname -eq $user.manager}).emailaddress)}}

Any ideas?

LAPS Import-Module AdmPwd.PS Fail

$
0
0

I'm trying to implement Microsoft's LAPS on a 2K8R2 DC. I have downloaded the documentation for installation. One step needs to import the module "AdmPwd.PS". When I try to import the module, it fails. Can someone please help me determine how to resolve this error?

PS C:\Windows\system32> Import-Module AdmPwd.PS
Import-Module : There were errors in loading the format data file:
Microsoft.PowerShell, C:\Windows\system32\WindowsPowerShell\v1.0\Modules\AdmPwd.PS\AdmPwd.PS.format.ps1xml : File skipp
ed because it was already present from "Microsoft.PowerShell".
At line:1 char:14+ Import-Module <<<<  AdmPwd.PS+ CategoryInfo          : InvalidOperation: (:) [Import-Module], RuntimeException+ FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Commands.ImportModuleCommand

LAPS: https://www.microsoft.com/en-us/download/details.aspx?id=46899

How to get events in the same log from two computers in one Format-Table

$
0
0

Hi

How to display events from the same Log on two computers in one format table?

I don't want to use these two commands.

Get-WinEvent-LogName$WinEventLog-ComputerName$PC1 | Ft

Get-WinEvent-LogName$WinEventLog-ComputerName$PC2 | Ft


Kind Regards Tomasz

Why does my table output have @ signs and property names in the values?

$
0
0

My code:

   $logtable= $eventloglist|Select-Object message,source,entrytype -unique
    $table=new-object system.Data.DataTable "$EventLogData"
    $col1=new-object system.Data.DataColumn Count,([string])
    $col2=new-object system.Data.DataColumn Source,([string])
    $col3=new-object system.Data.DataColumn Entrytype,([string])
    $col4=new-object system.Data.DataColumn Message,([string])
    $table.columns.add($col1)
    $table.columns.add($col2)
    $table.columns.add($col3)
    $table.columns.add($col4)
    $sources = $logtable|select source
    $messages = $logtable|select message
    $entrytypes = $logtable|select Entrytype
    $counts = $eventLogcount|select count

    for($i=0; $i -le $counts.length; $i++)        {$row=$table.NewRow();$row.Count=$counts[$i];$row.Source=$sources[$i];$row.EntryType=$entrytypes[$i];$row.Message=$messages[$i];$table.Rows.Add($row)}

Result:
My values in my table have @{Source="Value"} instead of just the value

  Question: How do I get rid of the @{Count,Source,Entrytype,Message =     part?   

Team Site's file/folder name changes via powershell

$
0
0

I was pointed towards this forum after I asked a question on the O365 forum... ( https://community.office365.com/en-us/f/154/t/359083 )

So lets try again...

I have a customer who is using Team Site's, part of the Office 365 Business Premium offering (not full blown SharePoint Online).

The customer has uploaded their old intranet file structure to the library however before they did this they did not check file name lengths when combined with everything in the directory. This means that a number of their files are over 256 characters in director length which is giving them issues in accessing those files.

Is there a way to connect to Team Sites via Powershell and then use a script, calling a CSV file to change the file/folder names of all files in the library to make path to the directory for each file under 256 characters? 

If yes then any hints and an ability to point me in the right direction would be helpful. 

Nic Version ESXi

$
0
0

I need to create a simple script to run a command against a set of ESXi hosts and return an output file. So, if I create a server.lst file to add the server names, then run "esxcli network nic get -n vmnic0" and output that information to a spreadsheet. I have 0 scripting background and this should be pretty simple, right?

Route the powershell output to a file

$
0
0

How do you route the powershell output to a file:

Powershell.exe -file c:\Users\Documents\ps.ps1  ??>?? c:\Users\Documents\pserror.txt 

Filename assistance

$
0
0

I am still new and trying to learn powershell. I am trying to accomplish 2 things. First is to retrieve only the filename (no .ext, no path) and be able to write to a different log file in a certain way. here is the code that i have with an example.

lets say the filename is "test1324.txt" all i need is the "test1234" without the path. i cant seem to find a cmdlet that will allow me to pull the filename out of $transfer.FileName. the log im using is RT9Write. CAn anyone help me?

 

param (
    $localPath = "C:\upload\*",
    $remotePath = "/home/user/",
    $backupPath = "C:\backup\",
    $RT9File = "C:\users\me\desktop\rt9.txt"

)


function RT9Write
    {
    Param ([string]$logstring)
    Add-content $RT9file -value $logstring
    }

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = "example.com"
    $sessionOptions.UserName = "user"
    $sessionOptions.Password = "mypassword"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        # Upload files, collect results
        $transferResult = $session.PutFiles($localPath, $remotePath)

        # Iterate over every transfer
        foreach ($transfer in $transferResult.Transfers)
        {
            # Success or error?
            if ($transfer.Error -eq $Null)
            {
                Write-Host ("Upload of {0} succeeded, moving to backup" -f
                    $transfer.FileName)
                RT9Write ("09                              "+(filename)+"       1234      123       20150716abcdefghImages uploaded to mine FTP site."  -f
                    $transfer.FileName)
                # Upload succeeded, move source file to backup
                Move-Item $transfer.FileName $backupPath
            }
            else
            {
                Write-Host ("Upload of {0} failed: {1}" -f
                    $transfer.FileName, $transfer.Error.Message)
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Bulk adding Active Directory users to a group by Display Name with PowerShell

$
0
0
Users often email me a list of Display names to be added to security groups. Need a script to read/get Display names from the txt/csv files and add them to security group
Viewing all 21975 articles
Browse latest View live


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