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

Powershell V2 on Windows 2016

$
0
0

Im hopping im not on the wrong forum.

Iv got an app that requres SQL Express 2014, and SQL Express 2014 requires Powershell V2 to be installed.

All the links that I can find sugest that powershellv2 is depricated and cannot be installed on Windows 2016. The windows2016 iso file doesnt have the powershellv2 sources, so I cant that to specify the soruce files when the add-windowsfeature asks for it.

Is this true or is there a way to install it?

Thanks

Zarko


Get-ADGroup Members recursive for the list of 50 thousand groups available in AD

$
0
0

Hello Team, 

I need to get the members of each groups for about 50 thousand groups and their recursive groups. 

I have pulled out the list of groups in the csv format using the CSV file need to get the members and their recursive groups with their members. 

I have followed the following code. 

$CSV =import-csv "C:\temp\xx.csv
foreach($groups in $csv)
{
$temp=$($groups.SamAccountName)
Get-AdgroupMembership -identity $groups -recursive|select-object MemberOf| export-csv c:\temp\xy.csv
}

But still i am getting the error. I have tried with the following code too. 

#// Start of script
#// Get year and month for csv export file
$DateTime = Get-Date -f "yyyy-MM"

#// Set CSV file name
$CSVFile = "C:\Temp\AD_Groups"+$DateTime+".csv"

#// Create emy array for CSV data
$CSVOutput = @()

#// Get all AD groups in the domain
$ADGroups = Get-ADGroup -Filter *

#// Set progress bar variables
$i=0
$tot = $ADGroups.count

foreach ($ADGroup in $ADGroups) {
	#// Set up progress bar
	$i++
	$status = "{0:N0}" -f ($i / $tot * 100)
	Write-Progress -Activity "Exporting AD Groups" -status "Processing Group $i of $tot : $status% Completed" -PercentComplete ($i / $tot * 100)

	#// Ensure Members variable is empty
	$Members = ""

	#// Get group members which are also groups and add to string
	$MembersArr = Get-ADGroup -filter {Name -eq $ADGroup.Name} | Get-ADGroupMember | select Name
	if ($MembersArr) {
		foreach ($Member in $MembersArr) {
			$Members = $Members + "," + $Member.Name
		}
		$Members = $Members.Substring(1,($Members.Length) -1)
	}

	#// Set up hash table and add values
	$HashTab = $NULL
	$HashTab = [ordered]@{
		"Name" = $ADGroup.Name"Category" = $ADGroup.GroupCategory"Scope" = $ADGroup.GroupScope"Members" = $Members
	}

	#// Add hash table to CSV data array
	$CSVOutput += New-Object PSObject -Property $HashTab
}

#// Export to CSV files
$CSVOutput | Sort-Object Name | Export-Csv $CSVFile -NoTypeInformation

#// End of script

powershell help

$
0
0
hi friends,
i am not good in powershell and i need a help
 in our active directory there are a lot of users which are a members in Groups, 

i need to list the users which are just members in these groups together grp1 and grp2

an Example:
 (user1 is member in domain users group and grp1 )
 (user2 is a member in domain users group, grp1 and grp2) 
in the output of the script i have to see just the user2 
because user2 is member of grp1 and grp2 together
can you help with a script please 

Get-ADUser from CSV, missing non-ADusers in output

$
0
0

Hi Guys,

I have a CSV file with usernames (CN-field in AD). Column A starts with CN, then the usernames (or CN's of the users) below.

From the file, i want to use Get-ADuser, see some properties and export this to a new CSV file. This works but one exception: In the input file there are also usernames that are not in AD. In the output file these users are filtered out, so they do not got exported to the new CSV file.

I want these non existing users visible in my new CSV file with all the other users. A message like "User not found in AD" would be likeable.

I am new to (Powershell) scripting, have read multiple forums and tried something like Try-Catch, or If. but i am failing everytime.

Here is my code i'm using:

import-csv H:\Test.csv | 
        ForEach-Object {
            Get-ADUser -Filter "CN -eq '$($_.CN)'" -Properties CN, DisplayName, Description
        } |
    select CN, DisplayName, Description | export-csv H:\Test_out.csv -NoTypeInformation
    H:\Test_out.csv

Can anyone please help me with probably this simple issue? And any improvements on my current file is also appreciated.

Thanks in advance

WinRM failing to connect

$
0
0

hi Experts,

I have two domains. Domain A and Domain B. My Target PCs exist in Domain A and the server exists in Domain B. Domain A trusts Domain B.

I am trying to execute few set of cmdlets on my target PCs which are in Domain A from the Server Domain B.

1. Target PCs have already been configured with WinRM including Trusted Hosts Configuration on the listeners.

2. The account I am using has already been added as admin on  the target PCs.

When I execute Test-WSman from the server to target PCs. it works fine with no issues:

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 3.0

But when I tried this: 

 Test-WSMan -ComputerName "xxxx.domaina.com" -Authentication Kerberos

it fails with this error: 

The computer xxxx.domaina.com is unknown to Kerberos. Verify that the computer exists on the network, that the name provided is spelled correctly, and that the Kerberos configuration for accessing the computer is correct. The most common Kerberos 
configuration issue is that an SPN with the format HTTP/xxxx.domaina.com is not configured for the target

I did added the SPN HTTP/xxxx.domaina.com and tried again. But No luck.

Here are the SPNs FYI:

 HTTP/xxxx.domaina.com
 HTTP/xxxx
 WSMAN/xxxx
 WSMAN/xxxx.domaina.com
 CmRcService/xxxx.domaina.com
 TERMSRV/xxxx.domaina.com
 RestrictedKrbHost/xxxx.domaina.com
 HOST/xxxx.domaina.com
 CmRcService/xxxx
 TERMSRV/xxxx
 RestrictedKrbHost/xxxx
 HOST/xxxx

The similar scenario I have tested with a different Domain which worked as expected.

Not sure what's missing.

Any help would be appreciated.


Thanks and Regards, Siva Kumar Balaguru

i have got below script on github but dont know how to execute please help

$
0
0
hello Team,

 I have a requirement in azure to enable or disable alerts at once during scheduled maintenance for that when i searching i got one script, as i am new to powershell i dont have any idea how to use that please help me 



git hub repositoty : josecons-msft/LogAnalyticsAlerts (sorry for not shareing the link as i am not verified yet not allowed to post URLs or links)



I have already migrated all alerts to scheduled query rules

Thanks
Vasudeva Reddy

FTP Authorization users permission checking command

$
0
0

Hi Guys,

               i want to check FTP Authorization User permission in powershell. i need the exact command to check this. Kindly

help me anyone. i have inserted the images for your reference. how to check user permission in powershell??

FTP Authorization users permission checking command

$
0
0

Hi Guys,

               i want check the users permission in FTP Authorization rules users permission through powershell commands. Plz tell me the exact commands or script to find that. 

to be more clear, i can share images also..


Elevate to Admin and Run Add-VPNConnection

$
0
0
Looking for a single ps1 file that will elevate to admin and run an Add-VpnConnection command. Tried a few things but not sure how to get the command to pass after I elevate to admin.

problem with format-table cmdlet

$
0
0

Hi

considering the following screenshots i need to know where i am wrong ? why no information is displayed under destination and time columns ?


even using -Autosize didn't have any effect !

Thanks in advanced

Power Shell Script

$
0
0
I want to create a PowerShell script that will pull out a report of AD user's who changed their lastname and the date of change .   

Adding a column to the output

$
0
0

Hello!

I am working with an application gateway on Azure and I want to get a table of all listeners including a column for the SslCertificate.

So far, I have stored the listeners in a variable and explored the possibilities with "Get-Member". I can see that a member exists for SslCertificate but I don't know how to make use of that.

I'm fairly new with PowerShell and any guidance will help, including just a link to another post.

Thanks!
Al

Powershell working on xml

$
0
0

Hi,

I'm starting to work with xml in powershell and I have stuck with it. My case: I have to inventory workstation/laptops in env that I have windows xp/windows 7 without SP1. I found and tested script in vbs but i got output in xml -  example :

<bios version="LENOVO - 2510" smbiosversion="GLET97WW (2.51 )" smbiosmajorversion="2" smbbiosminorversion="7">
  <bioscharacteristics id="7" name="PCI is supported" />
  <bioscharacteristics id="9" name="Plug and Play is supported" />
  <bioscharacteristics id="11" name="BIOS is Upgradable (Flash)" />
  <bioscharacteristics id="12" name="BIOS shadowing is allowed" />
  <bioscharacteristics id="15" name="Boot from CD is supported" />
  <bioscharacteristics id="16" name="Selectable Boot is supported" />
  <bioscharacteristics id="32" name="ACPI supported" />
  <bioscharacteristics id="33" name="USB Legacy is supported" />
  <bioscharacteristics id="40" name="Unknown (Undocumented)" />
  <bioscharacteristics id="42" name="Unknown (Undocumented)" />
  <bioscharacteristics id="43" name="Unknown (Undocumented)" />
 </bios>
 <osconfiguration osname="Microsoft Windows 10 Pro" computerrole="Standalone Workstation" domainname="WORKGROUP" domaintype="workgroup" windowslocation="C:\WINDOWS" oslanguage="Polish" installdate="2019-01-19 23:47:48" />
 <lastuser name="" />
 <windowscomponents>
  <component name="Internet Explorer (from Start Menu and Desktop)" class="0800" classname="" level="1" />
  <component name="Windows Media Player (from Start Menu and Desktop)" class="2200" classname="" level="1" />
 </windowscomponents>
 <installedapplications>
  <msiapplication productname=". ." vendor="Intel" version="7.1" installdate="20170321" />
  <msiapplication productname=". . ." vendor="Intel" version="2.7.2.4" installdate="20170321" />

To create reports and diagrams, I have to export it to csv. will be good if I use company sheet for it ( the columns is already predefined). Example:

Type of device Name Manufacturer Model MemoryProccessorBIOS

I try to work with get-content cmdlet and select-xml but I do not have idea for next step.

Can someone guide me how to get final summary based on above example.

Add in an object to a REST API response

$
0
0

I am queuing the Power BI (PBI) REST API to get the refresh history's for datasets on PBI. I'm then pushing the results back into a PBI Push Dataset for use in another report. The plan will then be to use a foreach loop to iterate the requests for every dataset on PBI. This is the script so far;

# Parameters - fill these in before running the script!
# =====================================================

# An easy way to get group and dataset ID is to go to dataset settings and click on the dataset
# that you'd like to refresh. Once you do, the URL in the address bar will show the group ID and 
# dataset ID, in the format: 
# app.powerbi.com/groups/{groupID}/settings/datasets/{datasetID} 

$groupID = "<REDACTED>" # the ID of the group that hosts the dataset. Use "me" if this is your My Workspace
$datasetID = "<REDACTED>" # the ID of the dataset that hosts the dataset

# AAD Client ID
# To get this, go to the following page and follow the steps to provision an app
# https://dev.powerbi.com/apps
# To get the sample to work, ensure that you have the following fields:
# App Type: Native app
# Redirect URL: urn:ietf:wg:oauth:2.0:oob
#  Level of access: all dataset APIs
$clientId = "<REDACTED>" 

# End Parameters =======================================

# Calls the Active Directory Authentication Library (ADAL) to authenticate against AAD
function GetAuthToken
{
       if(-not (Get-Module AzureRm.Profile)) {
         Import-Module AzureRm.Profile
       }
 
       $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
       $resourceAppIdURI = "https://analysis.windows.net/powerbi/api"
       $authority = "https://login.microsoftonline.com/common/oauth2/authorize";
       $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
       $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto")
       return $authResult
}

# Get the auth token from AAD
$token = GetAuthToken

# Building Rest API header with authorization token
$authHeader = @{
   'Content-Type'='application/json'
   'Authorization'=$token.CreateAuthorizationHeader()
}

# Properly format groups path
$groupsPath = ""
if ($groupID -eq "me") {
    $groupsPath = "myorg"
} else {
    $groupsPath = "myorg/groups/$groupID"
}

# Check the refresh history
$uri = "https://api.powerbi.com/v1.0/$groupsPath/datasets/$datasetID/refreshes"# + '?$top=1'
$refreshHistory = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method GET –Verbose | Select-Object -ExpandProperty value | Select-Object id, refreshType, startTime, endTime, status
# Remove $refreshHistory in final
$refreshHistory

# Push data to Power BI
$endpoint = "https://api.powerbi.com/beta/<REDACTED>/datasets/<REDACTED>/rows?key=<REDACTED>"
$payload = $refreshHistory | ConvertTo-Json
# Remove $payload in final
$payload
Invoke-RestMethod -Method Post -Uri "$endpoint" -Body $payload

This is an example of the $refreshHistory output;

id          : 595702443
refreshType : Scheduled
startTime   : 2019-03-31T03:00:11.91Z
endTime     : 2019-03-31T03:00:45.883Z
status      : Completed

id          : 594772832
refreshType : Scheduled
startTime   : 2019-03-30T03:02:03.353Z
endTime     : 2019-03-30T03:02:22.937Z
status      : Completed


And $payload;

[
    {"id":  595702443,"refreshType":  "Scheduled","startTime":  "2019-04-16T02:00:05.583Z","endTime":  "2019-03-31T03:00:45.883Z","status":  "Completed"
    },
    {"id":  594772832,"refreshType":  "Scheduled","startTime":  "2019-03-30T03:02:03.353Z","endTime":  "2019-03-30T03:02:22.937Z","status":  "Completed"
    }
]


What I want to do is add in the $datasetID so I can tie the refresh data back to a specific dataset when it comes to using the foreach loop. For example I would like my output for $refreshHistoryand $payload to be like;

id          : 595702443
refreshType : Scheduled
startTime   : 2019-03-31T03:00:11.91Z
endTime     : 2019-03-31T03:00:45.883Z
status      : CompleteddatasetId   : dd3d8631-b7bb-4183-aa01-066852f201f5

id          : 594772832
refreshType : Scheduled
startTime   : 2019-03-30T03:02:03.353Z
endTime     : 2019-03-30T03:02:22.937Z
status      : Completed
datasetId   : 793ec9d8-7efd-4341-a45f-d09217a2e210

[
    {
        "id":  595702443,"refreshType":  "Scheduled","startTime":  "2019-04-16T02:00:05.583Z","endTime":  "2019-03-31T03:00:45.883Z","status":  "Completed","datasetId":  "dd3d8631-b7bb-4183-aa01-066852f201f5"
    },
    {"id":  594772832,"refreshType":  "Scheduled","startTime":  "2019-03-30T03:02:03.353Z","endTime":  "2019-03-30T03:02:22.937Z","status":  "Completed","datasetId":  "793ec9d8-7efd-4341-a45f-d09217a2e210"
    }
]

Is this possible?

XML Retrieve First Record of Attribute Where...

$
0
0

I have a script that gets the first attribute of an Audits Element in my xml file.
The audit element looks like this

<Audits><Audit timestamp="" user="TestUSER" action="Listed"/>Jason Pope</Audits>
My scripts below gets the first audit data regardless of what the Action is, I only want the first Audits Record where the
Action is sold. There could be multiple Audits, but I don't want to retrieve any other Audit data just the first one  where the action = Sold.  In my current script it gets me the agents name (Jason Pope) but I only want the first agents name where action is sold.  There are multiple actions Sold,Listed,Pending,Removed. I just want the name of the Agent who sold.


Here is my current

PowerShell

 $varDirectory = "D:\Downloads\XmlTest\"
$files = Get-ChildItem $varDirectory -file -Filter *.xml;
  ForEach ($file in $files)
  {
  [xml] $xd = Get-Content $file
  $varSold = $xd.selectnodes("/RealEstate/House/Audits/Audit")  | Select-Object -first 1
 Write $varSold
  }


Sample XML Data

<RealEstate specVersion="5.09"><Header><SenderID>AB12345</SenderID><ReceiverID>AB56789</ReceiverID><DocTypeID>House</DocTypeID><DocCount>1</DocCount><Date type="generation">04/12/2019 16:05</Date><ListingRequest><Date>04/12/2019 16:05</Date><Reason>Rule Set House Extract</Reason><User UserId="TestUSer" FirstName="Test" LastName="User"><ContactMethods><ContactMethod sequenceNum="1" type="Phone"></ContactMethod><ContactMethod sequenceNum="1" type="Email">testuser@here.com</ContactMethod></ContactMethods></User></ListingRequest></Header><House internalId="24412065930" type="Residence"><ListingNumbers><ListingNumber type="House Number" isPrimary="true">8456874</ListingNumber><ListingNumber type="LST" isPrimary="false">789036954</ListingNumber></ListingNumbers><Comments><Comment type="SpecialInstructions">Awesome House BUY IT NOW</Comment></Comments><Status>NEW</Status><AssignedTo></AssignedTo><Owner>Joe Jones</Owner><Audits><Audit timestamp="" user="TestUSER" action="Sold"/>Jason Pope</Audits></House></RealEstate>

Thanks


PowerShell - Runspace - Fetch Data from Active Directory

$
0
0

I am new to PowerShell, so this may be a stretch for me, but I am hoping with some foundations I can build from there. I have the below basic example of what I wish to achieve;

# Load Assembly
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")  
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
[void] [System.Windows.Forms.Application]::EnableVisualStyles()

# Build the main form
$ExampleForm = New-Object system.Windows.Forms.Form
$ExampleForm.ShowIcon = $false
$ExampleForm.StartPosition = "CenterScreen"
$ExampleForm.Text = "Example"
$ExampleForm.Size = New-Object System.Drawing.Size(500,150)

# Label for the user's name
$NameLabel = New-Object System.Windows.Forms.Label 
$NameLabel.Text = "Name" 
$NameLabel.AutoSize = $true 
$NameLabel.Location = New-Object System.Drawing.Size(10,10) 
$ExampleForm.Controls.Add($NameLabel)

# Textbox for the user's name
$NameTextBox = New-Object System.Windows.Forms.TextBox
$NameTextBox.Size = New-Object System.Drawing.Size(150,20)
$NameTextBox.Location = New-Object System.Drawing.Size(130,8) 
$ExampleForm.Controls.Add($NameTextBox)

# Label for user's UPN
$UPNLabel = New-Object System.Windows.Forms.Label 
$UPNLabel.Text = "UserPrincipalName" 
$UPNLabel.AutoSize = $true 
$UPNLabel.Location = New-Object System.Drawing.Size(10,40) 
$ExampleForm.Controls.Add($UPNLabel)

# Textbox for user's UPN
$UPNTextBox = New-Object System.Windows.Forms.TextBox
$UPNTextBox.Size = New-Object System.Drawing.Size(150,20)
$UPNTextBox.Location = New-Object System.Drawing.Size(130,38) 
$ExampleForm.Controls.Add($UPNTextBox)

# Label for user's email address
$MailLabel = New-Object System.Windows.Forms.Label 
$MailLabel.Text = "Email Address" 
$MailLabel.AutoSize = $true 
$MailLabel.Location = New-Object System.Drawing.Size(10,70) 
$ExampleForm.Controls.Add($MailLabel)

# Textbox for user's email address
$MailTextBox = New-Object System.Windows.Forms.TextBox
$MailTextBox.Size = New-Object System.Drawing.Size(150,20)
$MailTextBox.Location = New-Object System.Drawing.Size(130,68) 
$ExampleForm.Controls.Add($MailTextBox)

# Button for the user to open an input box, which will allow them to input a user's Employee Number
$InputUserBtn = New-Object System.Windows.Forms.Button
$InputUserBtn.Location = New-Object System.Drawing.Size(320,38)
$InputUserBtn.Size = New-Object System.Drawing.Size(120,23)
$InputUserBtn.Text = "Enter User ID"
$ExampleForm.Controls.Add($InputUserBtn)

# The input box when clicking the above button
$InputUserBtn.Add_Click({
    $EmployeeID = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Employee ID", "Input Employee ID")
})

# Show the form
$ExampleForm.ShowDialog()

I would like help in getting the following to run in 'Runspace' so that the form doesn't come up as '(Not Responding)' with it searching by Employee Number it can take some time.

Get-ADUser -Filter "EmployeeID -eq $EmployeeID"

With that running in the background, when it has completed I'd like it to populate the text boxes with the information it has found.

Any help would be appreciated, thank you. Let me know if you have questions.

looking PowerShell script for RDP, Admin rights on server

$
0
0

I am in Infra division and we mostly got request from our customer to add people on multiple server and vice versa. Its time consuming to add an user to 20+ Server RDP\Admin group. Please assist


parsing logon scripts

$
0
0

I have multiple logon scripts that I want to turn into Group Policy drive mappings.

The batch files (logon1.bat, logon2.bat, etc) are all in this format. There are 423 batch files

:R Drive
Ifmember "domain\RUsers"
Net use R: /d
Net use R: \\fileserver1\sharename
:End R Drive

:S drive
Ifmember "domain\Susers"
Net Use S: /d
Net use S: \\fileserver2\sharename
End S Drive

:T Drive
ifmember "domain\Tusers"
Net use T: /d
Net use T: \\fileserver2\TShare
:End T Drive

Id like to run a powershell script and end up with a single csv file in this format

DriveLetter   Path                                  Group
R                  \\fileserver1\sharename    domain\RUsers
S                  \\fileserver2\sharename    domain\Susers
T                   \\fileserver2\TShare          domain\Tusers

I havent used PS to parse files like this before.

Any help appreciated.

Thanks,

Steve

PowerShell jarfile error screen: PLEASE HELP!

$
0
0
Every time I try to run this command [ javaw -jar server.jar nogui ] I receive a "Java Virtual Machine Launcher" error screen that reads: Error: Unable to access jarfile server.jar. The only thing I know is that I have a jarfile that for some reason won't launch. Please, if anyone knows how to help, please tell me ASAP.

New-PSDrive to SPO credentials not working

$
0
0

I need the script below to authenticate with OneDrive for Business and a Sharepoint Online library so I can in the location to my Quick Access links in Windows Explorer. 

The script works if I've already authenticated, but if it's not already authenticated the "-credential" property doesn't pass the information on. I get error"The operation being requested was not performed because the user has not been authenticated".

$creds = Get-Credential
New-PsDrive -Name N -Root "\\OURTENANT.sharepoint.com@SSL\sites\TEST" -PSProvider FileSystem -Credential $Creds
New-PSDrive -Name I -Root "\\OURTENANT-my.sharepoint.com@SSL\personal\' + $env:username + '_OURDOMAIN_org\Documents" -PSProvider FileSystem -Credential $Creds
Get-PSDrive N,I | Remove-PSDrive
$folder = "\\OURTENANT.sharepoint.com@SSL\sites\TEST"
$folder2 = '\\OURTENANT-my.sharepoint.com@SSL\personal\' + $env:username + '_OURDOMAIN_org\Documents'
$QuickAccess = New-Object -ComObject shell.application
$QuickAccess.Namespace($folder).Self.InvokeVerb("pintohome")
$QuickAccess.Namespace($folder2).Self.InvokeVerb("pintohome")

Viewing all 21975 articles
Browse latest View live


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