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

Mapping network drive using PS V3.0 New-PSDrive -name "K" -PSProvider FileSystem -Root but have snag on passing credentials through

$
0
0

Hello,

I am creating a simple PowerShell v3.0 local logon script for all who logon that is running on W2K8 R2 SP1 server to map a persistent "K:" drive to a remote AD domain W2K8 R2 SP1 file server (no AD domain trust between the server mapping from and file server mapping to).  The PS v3.0 script will map but you have to manually enter a password.  I want to get it where the PS script can store the username and password so no user intervention is necessary to persistently map this network drive. Here is the simple PS v3.0 script which works but requires manually entering a password:

New-PSDrive -name "K" -PSProvider FileSystem -Root \\FileServer1\FileShare1\DeptFolder1 -Persist -Credential DOMAIN\%serviceaccountname% -Password %Password%

I don't know if there is a "-Password" parameter so if any PS expert can lead a novice like me to a script that can store credentials, I will be most grateful.  



Matt


$CheckedListBox.SetItemChecked($CheckedListBox.Items.IndexOf($Item), $true); throws exception

$
0
0

$PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  2636   

Hello,

 I'm getting an exception thrown in a PowerShell SetItemsChecked, trying to check the checkbox. Nothing special

 In another area in the same script, I uncheck and check checkboxes in the same checkbox with no problems using the same syntax, pretty simple, however...

 For some reason when I try to check the check box I get a error message box...

    Exception calling "SetItemChecked" with "2" arguments(s);

    "InvalidArgument=Value of '-1' is not valid for "index"

    Paramenter name index.

The index is not -1, it is 0 or 1, or

I am able to manually set it to $false, or (1.0), but for some reason I'm unable to check it with $true

This is such a simple operation, I have been using it since C# beta 1 and it works in VS, so I'm seeing it as a bug.

The following is the code. The $false one has no problem with indexes, but the $true one throws an exception.

Is there some weird setting I need to have set or something, or a new PS version. 

I have looked around, and no-one has see this issue. 

I even copy examples from forums to verify, and they fail.

Again, in another area I have code to uncheck all items, and check the one item selected, with no problems.

Any ideas?

Thank you

#region [ FUNCTION ] - [ CHECK BAD ITEMS ]

   function CheckBadItems()

   {

       foreach($itemin$CheckedListBox.Items)

       {

           $OrderStatus =$item

           if($OrderStatus-like'*FAILED')

           {

               $CheckedListBox.SetItemChecked($CheckedListBox.Items.IndexOf($Item),$false);

               $CheckedListBox.SetItemChecked($CheckedListBox.Items.IndexOf($Item),$true);

           }

       }

   }

 

#endregion [ FUNCTION ] - [ CHECK BAD ITEMS ]


Richard Loba

(Amateur Question) Function for disabling multiple windows services

$
0
0

First time poster and brand new to PowerShell so forgive my ignorance. I have some light PHP and C++ experience so I may be approaching this in the wrong way, but I am trying to create a Function to disable a handful of windows services. So far here is what I got

function Disable-service{ param(
[string]$servicename
[switch]@disable
)
if($disable.IsPresent){
(Set-Service $servicename -StartupType Disabled)
}
}

Disable-service BcastDVRUserService_6622b0 -disable
Disable-service wildsvc -disable
Disable-service WpcMonSvc -disable
Disable-service icssvc -disable
Disable-service XboxGipSvc -disable
Disable-service XblAuthManager -disable
Disable-service XblGameSave -disable
Disable-service XboxNetApiSvc -disable

Again this is my first attempt at building a PowerSehll function so I'm sure there is a lot of things I'm missing. I'm using a function that un-pins and uninstalls windows apps as a template. I appreciate all help

Easiest way to create an Azure VM from an existing base image you already have in your lab?

$
0
0

I have about 20 or so images in my lab. I want to automate the process of spinning up one of these images without having to use the UI on the Azure portal.  I've encountered several scripts on the web, but they all seem to be about creating an image from scratch, or from a snapshot, etc. I just want a script that I can point to one of these base images and have it spin up.

I experimented with something like the below, but it seems to want to create a new VM instead of just using my base image. The image name in my lab is WJan2019X17.

$vmConfig = New-AzureRmVMConfig -VMName WJan2019X17 -VMSize Standard_DS3 | Set-AzureRmVMOperatingSystem -Windows -ComputerName myVM -Credential $cred

Set-AzureRmVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest | Add-AzureRmVMNetworkInterface -Id $nic.Id

New-AzureRmVM -ResourceGroupName VSImageTestFactoryRG750066 -Location EastUS -VM $vmConfig

Thanks for your help!



No searchbase in computername

$
0
0

Hello

I am trying to query AD for computer bitlocker keys.

I'm trying to display the name of the the computer and the key.

All works except my output also outputs the Searchbase with the computername.

Ex:CN=COMPUTERNAME,OU=FIRSTOU,OU=SECONDOU,OU=THIRDOU,DC=DOMAIN,DC=local

I only want/need the computername.

Get-AdObject -Filter "objectclass -eq 'msFVE-RecoveryInformation'" -Properties DistinguishedName , msFVE-RecoveryPassword, WhenCreated |
Select-Object -Property @{n="ComputerName";e={$_.DistinguishedName.Split(',',2)[1]}}, msFVE-RecoveryPassword | Export-csv c:\temp\compsAndKeys.csv

Not sure how to go about displaying Just the computername without the whole searchbase etc.

My actual intent is to search AD for computers that do have a bitlocker key and those that don't; so that I can bitlocker the ones that don't.

Thank You

Terry


Getting Object reference not set to an instance of an object. NullReferenceException when I try to run get-command

$
0
0

Greetings, powershell newbie. i have been going through a pluralsight course on powershell and trying to run the commands in the course. I am hitting an error running get-command, it returns the error shown below. I am running on windows 7 sp1  running powershell v3 which I just installed from v2.  I have also hit an error when running update-help. notice that get-command -listimported does work.  I am running the ise as admin, it gets the same errors either way. I have tried it from command window using powershell.exe, it is consistent and errors. I checked if I had a profile and I do not, using test-path $profile  it returned false. I have ran the update-help -force -erroraction silentlycontinue and it appears to update skipping some. Appreciate any help here.



Powershell - How to list Disk Activity Files column from Resource Monitor

$
0
0

Hello!

I'm trying to view the File column from the Disk Activity section of Resource Monitor. I've looked through several different pages of explanations on displaying Disk Activity information but nothing ever covers the File column. The different WMI classes people have used to get Disk Activity information are Win32_PerfFormattedData_PerfDisk_LogicalDisk, Win32_PerfRawData_PerfDisk_LogicalDisk, Win32_PerfFormattedData_PerfDisk_PhysicalDisk, and Win32_PerfRawData_PerfDisk_PhysicalDisk. I've explored these classes and can't find where I'd retrieve the File column info.

The different websites and blogs seem to provide all the Disk Activity information but never the File column or address why the File column information isn't provided. Is it even possible to access this information from Powershell? The screenshot below reflects the information I'm trying to gather. Thanks for the help!

So in Powershell, I imagine it'd look something like this:

Image          PID        File
-----              ---          ----
System         4           C:\ProgramData\CentraStage\...
System         4           E:\Video.Storage\d253...
svchost.ex... 4           C:\Windows\System32\...


How do I set a variable to the value contained in an ADGroup attribute?

$
0
0

Good evening. I'm trying to store the expected count of users in a group against the actual count. The plan is to use "extensionAttribute1" to store how many users should be in the group. I then want to query the count of members to compare and see if one is higher than the other (used to track owned licenses). I'm having no problem counting the group members, but I can't seem to set a variable to the attribute's value. Feel like this should be really easy. What am I doing wrong? My goal is to set $ExpectedMemberCount to the value stored in the attribute.

$ExpectedMemberCount = Get-ADGroup -Identity "DoNotDelete-ProductALicensedUsers" -Properties extensionAttribute1
$ExpectedMemberCount

Thanks in advance!


Find deleted objects from SP calendar

$
0
0

I am using the method to get list of object in calendar:

$web = $clientContext.Web
$list = $web.Lists.GetByTitle("Pages")
$clientContext.Load($list)
$clientContext.ExecuteQuery()

But, when getting all content of $list I am getting also the (Already) deleted objects from the Web portal (not showing anymore).

Need to get it PowerShell, I need to know which has been deleted a which is not.

Is there any option to find these deleted objects and filter them?

Thanks Tal

PowerShell - Searching Excel and replacing text

$
0
0

Hi all,

I am trying to figure out how to loop this script so that it replaces all the text that I am searching for in my Excel file.  I am able to get it to run but it only replaces the text in the first column and then ends. Any help is appreciated and thanks in advance.

-Gaz

$File="D:\test.xlsx"

# Setup Excel, open $File and set the the first worksheet
$Excel=New-Object-ComObjectExcel.Application
$Excel.visible=$true
$Workbook=$Excel.workbooks.open($file)
$Worksheets=$Workbooks.worksheets
$Worksheet=$Workbook.Worksheets.Item(1)

$SearchString="TEMP# This is the value that I will be searching for

$Range=$Worksheet.Range("A1").EntireColumn
$Search=$Range.find($SearchString)

$Search.value()="ABSENT"# This is the value that i want to replace the text with.

Connect to Sharepoint Online with Powershell and use error-handling

$
0
0

Hi,

I have a Powershell-script that makes a connection to SharePoint Online. When the user puts a wrong password, then it doesn't make a connection to SharePoint Online but still executes my script. I need to do a error-handling. This is my CSOM code:

$SiteUrl = "xxxxxxxxxxxxxxxxx"
$UserName="xxxxxxxxxxxxxxxx"
$Password ="xxxxxxxxxxxxxx"
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials

What do I have to put in the Try-catch code:

try
{

}
return;
}
catch (Exception ex)
{
throw;
    }
}

Gr. P

Creating a bat file

$
0
0
I want to create a batch file that can open multiple websites and enter text into each of those websites respective search boxes. 

Powershell Script - Export Services and Compare (before & after restart)

$
0
0

Hello All,

I hoping that someone can help me (I am terrible at coding and even worse at powershell). My team performs a lot of patching/restarting of Servers - currently before we begin we log onto each server and export the services, at the end of the restarts etc we log back in and export the services again and compare to ensure that they match.

I'm looking for a way to do this quicker/easier - I discussed with a colleague who advised that we can do this via powershell, unfortunately i've been unable to get it to work, I have no idea where to start.

What i'm thinking is:

A menu screen:

1 - WMI - Pre-Patching Exports

2 - WMI - Post-Patching Exports

3 - WMI - Comparison

4 - Get Service * - Pre-Patching Exports

5 - Get Service * - Post-Patching Exports

6 - Get Service * - Comparison

With each command reads the "Server/Computer Name" from a Text file, for example:

for each Computer in $Computers {Get Service *} export to $ComputerName Before.XML

Compare $ComputerName Before.xml and $ComputerName After.xml

If anyone could help that would be great!!

Powershell scripts failing with error There is not enough space on the disk

$
0
0

Hi All

I have a scenario where all my scripts are failing on my Orchestrator Windows 2016 server " There is not enough space on the disk".

What could be the issue. I also could see in the Operations manager log that even SCOM scripts are failing with the same error.


Justin


Assigning DHCP IP manually once allocated using powershell script

$
0
0

Hi There

In order to avoid client's going back to DHCP once IP is configured after provisioning. I am trying to automate manual assignment. As per our setup, Windows VMs are auto provisioned through the API on openstack platform and public IPs are configured through DHCP. Now as the client's go back to DHCP after every few minutes, any time there is any issue with DHCP server, all client's loose their IPs and the availability goes down. Thus I am trying to write a script which should first note the IP configuration in variables and then disable dhcp in client and then write the same variable on the network interface configurations thus the IP assigment is changed to manual and client does not have to go back to dhcp server again. Below is the script at the moment and I am stuck at one point.

$IP = Get-NetIPAddress -InterfaceAlias Ethernet -AddressFamily IPv4 | Select IPAddress
$Mask = Get-NetIPAddress -InterfaceAlias Ethernet -AddressFamily IPv4 | Select PrefixLength
$Gateway = Get-WmiObject win32_NetworkAdapterConfiguration | Select DefaultIPGateway
$IPType = "IPv4"
$Dns = "8.8.8.8"
$adapter = Get-NetAdapter | ? {$_.Status -eq "up"}
If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
 $adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
}
If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
 $adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
}
Set-NetIPInterface -DHCP Disabled
$adapter | New-NetIPAddress -AddressFamily $IPType -IPAddress $IP -PrefixLength $Mask.string -DefaultGateway $Gateway
$adapter | Set-DnsClientServerAddress -ServerAddresses $Dns

When I execute the above, It gives me an error

New-NetIPAddress : Invalid parameter IPv4Address @{IPAddress=xx.xx.xx.xx}
At line:1 char:1
+ New-NetIPAddress -AddressFamily $IPType -IPAddress $IP -PrefixLength $Mask.strin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddress) [New-NetIPAddr
   ess], CimException
    + FullyQualifiedErrorId : Windows System Error 87,New-NetIPAddress

Any advise would be highly appreciated.


need help with output for GUI + runspaces

$
0
0

Hi,

I'm working on a personnal project and try to learn about GUI and  runspaces for multithreading purpose.

I would like to run commands ( ping , os info, network info ...) for all computers in the listview " selected computers"   

open a runspacepool for each computer

the output (wich is different for each command) should be outputted in the listview "Output"

My issue if for the formating and the output data

any help would be very appreciated

here is a part of my code

 

##########################################################################################
# Load Assembly and Library
##########################################################################################

try{
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
} catch {
Throw "Failed to load Windows Presentation Framework assemblies."
}

##########################################################################################
# END Load Assembly and Library
##########################################################################################

##########################################################################################
# region Import Modules
##########################################################################################

try{
Import-Module ActiveDirectory
} catch {
Throw "Failed to import module active directoy"
}

try{
Import-Module DNSSERVER
} catch {
Throw "Failed to import module DNS SERVER"
}

##########################################################################################
# END region Import Modules
##########################################################################################


##########################################################################################
# region functions
##########################################################################################



##########################################################################################
# END region functions
##########################################################################################

#region Synchronized Collections
$runspace = [hashtable]::Synchronized(@{})
$ui = [hashtable]::Synchronized(@{})
$jobCleanup = [hashtable]::Synchronized(@{})
$jobs = [collections.arraylist]::Synchronized([collections.arraylist]@())
$collection = [hashtable]::Synchronized(@{})
#endregion Synchronized Collections

#region Extra things for Sync'ed Collections
$collection.ObservableCollection = New-Object System.Collections.ObjectModel.ObservableCollection[object]
$jobCleanup.Flag = $True
#endregion Extra things for Sync'ed Collections

#region UI Runspace Creation
$runspace.Runspace =[runspacefactory]::CreateRunspace()
$runspace.Runspace.ApartmentState = "STA"
$runspace.Runspace.Open()
$runspace.Runspace.SessionStateProxy.SetVariable("runspace",$runspace)
$runspace.Runspace.SessionStateProxy.SetVariable("ui",$ui)
$runspace.Runspace.SessionStateProxy.SetVariable("jobCleanup",$jobCleanup)
$runspace.Runspace.SessionStateProxy.SetVariable("jobs",$jobs)
$runspace.Runspace.SessionStateProxy.SetVariable("collection",$collection)
$runspace.PowerShell = [powershell]::Create().AddScript({
$ui.Error = $Error
#region Build the GUI
[xml]$xaml = @"
<Window
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'

Title="Admin Tools" Height="933" Width="1000">
<Grid Margin="-2,0,2,-1">
<Menu HorizontalAlignment="Left" Height="18" Margin="0,-2,0,0" VerticalAlignment="Top" Width="992" Grid.RowSpan="2" Grid.ColumnSpan="4">
<MenuItem Header="_File" Name="MainFile">
<MenuItem Header="_Edit ini file" Name="miini"/>
<Separator/>
<MenuItem Header="_Import a csv to queue" Name="miimp"/>
<MenuItem Header="_Export queue to csv" Name="miexp"/>
<Separator/>
<MenuItem Header="Exit" Name="miex"/>
</MenuItem>

<MenuItem Header="_Actions" Name="MainActions">
<MenuItem Header="_Use Others Credentials" Name="miuoc"/>
<MenuItem Header="_Connect Other Domain" Name="micod"/>
</MenuItem>

<MenuItem Header="_?" Name="MainQuestionMark">
<MenuItem Header="_?" Name="miqm"/>
<MenuItem Header="_About" Name="miab"/>
</MenuItem>
</Menu>
<StatusBar x:Name="SB1" HorizontalAlignment="Left" Height="27" Margin="0,876,0,0" VerticalAlignment="Top" Width="992" RenderTransformOrigin="-0.917,-0.06">
<StatusBar.ContextMenu>
<ContextMenu/>
</StatusBar.ContextMenu>
<StatusBarItem x:Name="LABEL_SB1" Content="Ready" Height="27" VerticalAlignment="Top"/>
</StatusBar>
<Label x:Name="label_user_connected_to" Content="User :" HorizontalAlignment="Left" Margin="0,21,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.311,-0.372"/>
<TextBox x:Name="TB_user_connected_to" HorizontalAlignment="Left" Height="23" Margin="45,25,0,0" TextWrapping="Wrap" Text="current_user" VerticalAlignment="Top" Width="97" RenderTransformOrigin="0.119,-0.607"/>
<Label x:Name="label_domain_connected_to" Content="connected to domain :" HorizontalAlignment="Left" Margin="156,22,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.311,-0.372"/>
<TextBox x:Name="TB_domain_connected_to" HorizontalAlignment="Left" Height="23" Margin="290,26,0,0" TextWrapping="Wrap" Text="current_domain" VerticalAlignment="Top" Width="221" RenderTransformOrigin="0.119,-0.607"/>
<TabControl x:Name="tabControl" HorizontalAlignment="Left" Height="823" Margin="0,53,0,0" VerticalAlignment="Top" Width="992" RenderTransformOrigin="-2.573,-0.982">
<TabItem x:Name="Tab_Computers" Header="Computers" Width="80" FontSize="11">
<Grid Background="#FFE5E5E5">
<Label x:Name="label_search_computers" Content="Search Computer(s) :" HorizontalAlignment="Left" VerticalAlignment="Top" RenderTransformOrigin="-0.291,-0.765" Width="123" Margin="0,5,0,0"/>
<TextBox x:Name="TB_Search_Computer" HorizontalAlignment="Left" Height="26" Margin="123,7,0,0" TextWrapping="Wrap" Text="Type hostname or IP address" VerticalAlignment="Top" Width="170" ToolTip=" Type hostname or IP address wildcard accepted"/>
<Button x:Name="BTN_Get_All_AD_Computers" Content="Get All AD Computers" HorizontalAlignment="Left" Margin="354,7,0,0" VerticalAlignment="Top" Width="114" RenderTransformOrigin="1.199,0.404" Height="26" ToolTip="Get all computers from active directory"/>
<Label x:Name="label_Founded_Computers" Content="Founded Computers :" HorizontalAlignment="Left" Margin="0,36,0,0" VerticalAlignment="Top" Width="127"/>

<ProgressBar x:Name="PB_Computers" HorizontalAlignment="Left" Height="18" Margin="0,781,0,0" VerticalAlignment="Top" Width="986" RenderTransformOrigin="-1.588,4.833"/>
<Label x:Name="label_Selected_Computers" Content="Selected Computers :" HorizontalAlignment="Left" Margin="0,287,0,0" VerticalAlignment="Top" Width="127"/>
<Label x:Name="label_Output_Computers" Content="Output :" HorizontalAlignment="Left" Margin="0,528,0,0" VerticalAlignment="Top" Width="127"/>
<Button x:Name="BTN_Add_Selected_Founded_Computers" Content="+" HorizontalAlignment="Left" Margin="298,163,0,0" VerticalAlignment="Top" Width="25" ToolTip="Add selected computers" RenderTransformOrigin="-0.225,0.602"/>
<Button x:Name="BTN_Add_All_Founded_Computers" Content="++" HorizontalAlignment="Left" Margin="298,197,0,0" VerticalAlignment="Top" Width="25" ToolTip="Add all computers" RenderTransformOrigin="0.532,-0.288"/>
<Button x:Name="BTN_Remove_Selected_Selected_Computers" Content="-" HorizontalAlignment="Left" Margin="298,312,0,0" VerticalAlignment="Top" Width="25" ToolTip="Remove selected computers" RenderTransformOrigin="0.32,-0.211"/>
<Button x:Name="BTN_Remove_All_Selected_Computers" Content="X" HorizontalAlignment="Left" Margin="298,340,0,0" VerticalAlignment="Top" Width="25" ToolTip="Remove all computers" RenderTransformOrigin="0.605,5.021"/>
<Button x:Name="BTN_Import_Computers_From_File" Content="File" HorizontalAlignment="Left" Margin="298,62,0,0" VerticalAlignment="Top" Width="25" ToolTip="Add computers From File"/>
<Button x:Name="BTN_Export_Computers_TO_File" Content="File" HorizontalAlignment="Left" Margin="298,480,0,0" VerticalAlignment="Top" Width="25" ToolTip="Export computers To File"/>
<Button x:Name="BTN_Ping" Content="Ping" HorizontalAlignment="Left" Margin="354,67,0,0" VerticalAlignment="Top" ToolTip="Test Connectivity" Width="105" Height="25"/>
<Button x:Name="BTN_OS_Info" Content="OS Infos" HorizontalAlignment="Left" Margin="354,109,0,0" VerticalAlignment="Top" ToolTip="Get infos related to OS" Width="105" Height="25"/>
<Button x:Name="BTN_Disk_Info" Content="DISK Infos" HorizontalAlignment="Left" Margin="354,146,0,0" VerticalAlignment="Top" ToolTip="Get infos related to disks" Width="105" Height="25"/>
<Button x:Name="BTN_Export_Output_Computers_TO_File" Content="Export To File :" HorizontalAlignment="Left" Margin="809,531,0,0" VerticalAlignment="Top" Width="81" ToolTip="Export Output To File"/>
<Button x:Name="BTN_Export_Output_Computers_TO_Mail" Content="Send by Mail" HorizontalAlignment="Left" Margin="897,531,0,0" VerticalAlignment="Top" Width="79" ToolTip="Send Output by mail"/>
<Button x:Name="BTN_Search_AD_Computers" Content="Search" HorizontalAlignment="Left" Margin="298,7,0,0" VerticalAlignment="Top" Width="51" RenderTransformOrigin="1.199,0.404" Height="26" ToolTip="search ad Computer"/>
<Label x:Name="label_Days_Computers" Content="Days :" HorizontalAlignment="Left" Margin="695,7,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.533,-0.347"/>
<TextBox x:Name="TB_Days_Computer_To_Delete" HorizontalAlignment="Left" Height="26" Margin="740,7,0,0" TextWrapping="Wrap" Text="days" VerticalAlignment="Top" Width="38"/>
<Button x:Name="BTN_Search_Days_Computers_To_Delete" Content="Search" HorizontalAlignment="Left" Margin="783,7,0,0" VerticalAlignment="Top" Width="51" RenderTransformOrigin="1.199,0.404" Height="26" ToolTip="search Computers not connected since numbers of days"/>
<Button x:Name="BTN_Cleanup_Days_Computers_To_Delete" Content="Cleanup" HorizontalAlignment="Left" Margin="839,7,0,0" VerticalAlignment="Top" Width="51" RenderTransformOrigin="1.199,0.404" Height="26" ToolTip="Cleanup Computers not connected since numbers of days"/>
<Button x:Name="BTN_ADD_AD_Computers" Content="ADD" HorizontalAlignment="Left" Margin="298,31,0,0" VerticalAlignment="Top" Width="51" RenderTransformOrigin="1.199,0.404" Height="26" ToolTip="search ad Computer"/>
<ListBox x:Name="LB_Founded_Computers" HorizontalAlignment="Left" Height="155" Margin="0,61,0,0" VerticalAlignment="Top" Width="298" AllowDrop="True" SelectionMode="Multiple"/>
<ListView x:Name="LV_Output_Computer" HorizontalAlignment="Left" Height="228" Margin="0,553,0,0" VerticalAlignment="Top" Width="986">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
<Button x:Name="BTN_Remove_Selected_founded_Computer" Content="-" HorizontalAlignment="Left" Margin="298,97,0,0" VerticalAlignment="Top" Width="25" ToolTip="Remove selected computers" RenderTransformOrigin="0.32,-0.211"/>
<Button x:Name="BTN_Remove_All_Founded_Computers" Content="X" HorizontalAlignment="Left" Margin="298,121,0,0" VerticalAlignment="Top" Width="25" ToolTip="Remove all computers" RenderTransformOrigin="0.605,5.021"/>
<StatusBar x:Name="SB_Founded_Computers" HorizontalAlignment="Left" Height="24" Margin="0,217,0,0" VerticalAlignment="Top" Width="298">
<StatusBarItem x:Name="LABEL_LB_Founded_Computers" Content="" Height="24" VerticalAlignment="Top"/>
</StatusBar>
<StatusBar x:Name="SB_Selected_Computers" HorizontalAlignment="Left" Height="24" Margin="0,499,0,0" VerticalAlignment="Top" Width="298">
<StatusBarItem x:Name="LABEL_SB_LV_Selected_Computers" Content="" Height="24" VerticalAlignment="Top"/>
</StatusBar>
<ListView x:Name="LV_Selected_Computers" HorizontalAlignment="Left" Height="189" Margin="0,310,0,0" VerticalAlignment="Top" Width="298" AllowDrop="True" IsManipulationEnabled="True">
<ListView.View>
<GridView x:Name="gv1" >
<GridViewColumn x:Name = 'name' Width = '150' DisplayMemberBinding = '{Binding Path = name}' Header='Hostname'/>
<GridViewColumn x:Name = 'IP_Address' Width = '148' DisplayMemberBinding = '{Binding Path = IP_Address}' Header='Ip_Address'/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</TabItem>
</TabControl>


</Grid>
</Window>

"@
#endregion Build the GUI

#region Background runspace to clean up jobs
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("jobCleanup",$jobCleanup)
$newRunspace.SessionStateProxy.SetVariable("jobs",$jobs)
$newRunspace.SessionStateProxy.SetVariable("ui",$ui)
$jobCleanup.PowerShell = [PowerShell]::Create().AddScript({
#Routine to handle completed runspaces
Do {
[System.Threading.Monitor]::Enter($Jobs.syncroot)
Foreach($runspace in $jobs) {
If ($runspace.Handle.isCompleted) {
$runspace.powershell.EndInvoke($runspace.Handle) | Out-Null
$runspace.powershell.dispose()
$runspace.Handle = $null
$runspace.powershell = $null
}
}
#Clean out unused runspace jobs
$temphash = $jobs.clone()
$temphash | Where {
$_.runspace -eq $Null
} | ForEach {
$jobs.remove($_)
}
[System.Threading.Monitor]::Exit($Jobs.syncroot)
Start-Sleep -Seconds 1
} while ($jobCleanup.Flag)
})
$jobCleanup.PowerShell.Runspace = $newRunspace
$jobCleanup.Thread = $jobCleanup.PowerShell.BeginInvoke()
#endregion


#region Create Variables


#-------------------------------------------------------------------------------------------------------------------------------


#$scriptDir = "c:\temp"
#-------------------------------------------------------------------------------------------------------------------------------
$date = get-date -f yyyy-MM-dd-hh_mm_ss
#-------------------------------------------------------------------------------------------------------------------------------


#endregion Create Variables


#region Connect to Controls

$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$ui.Window=[Windows.Markup.XamlReader]::Load( $reader )


$ui.TB_user_connected_to = $ui.Window.FindName('TB_user_connected_to')
$ui.TB_domain_connected_to = $ui.Window.FindName('TB_domain_connected_to')

$ui.SB1 = $ui.Window.FindName('SB1')
$ui.LABEL_SB1 = $ui.Window.FindName('LABEL_SB1')

$ui.TB_Search_Computer = $ui.Window.FindName('TB_Search_Computer')

$ui.LB_Founded_Computers = $ui.Window.FindName('LB_Founded_Computers')
$ui.SB_Founded_Computers = $ui.Window.FindName('SB_Founded_Computers')
$ui.LABEL_LB_Founded_Computers = $ui.Window.FindName('LABEL_LB_Founded_Computers')

$ui.LV_Selected_Computers = $ui.Window.FindName('LV_Selected_Computers')
$ui.SB_Selected_Computers = $ui.Window.FindName('SB_Selected_Computers')
$ui.LABEL_SB_LV_Selected_Computers = $ui.Window.FindName('LABEL_SB_LV_Selected_Computers')

$ui.BTN_ADD_AD_Computers = $ui.Window.FindName('BTN_ADD_AD_Computers')
$ui.BTN_Get_All_AD_Computers = $ui.Window.FindName('BTN_Get_All_AD_Computers')
$ui.BTN_Search_AD_Computers = $ui.Window.FindName('BTN_Search_AD_Computers')


$ui.BTN_Add_Selected_Founded_Computers = $ui.Window.FindName('BTN_Add_Selected_Founded_Computers')
$ui.BTN_Add_All_Founded_Computers = $ui.Window.FindName('BTN_Add_All_Founded_Computers')


$ui.LV_Output_Computer = $ui.Window.FindName('LV_Output_Computer')

$ui.PB_Computers = $ui.Window.FindName('PB_Computers')

$ui.BTN_Ping = $ui.Window.FindName('BTN_Ping')



#region UI Events



$ui.Window.Add_Loaded({
$ui.LV_Output_Computer.ItemsSource = $collection.ObservableCollection
})

$ui.TB_user_connected_to.Text = $env:USERNAME
$ui.TB_domain_connected_to.Text = $env:USERDNSDOMAIN

$ui.LABEL_SB1.content = "Ready"
$ui.LABEL_LB_Founded_Computers.content = ("List contains $($ui.LB_Founded_Computers.Items.Count) items")
$ui.LABEL_SB_LV_Selected_Computers.content = ("List contains $($ui.LABEL_SB_LV_Selected_Computers.Items.Count) items")

$ui.BTN_Add_Selected_Founded_Computers.Add_Click({
$ui.LB_Founded_Computers.selecteditems | foreach { $ui.LV_Selected_Computers.AddChild([pscustomobject]@{Name=$_}) }
$ui.LABEL_SB_LV_Selected_Computers.content = ("List contains $($ui.LV_Selected_Computers.Items.Count) items")
})

$ui.BTN_Add_All_Founded_Computers.Add_Click({
$ui.LB_Founded_Computers.items | foreach { $ui.LV_Selected_Computers.AddChild([pscustomobject]@{Name=$_}) }
$ui.LABEL_SB_LV_Selected_Computers.content = ("List contains $($ui.LV_Selected_Computers.Items.Count) items")
})

$ui.BTN_ADD_AD_Computers.Add_Click({
$ui.LB_Founded_Computers.Items.add($ui.TB_Search_Computer.text)
$ui.LABEL_LB_Founded_Computers.content = ("List contains $($ui.LB_Founded_Computers.Items.Count) items")
$ui.TB_Search_Computer.clear()
})

$ui.BTN_Ping.Add_Click({

$ui.PB_Computers.Value = 0
$ps = [powershell]::Create().AddScript({
Param ($Collection, $ui, $jobs)
$RunspacePool = [runspacefactory]::CreateRunspacePool(1,5)
$ScriptBlock = {
Param ($ui, $Collection)
$T = Test-Connection $_.name -count 1
$Name = ($T).Address
$IP = ($T).IPV4Address.ToString()

$Object += [pscustomobject]@{

TimeStart = (Get-Date).ToString()
Name = $Name
IP = $IP
Status = "status"

}


Start-Sleep -Seconds 2
$ui.LV_Output_Computer.Dispatcher.Invoke('Normal',[action]{
[void]$collection.observableCollection.Add($Object)
#[void]$ui.LV_Output_Computer.itemssource.add($Object)
$ui.PB_Computers.Value++
})
}
$servers = $ui.LV_Selected_Computers.Items
$servers | ForEach {
$ps = [powershell]::Create()
$ps.RunspacePool = $RunspacePool
$RunspacePool.Open()
[void]$ps.AddScript($ScriptBlock).AddArgument($ui).AddArgument($Collection)
[void]$jobs.Add([pscustomobject]@{
PowerShell = $Ps
Handle = $PS.BeginInvoke()
})
}
}).AddArgument($Collection).AddArgument($ui).AddArgument($jobs)

[System.Threading.Monitor]::Enter($Jobs.syncroot)
$jobs.Add([pscustomobject]@{
PowerShell = $ps
Handle = $Ps.BeginInvoke()
})
[System.Threading.Monitor]::Exit($Jobs.syncroot)
})


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

$ui.Window.Add_Closed({
#Halt job processing
$jobCleanup.Flag = $False

#Stop all runspaces
$jobCleanup.PowerShell.Dispose()

$runspace.PowerShell.Runspace.Close()
$runspace.PowerShell.Dispose()

[gc]::Collect()
[gc]::WaitForPendingFinalizers()
})
#endregion UI Events


[void]$ui.Window.ShowDialog()

})


$runspace.PowerShell.Runspace = $runspace.Runspace
$runspace.Handle = $runspace.PowerShell.BeginInvoke()
#endregion UI Runspace Creation

 

Cannot connect from W2016 Server

$
0
0

I am actually trying to setup the RDS role on a W2016 Server. It fails with cannot connect to remote powershell. I have gone through all the enable-PSremoting, disabling all group policies, disabling firewalls etc. but it keeps coming back to this error. Now I tested the remote capability of the server, and the strange thing is that I can access the remote powershell from a W2012 server just fine! I do Enter-PSSession -ComputerName <<W2016Servername>> on the W2012 server and it opens the session. Another W2016 server cannot connect, and this W2016 server cannot connect to the W2012 server either, while other W2012 servers can.

So the issue seems to be that the W2016 servers cannot start to build the connection to an external server, it is not the receiving end that is not working but the initiating side. Has anyone got any thoughts on this?

Thanks In Advance,

Kind Regards,

Theo Baarslag

Azure - App Service Plan - Scale Out

$
0
0

Starting at a new company and working with Developers and API's.

Found out that almost all of their scaling configurations are not setup correctly.  There are alot of App Service Plans.

Trying to find a way via PowerShell to get the Scale Out configuration of App Service Plans without any luck.  I have found examples where people have created the Scale Out configs, but nothing that pulls the existing scale out configurations. 

Or is there a better, non PowerShell way?  

Thanks in advance for any help.

Get-ADuser -filter emailaddress -like $mail

$
0
0

Howdy folks,

I have a PS script that gets the email address from a CSV and then it executes get-<g class="gr_ gr_87 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="87" id="87">aduser</g> to query for specific details.

The issue I have is that some entities in AD may have a similar or composed email address as the one I have in CSV and its evaluated against.

For example:

NT-username 1 has email address: test@test.com

NT-username 2 has email address:test2@test.com

foreach($mai in import-csv "C:\Users\ieuser\Desktop\users.csv") 
{
    $mail = $mai.mail
   # Write-Host $mail

    $members = Get-ADUser -properties name,GivenName,Surname,DisplayName,employeeNumber,EmailAddress,Title,Division,Department,co,OfficePhone,MobilePhone,employeetype,PasswordLastSet,enabled `
    -Filter {(EmailAddress -like $mail) -and (-not (employeetype -like "ADMIN")) -and (enabled -eq $true)} 

        $out = New-Object PSObject
        $out | Add-Member noteproperty 511 $members.Name
        $out | Add-Member noteproperty FirstName $members.GivenName
        $out | Add-Member noteproperty LastName $members.Surname
        $out | Add-Member noteproperty DisplayName $members.DisplayName
        $out | Add-Member noteproperty UPI $members.employeeNumber
}


When 2 or more users are found with the similar email address the result I get in the exported CSV is System.Object[].

I tried to modify the Filter parameter as below but without any success.

 -Filter {(EmailAddress -equal $mail)

or 
 -Filter {(EmailAddress -is $mail)

I'm looking for an operator if any that will validate against the exact email address and will dump results only for that email address not other that are derived or similar to it.

Any suggestion will be highly <g class="gr_ gr_549 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" data-gr-id="549" id="549">appreciated !</g>

Thank <g class="gr_ gr_562 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" data-gr-id="562" id="562">you !</g>

List folders N deep - List subfolders

$
0
0

I need to list subfolders two deep. It would seem I could do "Get-ChildItem\\test\test | Where { $_.PSIsContainer } | Select -Exp name" and pass those results into a variable and run a for each: "Get-ChildItem\\test\test\$var | Where { $_.PSIsContainer } | Select -Exp name"

However, is there a function out there that will accomplish what I need and perhaps is flexible enough to specify how deep to go?

Thank you,

Viewing all 21975 articles
Browse latest View live


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