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

Weird Powershell Behavior with Logging using *>> Spaces Between Characters in Logs

$
0
0

I am experiencing some very weird issue whilst logging from my PS Script.

What I have noticed, if I log for the first time using *>>, all of my characters in the Log file have spaces between, however, if I log for the first time using *>, this works fine, then if I change my script to *>>, this also appends to the existing log fine with no spaces, it almost seems like the two commands are doing something different, they are writing to the Log in a different way.

It is only when I start a log with *>> this occurs, so its something to do with the Encoding, can i change this?

Has anyone seen this behavior before, or know how to fix it?


how to denest or flatten particular level of nested AD groups

$
0
0

how to denest or flatten particular level of nested AD groups. I am learning scripting. any inputs will be helpful to take off the scripting 

$GroupDN will have a list of nested groups with group names and distinguishednames

$GroupDN = import-csv .\desktop\group.csv
$member = (Get-ADObject-Identity$GroupDN.groupname).ObjectClass
Set-ADGroup -Identity $GroupDN.distinguishedname -Remove $member


suresh arasu

PS1 - specify local admin to install exe

$
0
0

Hello,

I am trying to push exe file through Microsoft Intune and need to run the exe file as local admin.
I have package psexec, application.exe into intunewin format and push it through Intune and run the commnad - psexec.exe -h -u admin -p password -accepteula .\application.exe /s

But I am not able to get it installed. How can I with powershell or Psexec specify local credentials to run exe file and package it as exe to push it throgh intune?

The package does not install using System context thats why we are trying to run exe using PSEXEC or PS1 to run it with the local admin account on the computer


How does Desired State Configuration (DSC) compare with other CM tools?

$
0
0

I'd like to hear opinions of DSC from folks who have at least some experience using it.  Is it easy to learn?  Does it work as expected?  Is it on its way up or on its way out?  How does it compare to other configuration management tools such as Ansible?  I need to evaluate a free solution for configuration of Windows servers and deployment of updates etc and DSC comes to mind, but I've heard mixed reviews about it.

Thanks for any experience you can share.

Subtract column value by 1 in a tab file

$
0
0

Hi All,

I have a tab delimited file and I want to subtract 3 tab value by 1 using powershell script

Please suggest.


Error when connecting to Domain with New-PSDrive Paramter -Server not found

$
0
0

I am trying to add to my script a connector to connect to another Domain. I keep getting the below error when trying to connect.

New-PSDrive : A parameter cannot be found that matches parameter name 'Server'.

I am using the below.

if (-not(Get-PSDrive DomainB)) {
    New-PSDrive `–Name DomainB `
        –PSProvider ActiveDirectory `
        –Server "DC.DomainB.local" `–Credential (Get-Credential ‘DOMAINB\Test’) `
        –Root ‘//RootDSE/’ `
        -Scope Global
    }Else{
    "Drive already exists"
    }

I want the script to then Set-Location so it can run the commands prompted in the new Domain. However i keep getting the error. Google has found little, has this been removed from PS. Or can someone advise a better way?

Thanks in advance all.

Aide pour la création d'un script pour automatiser la priorisation du réseau filaire au wifi

$
0
0

Bonjour,

Je souhaiterais pouvoir scripter la priorisation du wifi par rapport aux connexion ethernet, pour se faire, je passe par les commandes get-netipinterface et set-netipinterface.

Aujourd'hui je récupère ma liste d'objet avec leurs valeurs sous le format ci dessous via get-netkipinterface | select-objet ifindex, interfacealias, interfacemetric )

IfIndex      InterfaceAlias  InterfaceMetric

12             Ethernet 2           30

9               Wi-Fi                  25

24             Ethernet 7           30

Je souhaiterais pouvoir faire une vérification que mon interfacealias est bien -eq à "Wi-Fi" et si c'est le cas faire l'intégrer dans une variable pour ensuite lancer un set-netipinterface -IfIndex $index -InterfaceMetric 50

Le souci, je ne parviens pas à agir que sur mon ifindex dans le cas ou sa valeur "interfaceAlias" est -eq à Wi-Fi.

Auriez vous une idée de comment je pourrais formuler mon script ? (je bloque surtout sur le fait d'agir que sur une ligne, je pense que je bloque sur la façon de faire (foreach?))

Merci par avance

Get-NetAdapterStatistics can't running in VM

$
0
0

Get-NetAdapterStatistics can't running in VM

PS C:\Users\Administrator> Get-NetAdapter


Name                      InterfaceDescription                    ifIndex Status       MacAddress    
----                      --------------------                    ------- ------       ----------    
work                      Microsoft Hyper-V Network Adapter            14 Up           00-15-5D-01...

PS C:\Users\Administrator> Get-NetAdapterStatistics -Name work

Get-NetAdapterStatistics : No MSFT_NetAdapterStatisticsSettingData objects found 
with property 'Name' equal to 'work'.  Verify the value of the property and retry.
At line:1 char:1
+ Get-NetAdapterStatistics -Name work
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (work:String) [Get-NetAdapterStatistic 
   s], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound_Name,Get-NetAdapterStatist 
   ics






Invoke-Restmethod - intermittent unauthorized error with certificate option

$
0
0
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Uri = 'https://somerandomserver.com'

$Store = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My, "localmachine")
$Store.Open("MaxAllowed")
$Certificate = $Store.Certificates | Where-Object Thumbprint -EQ "xxxxxxx"
Invoke-RestMethod `
-Certificate $Certificate `
-ContentType 'application/json' `
-Uri $uri

I have configured access to the apiand trying to access the apiusing the certificate configured with. It is throwing unauthorized error intermittently, Am I missing something when passing the parameters to invoke-restmethod?

Which is best method to authenticate the Remote machine

$
0
0

As of now I  tried using Wsman commands and it succeed in most cases.

Here is the sample code for that:

$Password = ConvertTo-SecureString $password -AsPlainText -Force
    $Username = $username    
    $Cred = New-Object System.Management.Automation.PSCredential ($Username$Password)
    $Session = New-PSSession -ComputerName $Target.ip -Credential $Cred
    if(-not($Session)){
        Remove-PSSession $Session
        throw "Access Denied. Invalid credentials."
    }
    Remove-PSSession $Session

Can any one suggest any better approach to authenticate the remote machine with credentials. Above cases has a loop-hole that it will freeze when connection is lost(no error comes up just hangs)

Powershell RDS Installed License Report - Sent to email

$
0
0

Hi Experts, I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. Instead of write-host (to screen), I'd like to change it to a variable so that I can add it to the body of an email and have it run on a schedule and email me weekly reports on usage (Available CAL's) I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..

$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = ($summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses})

$EmailTo = "itgroup@microsoft.com"
$EmailFrom = "admin@microsoft.com"
$user = 'admin@microsoft.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp@contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)

I have used both parts of this script separately, but I would like to join them together, to make more useful. I have tried every way I know how in my limited experience, hopefully it is possible. Thanks in advance..


Exchange MS v2.0 Exporting to CSV -append Error

$
0
0

Hi - I am trying to import a list of users, get mailbox permissions and export results to a .csv file. If i have just one name in the input file it works as soon as I have multiple it does not.If I use -append it errors (I believe it is cause I am using version 2.0 of PS EMS) any suggestions?

$users = get-content “mailboxusers.txt”
foreach ($user in $users) {
Get-MailboxPermission -identity $user | where {$_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false} | Export-Csv MailboxAccess.csv;
}

Add a variable in a Invoke-RestMethod

$
0
0

Hello guys I need your help:

I would like to pass a variable in the $body of my command :

$name = "test.com."
$headers = @{"X-API-Key" = 'myApiKey'
}
$body = '{"rrsets": [ {"name": '+ $name +', "type": "CNAME", "ttl": 600, "changetype": "REPLACE", "records": [ {"content": "things.com.", "disabled": false } ] } ] }'
Invoke-RestMethod -Method Patch -Uri https://dnsadmin.ovea.com/api.com -Headers $headers -ContentType "application/json" -Body $body 

As you can see I try to add the $name variable but it's obviously not the good method, I don't find the correct way to do it.

Does someone have a solution for me ?

Thanks for your time.


 

Powershell - change IP on remote computer and shutdown the box

$
0
0

Hi Friends,

I'm using the technet for the very first time...

I have a task to complete where I should update the IP address on remote server and shutdown a wintel box.

My initial thoughts was to use Psexec... however I assume the remote connectivity will get lost once the ip gets changed and therefore shutting down the box will be problem...

this lead me to write a bat script where I can save a copy on the remote server using powershell and execute it from there. it works on my laptop locally but when I tried to work it out remotely - I find nothing happening.

could you advise how I can achieve it. code below...

$a = "192.168.1.112"
$b = "255.255.255.0"
$c = "192.168.1.1"
Start-Process -Verb RunAs "C:\temp.bat" -ArgumentList $a, $b, $c

temp.bat :--

@echo off
netsh interface ip set address "Ethernet" static %1 %2 %3 1
timeout /t 2
shutdown /s /f /d p:1:2 /c "Performing Migration activity" /t 10



unable to extract particular element from object[]

$
0
0

I have output from $a as 

$a

Name  Collage Marks Address Date
----  ------- ----- ------- -----
Andra   JKI     78.9  RRRR    5/15/2020 3:10 PM
Prakash TYU     67.9  EWSR    6/15/2019 6:10 PM
Amit    ERT     88.9  RRFR    6/15/2020 7:10 AM
Nobel   VFR     33.9  TTT     2/15/2020 3:10 PM

$a.gettype()
IsPublic ISSerial Name       BaseType
------- -------- ------      --------
True     True    Object[]    System.Array

I am unable to exract name or line Amit with Marks 88.9
due to Object[] no success 

I have tried all like  
$a=$a | ? {$_.Name -ilike "Amit"} OR contains  

I convert $a to string or to convertto-json but the json is weared and have no value of any of the fields 

also tried echo ($a | select -ExpandProperty "Name") OR $a."Marks" OR $a.PSObject.Properties |  ? isGettable| select-object -Property Name but no names are sorted 


PowerShell - Get Folder ID from String

$
0
0

Hi All,

I am trying to write a powershell script that will get the contents of a folder which contains zip file and then move these to the corresponding folders.

For example d:\datadownload contains;

data-230809_0008888.zip
data-230809_0008878.zip

I wont a script that will move the file data-230809_008878.zip to d:\data\0008878.

The script doesn't need to unpack it but just needs to move it.

[string[]]$files = Get-ChildItem -Path "d:\datadownload" | Select -ExpandProperty name

foreach($file in $files)
{
    [string[]]$folder = $file.Split("_",8)
    write-host $file.Split("_")
}

This is what I have currently started with but I can't figure out how to remove everything other than the bit of information that I need.

Could someone point me in the right direction of where to go next. I was looking at using some kind of 'substring' but there doesn't seam to be a substring option in PowerShell.

Regards,

Tom


TPark IT Technician

Active Directory PowerShell Issue

$
0
0

Hi

I have an issue with Powershell and the Active Directory Module.  When trying to load the Active Directory Module I get the following error :

import-module : The server was unable to process the request due to an internal error.  For more information about the
error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug>
configuration behavior) on the server in order to send the exception information back to the client, or turn on
tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
    + CategoryInfo          : NotSpecified: (AD:PSDriveInfo) [Import-Module], ADException
    + FullyQualifiedErrorId : ADProvider:NewDrive:InvalidRoot:ADError,Microsoft.PowerShell.Commands.ImportModuleComman
   d

Any help is greatly appreciated.

Regards

Mark

How does trap {} in powershell work?

$
0
0

Hello! I'm new to powershell. Trying to understand the difference between trap {} and try, catch, finally and how does trap {} in powershell work ... 


ACL System.Security.AccessControl.FileSystemRights permissions level

$
0
0

Hi,

I want to set folder permissions to two folders "f:\first" and "f:\first\second"     On the "first folder" the user has to have "FullControl" permissions, on the "second" folder I want the user having "Read" permissions.

I also don't want that changing the permissions to read/write in the first folder of a new user is going to change the permissions on the second folder to the old users already there.

I have run this script 

#For the folder first

    

       $acl = Get-Acl $homeShare

    $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"FullControl"
    $AccessControlType = [System.Security.AccessControl.AccessControlType]"Allow"
    $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"


    $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User, $FileSystemRights,      $InheritanceFlags, $PropagationFlags, $AccessControlType)
    $acl.AddAccessRule($AccessRule)

    Set-Acl -Path $homeShare -AclObject $acl -ea Stop

# for the second folder

      $acl2 = Get-Acl $homeShare

    $FileSystemRights2 = [System.Security.AccessControl.FileSystemRights]"Read"
    $AccessControlType2 = [System.Security.AccessControl.AccessControlType]"Allow"
    $InheritanceFlags2 = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $PropagationFlags2 = [System.Security.AccessControl.PropagationFlags]"InheritOnly"


    $AccessRule2 = New-Object System.Security.AccessControl.FileSystemAccessRule ($User, $FileSystemRights2,      $InheritanceFlags2, $PropagationFlags2, $AccessControlType2)
    $acl2.AddAccessRule($AccessRule2)

    Set-Acl -Path $homeShare -AclObject $acl2 -ea Stop

I run both in the same script, It all goes through without error and "First" folder is set to read/write for the user but "second"

is set to "custom" . Any idea what I should change?

Thanks

Powershell ISE runs my script with out issues but regular powershell fails

$
0
0

I have a PS script which is communicating to Office 365 management API to extract logs, the script works when I run it on ISE but the same script fails with an error "Unable to connect to remove server" when I run it on PowerShell. 

I have added [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12 and $env:NO_PROXY but no luck.

Could someone please assist me on this issue?


Karthikeyan

Viewing all 21975 articles
Browse latest View live


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